ApproachOrderForm.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Cache;
  4. use common\helpers\Date;
  5. use common\components\Model;
  6. use common\helpers\Form;
  7. use common\helpers\LoggerTool;
  8. use common\helpers\PayStack;
  9. use common\helpers\user\Balance;
  10. use common\helpers\user\Cash;
  11. use common\helpers\user\Info;
  12. use common\libs\logging\operate\AdminOperate;
  13. use common\models\ApproachDecOrder;
  14. use common\models\ApproachOrder;
  15. use common\models\ApproachOrderGoods;
  16. use common\models\DealType;
  17. use common\models\DecLevelLog;
  18. use common\models\DecOrder;
  19. use common\models\Order;
  20. use common\models\OrderGoods;
  21. use common\models\Period;
  22. use common\models\ReceiveAddress;
  23. use common\models\Region;
  24. use common\models\ShopGoods;
  25. use common\models\User;
  26. use common\models\UserNetwork;
  27. use yii\base\Exception;
  28. /**
  29. * Login form
  30. */
  31. class ApproachOrderForm extends Model
  32. {
  33. public $sn;
  34. public $expressCompany;
  35. public $orderTrackNo;
  36. public $status;
  37. public $remark;
  38. public $note;
  39. public $type;
  40. public $addressId;
  41. public $payType;
  42. public $goodsId;
  43. public $goodsNum;
  44. public $payPassword;
  45. public $email;
  46. public $userName;
  47. public $consignee;
  48. public $acceptMobile;
  49. public $province;
  50. public $city;
  51. public $county;
  52. public $lgaName;
  53. public $cityName;
  54. public $detailaddress;
  55. private $_address;
  56. private $_decAmount;
  57. private $_decPv;
  58. private $_freight;
  59. private $_payAmount;
  60. private $_orderGoods;
  61. /**
  62. * @var ApproachOrder
  63. */
  64. private $_model;
  65. public function init() {
  66. parent::init();
  67. $this->adminOperateLogger = new AdminOperate([
  68. 'fetchClass' => ApproachOrder::class,
  69. ]);
  70. }
  71. /**
  72. * @inheritdoc
  73. */
  74. public function rules()
  75. {
  76. return [
  77. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
  78. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
  79. [['status'], 'isStatus'],
  80. [['addressId'], 'isAddress'],
  81. [['payType'], 'isPayType'],
  82. [['payPassword'], 'validatePassword'],
  83. ];
  84. }
  85. public function attributeLabels()
  86. {
  87. return [
  88. 'sn' => 'Order code',//订单号
  89. 'expressCompany' => 'ExpressCompany',//快递公司
  90. 'orderTrackNo' => 'courier number',//快递单号
  91. 'status' => 'status',//状态
  92. 'remark' => 'remark',//备注
  93. 'type' => 'order type',//订单类型
  94. 'addressId' => 'addressId',//收货地址
  95. 'payType' => 'payType',//支付方式
  96. 'goodsId' => 'Product ID',
  97. 'goodsNum' => 'Product quantity',//
  98. 'userName' => '复消会员编号',//复消会员编号
  99. 'consignee' => '收货人',//收货人
  100. 'acceptMobile' => '收货电话',//收货电话
  101. 'province' => '省',
  102. 'city' => '市',
  103. 'county' => '区',
  104. 'lgaName' => 'lga name',
  105. 'cityName' => 'City Name',
  106. 'detailaddress' => '收货详细地址',
  107. 'email' => 'Email',
  108. ];
  109. }
  110. /**
  111. * 指定校验场景
  112. * @return array
  113. */
  114. public function scenarios()
  115. {
  116. $parentScenarios = parent::scenarios();
  117. $customScenarios = [
  118. // 管理员修改订单状态
  119. 'adminStatus' => ['sn', 'status'],
  120. // 校验订单支付
  121. 'verifyPayStack' => ['sn', 'note', 'status'],
  122. // 会员下单
  123. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
  124. ];
  125. return array_merge($parentScenarios, $customScenarios);
  126. }
  127. /**
  128. * 校验之前
  129. * @return bool
  130. */
  131. public function beforeValidate()
  132. {
  133. $parentValidate = parent::beforeValidate();
  134. if ($this->sn) {
  135. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  136. if (!$this->_model){
  137. $this->addError('sn', '订单不存在');
  138. return false;
  139. }
  140. }
  141. if ($this->scenario == 'verifyPayStack'){
  142. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  143. $this->addError('sn', '订单支付状态错误');
  144. return false;
  145. }
  146. }
  147. return $parentValidate;
  148. }
  149. /**
  150. * 判断收货地址是否存在
  151. * @param $attribute
  152. */
  153. public function isAddress($attribute){
  154. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  155. $this->addError($attribute, '收货地址不存在');
  156. } else {
  157. $this->_address = $receiveAddress;
  158. }
  159. }
  160. /**
  161. * 校验支付密码
  162. * @param $attribute
  163. * @param $params
  164. */
  165. public function validatePassword($attribute, $params) {
  166. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  167. $this->addError($attribute, '支付密码不正确');
  168. }
  169. }
  170. /**
  171. * 判断支付方式
  172. * @param $attribute
  173. */
  174. public function isPayType($attribute)
  175. {
  176. if ($this->payType != 'pay_stack'){
  177. $this->addError($attribute, '只允许PayStack方式支付');
  178. return;
  179. }
  180. // 一个订单只能包含一类商品
  181. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  182. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  183. if (count($goodsCategoryType) != 1) {
  184. $this->addError($attribute, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
  185. return;
  186. }
  187. // 购买方式
  188. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  189. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  190. $this->addError($attribute, '不支持PayStack方式支付');
  191. return;
  192. }
  193. // 所选支付方式必须是商品分类支持的类型
  194. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  195. // 商品类型
  196. $currCategoryType = $goodsCategoryType[0];
  197. if (!array_key_exists($currCategoryType, $categoryType)) {
  198. $this->addError($attribute, '商品分类错误');
  199. return;
  200. }
  201. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  202. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  203. $this->addError($attribute, '支付方式错误3');
  204. }
  205. }
  206. /**
  207. * 校验类型
  208. * @param $attribute
  209. */
  210. public function isStatus($attribute){
  211. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  212. $this->addError($attribute, '订单状态类型错误');
  213. return ;
  214. }
  215. if ($this->scenario == 'adminStatus'){
  216. if ($this->status == $this->_model['STATUS']) {
  217. $this->addError($attribute, '订单状态没有改变');
  218. return ;
  219. }
  220. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  221. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  222. return ;
  223. }
  224. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  225. $this->addError($attribute, '订单已失效不能处理');
  226. return ;
  227. }
  228. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  229. $this->addError($attribute, '订单不能单独处理为物流状态');
  230. return ;
  231. }
  232. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  233. $this->addError($attribute, '订单已失效不能处理');
  234. return ;
  235. }
  236. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  237. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  238. $this->addError($attribute, '订单已完成不能取消');
  239. return ;
  240. }
  241. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  242. $this->addError($attribute, '订单已删除不能取消');
  243. return ;
  244. }
  245. }
  246. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  247. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  248. $this->addError($attribute, '订单已完成不能删除');
  249. return ;
  250. }
  251. }
  252. }
  253. }
  254. /**
  255. * 校验PayStack支付,更新订单状态.同步到正式订单.
  256. * @throws Exception
  257. */
  258. public function verifyPayStack(): ?ApproachOrder
  259. {
  260. if (!$this->validate()) {
  261. return null;
  262. }
  263. // 调用PayStack支付校验
  264. LoggerTool::info([$this->note['reference'], $this->note]);
  265. $payload = PayStack::transactionVerify($this->note['reference']);
  266. LoggerTool::info($payload);
  267. if ($payload['status'] !== true) {
  268. throw new Exception(Form::formatErrorsForApi($payload['message']));
  269. }
  270. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  271. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  272. }
  273. $db = \Yii::$app->db;
  274. $transaction = $db->beginTransaction();
  275. try {
  276. // 更新准订单状态为已支付
  277. $this->_model->STATUS = $this->status;
  278. $this->_model->NOTE = json_encode($this->note);
  279. $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
  280. $this->_model->EMAIL = $this->note['email'];
  281. if (!$this->_model->save()) {
  282. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  283. }
  284. // 更新订单商品的支付Email
  285. ApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  286. // 同步准订单到正式订单
  287. Order::insertOne($this->_model->toArray());
  288. // 同步准订单商品到正式订单商品
  289. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  290. foreach ($approachOrderGoods as &$approachOrderGood) {
  291. $approachOrderGood['EMAIL'] = $this->email;
  292. }
  293. OrderGoods::batchInsert($approachOrderGoods);
  294. // 同步报单
  295. $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  296. if ($approachDecOrder) {
  297. unset($approachDecOrder['STATUS']);
  298. // 同步报单
  299. DecOrder::insertOne($approachDecOrder);
  300. // 会员升级 报单类型:2会员升级单
  301. if ($approachDecOrder['DETAIL_TYPE'] == 2) {
  302. // 为被升级人进行升级操作
  303. $decLevelLog = new DecLevelLog();
  304. $decLog = [
  305. 'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
  306. 'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
  307. 'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
  308. 'actionId' => $approachDecOrder['USER_ID'],
  309. 'remark' => $approachDecOrder['REMARK'],
  310. 'lvPv' => $this->_model->PV,
  311. ];
  312. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  313. if (empty($modifyDecLv)) {
  314. $transaction->rollBack();
  315. throw new Exception("Failed to upgrade for member");//为会员升级失败
  316. }
  317. }
  318. }
  319. // 删除中间表
  320. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  321. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  322. ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  323. $transaction->commit();
  324. } catch (Exception $e) {
  325. $transaction->rollBack();
  326. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  327. return null;
  328. }
  329. return $this->_model;
  330. }
  331. /**
  332. * 复销
  333. * @throws Exception
  334. * @throws \yii\db\Exception
  335. */
  336. public function add(){
  337. if(!$this->validate()){
  338. return null;
  339. }
  340. $ids = $this->goodsId;
  341. $totalAmount = 0;
  342. $totalPv = 0;
  343. $goodsType = ShopGoods::GOODS_TYPE;
  344. foreach ($this->goodsNum as $k => $v) {
  345. if ($v) {
  346. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  347. if($goods['STORE_NUMS']>0){
  348. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  349. $discount = $goodsType[$goods['TYPE']]['discount'];
  350. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  351. $realPv = $goods['PRICE_PV'] * $discount/100;
  352. } else {
  353. $discount = $goods['SELL_DISCOUNT'];
  354. $realPrice = $goods['SELL_PRICE'] * $discount;
  355. $realPv = $goods['PRICE_PV'] * $discount;
  356. }
  357. $totalAmount += $realPrice * intval($v);
  358. $totalPv += $realPv * intval($v);
  359. $this->_orderGoods[] = [
  360. 'GOODS_ID' => $goods['ID'],
  361. 'PRICE' => $goods['SELL_PRICE'],
  362. 'PV' => $goods['PRICE_PV'],
  363. 'REAL_PRICE' => $realPrice,
  364. 'REAL_PV' => $realPv,
  365. 'POINT' => $goods['POINT'],
  366. 'BUY_NUMS' => intval($v),
  367. 'TAX_RATE' => $goods['TAX_RATE'],
  368. 'SKU_CODE' => $goods['GOODS_NO'],
  369. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  370. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  371. 'PAY_TYPE' => $this->payType,
  372. 'EMAIL' => $this->email,
  373. ];
  374. }
  375. }
  376. }
  377. // 汇率
  378. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  379. // 运费.奈拉
  380. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  381. // 普通商品免运费阈值.奈拉
  382. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  383. $this->_decAmount = $totalAmount;
  384. $this->_decPv = $totalPv;
  385. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  386. if($this->_address['PROVINCE']==1){
  387. $this->_freight = 0;
  388. }
  389. $this->_payAmount = $this->_decAmount + $this->_freight;
  390. $db = \Yii::$app->db;
  391. $transaction = $db->beginTransaction();
  392. try {
  393. //写入订单
  394. if (!$orderResult = $this->addOrder()) {
  395. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  396. }
  397. $transaction->commit();
  398. return $orderResult;
  399. }catch (\Exception $e){
  400. $transaction->rollBack();
  401. $this->addError('add', $e->getMessage());
  402. return null;
  403. }
  404. }
  405. /**
  406. * 复销订单
  407. * @throws Exception
  408. */
  409. public function addOrder()
  410. {
  411. $periodObj = Period::instance();
  412. $nowPeriodNum = $periodObj->getNowPeriodNum();
  413. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  414. $userId = \Yii::$app->user->id;
  415. $userName = Info::getUserNameByUserId($userId);
  416. $userRealName = Info::getUserRealNameByUserId($userId);
  417. $userMobile = Info::getUserMobileByUserId($userId);
  418. $userEmail = Info::getUserEmailByUserId($userId);
  419. // 加入订单信息
  420. if ($this->_address['PROVINCE'] != 1) {
  421. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  422. if (!$warehouse) {
  423. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  424. }
  425. }else{
  426. $warehouse = '01';
  427. }
  428. $_hasPV = $this->_decPv;
  429. $ordNo = $this->_generateSn();
  430. $orderModel = new ApproachOrder();
  431. $orderModel->SN = 'OS' . $ordNo;
  432. $orderModel->DEC_SN = 'DS' . $ordNo;
  433. $orderModel->ORDER_TYPE = $this->type;
  434. $orderModel->USER_ID = $userId;
  435. $orderModel->USER_NAME = $userName;
  436. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  437. $orderModel->PV = $_hasPV;
  438. $orderModel->PAY_AMOUNT = $this->_payAmount;
  439. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  440. $orderModel->PAY_AT = 0;
  441. $orderModel->PAY_TYPE = $this->payType;
  442. $orderModel->PERIOD_NUM = $nowPeriodNum;
  443. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  444. $orderModel->FREIGHT = $this->_freight;
  445. $orderModel->PAY_FREIGHT = $this->_freight;
  446. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  447. $orderModel->MOBILE = $this->_address['MOBILE'];
  448. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  449. // $orderModel->CITY = $this->_address['CITY'];
  450. // $orderModel->COUNTY = $this->_address['COUNTY'];
  451. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  452. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  453. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  454. $orderModel->FRONT_REMARK = $this->remark;
  455. $orderModel->WAREHOUSE = $warehouse;
  456. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  457. $orderModel->CREATED_AT = Date::nowTime();
  458. $orderModel->CREATE_USER = $userName;
  459. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
  460. if($this->_address['PROVINCE']==1){
  461. $orderModel->EXPRESS_TYPE = 1;
  462. $orderModel->CONSIGNEE = $userRealName;
  463. $orderModel->MOBILE = $userMobile;
  464. $orderModel->PROVINCE = 1;
  465. $orderModel->CITY = 1;
  466. $orderModel->COUNTY = 1;
  467. $orderModel->ADDRESS = '';
  468. }
  469. if(!$orderModel->save()){
  470. $this->addErrors($orderModel->getErrors());
  471. return false;
  472. }
  473. // 加入商品到订单商品表
  474. foreach($this->_orderGoods as $key=>$value) {
  475. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  476. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  477. }
  478. ApproachOrderGoods::batchInsert($this->_orderGoods);
  479. // TODO: 记录流水
  480. return $orderModel;
  481. }
  482. /**
  483. * 生成流水号
  484. * @return string
  485. */
  486. private function _generateSn() {
  487. return Date::today('Ymd') . $this->_random(10, 1);
  488. }
  489. /**
  490. * 生成随机数
  491. * @param $length
  492. * @param int $numeric
  493. * @return string
  494. */
  495. private function _random($length, $numeric = 0) {
  496. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  497. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  498. $hash = '';
  499. $max = strlen($seed) - 1;
  500. for ($i = 0; $i < $length; $i++) {
  501. $hash .= $seed[mt_rand(0, $max)];
  502. }
  503. return $hash;
  504. }
  505. }