BaApproachOrderForm.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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\BaApproachDecOrder;
  17. use common\models\BaApproachOrder;
  18. use common\models\BaApproachOrderGoods;
  19. use common\models\BaDecOrder;
  20. use common\models\BaOrder;
  21. use common\models\BaOrderGoods;
  22. use common\models\BaReceiveAddress;
  23. use common\models\BaUser;
  24. use common\models\DealType;
  25. use common\models\DecLevelLog;
  26. use common\models\DecOrder;
  27. use common\models\Order;
  28. use common\models\OrderGoods;
  29. use common\models\Period;
  30. use common\models\ReceiveAddress;
  31. use common\models\Region;
  32. use common\models\ShopGoods;
  33. use common\models\User;
  34. use common\models\UserNetwork;
  35. use Yii;
  36. use yii\base\Exception;
  37. /**
  38. * BAApproachOrderForm
  39. */
  40. class BaApproachOrderForm extends Model
  41. {
  42. public $sn;
  43. public $expressCompany;
  44. public $orderTrackNo;
  45. public $status;
  46. public $remark;
  47. public $note;
  48. public $type;
  49. public $addressId;
  50. public $payType;
  51. public $goodsId;
  52. public $goodsNum;
  53. public $payPassword;
  54. public $email;
  55. public $userName;
  56. public $consignee;
  57. public $acceptMobile;
  58. public $province;
  59. public $city;
  60. public $county;
  61. public $lgaName;
  62. public $cityName;
  63. public $detailaddress;
  64. private $_address;
  65. private $_decAmount;
  66. private $_decPv;
  67. private $_freight;
  68. private $_payAmount;
  69. private $_orderGoods;
  70. private $_model;
  71. public function init()
  72. {
  73. parent::init();
  74. $this->adminOperateLogger = new AdminOperate([
  75. 'fetchClass' => BaApproachOrder::class,
  76. ]);
  77. $this->payType = ShopGoods::getSaleType()[7]['label'];
  78. }
  79. /**
  80. * @inheritdoc
  81. */
  82. public function rules(): array
  83. {
  84. return [
  85. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','lgaName','cityName','detailaddress','email'], 'trim'],
  86. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','detailaddress'], 'required'],
  87. [['status'], 'isStatus'],
  88. [['addressId'], 'isAddress'],
  89. [['payPassword'], 'validatePassword'],
  90. ];
  91. }
  92. public function attributeLabels(): array
  93. {
  94. return [
  95. 'sn' => Yii::t('app', 'orderSn'),
  96. 'expressCompany' => Yii::t('app', 'expressCompany'),
  97. 'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
  98. 'status' => Yii::t('app', 'state'),
  99. 'remark' => Yii::t('app', 'remark'),
  100. 'type' => Yii::t('app', 'orderType'),
  101. 'addressId' => Yii::t('app', 'shippingAddress'),
  102. 'payType' => Yii::t('app', 'payType'),
  103. 'goodsId' => Yii::t('app', 'productID'),
  104. 'goodsNum' => Yii::t('app', 'quantity'),
  105. 'userName' => Yii::t('app', 'repeatSalesMemberNo'),
  106. 'consignee' => Yii::t('app', 'consignee'),
  107. 'acceptMobile' => Yii::t('app', 'acceptMobile'),
  108. 'lgaName' =>Yii::t('app', 'lgaName'),
  109. 'cityName' => Yii::t('app', 'cityName'),
  110. 'detailaddress' => Yii::t('app', 'detailAddress'),
  111. 'email' => Yii::t('app', 'email'),
  112. ];
  113. }
  114. /**
  115. * 指定校验场景
  116. * @return array
  117. */
  118. public function scenarios(): array
  119. {
  120. $parentScenarios = parent::scenarios();
  121. $customScenarios = [
  122. // 管理员修改订单状态
  123. 'adminStatus' => ['sn', 'status'],
  124. // 校验订单支付
  125. 'verifyPayStack' => ['sn', 'note', 'status'],
  126. // 会员下单
  127. 'userOrder' => ['type', 'addressId', 'goodsId', 'goodsNum', 'note', 'payPassword'],
  128. ];
  129. return array_merge($parentScenarios, $customScenarios);
  130. }
  131. /**
  132. * 校验之前
  133. * @return bool
  134. */
  135. public function beforeValidate()
  136. {
  137. $parentValidate = parent::beforeValidate();
  138. if ($this->sn) {
  139. $this->_model = BaApproachOrder::findOne(['SN' => $this->sn]);
  140. if (!$this->_model){
  141. $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
  142. return false;
  143. }
  144. }
  145. if ($this->scenario == 'verifyPayStack'){
  146. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  147. $this->addError('sn', Yii::t('app', 'payTypeError'));
  148. return false;
  149. }
  150. }
  151. return $parentValidate;
  152. }
  153. /**
  154. * 判断收货地址是否存在
  155. * @param $attribute
  156. * @param $params
  157. */
  158. public function isAddress($attribute, $params)
  159. {
  160. if (!$receiveAddress = BaReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  161. $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
  162. } else {
  163. $this->_address = $receiveAddress;
  164. }
  165. }
  166. /**
  167. * 校验支付密码
  168. * @param $attribute
  169. * @param $params
  170. */
  171. public function validatePassword($attribute, $params) {
  172. if (!BaUser::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  173. $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
  174. }
  175. }
  176. /**
  177. * 判断支付方式
  178. * @param $attribute
  179. */
  180. public function isPayType($attribute)
  181. {
  182. if ($this->payType != 'pay_stack'){
  183. $this->addError($attribute, '只允许PayStack方式支付');
  184. return;
  185. }
  186. // 一个订单只能包含一类商品
  187. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  188. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  189. if (count($goodsCategoryType) != 1) {
  190. $this->addError($attribute, Yii::t('app', 'orderCanNotContainMultipleProductCategories'));
  191. }
  192. }
  193. /**
  194. * 校验类型
  195. * @param $attribute
  196. */
  197. public function isStatus($attribute){
  198. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  199. $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
  200. return ;
  201. }
  202. if ($this->scenario == 'adminStatus'){
  203. if ($this->status == $this->_model['STATUS']) {
  204. $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
  205. return ;
  206. }
  207. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  208. $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
  209. return ;
  210. }
  211. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  212. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  213. return ;
  214. }
  215. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  216. $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
  217. return ;
  218. }
  219. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  220. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  221. return ;
  222. }
  223. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  224. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  225. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
  226. return ;
  227. }
  228. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  229. $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
  230. return ;
  231. }
  232. }
  233. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  234. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  235. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
  236. return ;
  237. }
  238. }
  239. }
  240. }
  241. /**
  242. * 校验PayStack支付,更新订单状态.同步到正式订单.
  243. * @throws Exception
  244. */
  245. public function verifyPayStack()
  246. {
  247. if (!$this->validate()) {
  248. return null;
  249. }
  250. // 调用PayStack支付校验
  251. LoggerTool::info([$this->note['reference'], $this->note]);
  252. $payload = PayStack::transactionVerify($this->note['reference']);
  253. LoggerTool::info($payload);
  254. if ($payload['status'] !== true) {
  255. throw new Exception(Form::formatErrorsForApi($payload['message']));
  256. }
  257. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  258. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'payAmountNotEqualOrderAmount')));
  259. }
  260. // 订单类型:baOrder(BA订单)、baDec(BA报单)
  261. $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
  262. $db = \Yii::$app->db;
  263. $transaction = $db->beginTransaction();
  264. try {
  265. // 更新准订单状态为已支付
  266. $this->_model->STATUS = $this->status;
  267. $this->_model->NOTE = json_encode($this->note);
  268. $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
  269. $this->_model->EMAIL = $this->note['email'];
  270. if (!$this->_model->save()) {
  271. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  272. }
  273. // 更新订单商品的支付Email
  274. BaApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  275. // 同步准订单到正式订单
  276. BaOrder::insertOne($this->_model->toArray());
  277. // 同步准订单商品到正式订单商品
  278. $approachOrderGoods = BaApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  279. foreach ($approachOrderGoods as &$approachOrderGood) {
  280. $approachOrderGood['EMAIL'] = $this->email;
  281. }
  282. BaOrderGoods::batchInsert($approachOrderGoods);
  283. // BA报单
  284. if ($orderType === 'baDec') {
  285. // 同步报单
  286. $approachDecOrder = BaApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  287. if ($approachDecOrder) {
  288. unset($approachDecOrder['STATUS']);
  289. // 同步报单
  290. BaDecOrder::insertOne($approachDecOrder);
  291. // 修改会员锁定状态
  292. if (!BaUser::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
  293. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'brandAmbassadorUpgradeError')));
  294. }
  295. }
  296. BaApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  297. }
  298. // 删除中间表
  299. BaApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  300. BaApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  301. $transaction->commit();
  302. } catch (Exception $e) {
  303. $transaction->rollBack();
  304. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  305. return null;
  306. }
  307. return $this->_model;
  308. }
  309. /**
  310. * 复销
  311. * @throws Exception
  312. */
  313. public function add()
  314. {
  315. if(!$this->validate()){
  316. return null;
  317. }
  318. $ids = $this->goodsId;
  319. $totalAmount = 0;
  320. $totalPv = 0;
  321. $goodsType = ShopGoods::getGoodType();
  322. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  323. foreach ($this->goodsNum as $k => $v) {
  324. if ($v) {
  325. $goods = ShopGoods::findOneAsArray('ID = :ID AND STATUS = 1', [':ID' => $ids[$k]]);
  326. if (!$goods) {
  327. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  328. }
  329. if ($goods['STORE_NUMS'] > 0) {
  330. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  331. $discount = $goodsType[$goods['TYPE']]['discount'];
  332. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  333. $realPv = $goods['PRICE_PV'] * $discount/100;
  334. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  335. } else {
  336. $discount = $goods['SELL_DISCOUNT'];
  337. $realPrice = $goods['SELL_PRICE'] * $discount;
  338. $realPv = $goods['PRICE_PV'] * $discount;
  339. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  340. }
  341. $totalAmount += $realPrice * intval($v);
  342. $totalPv += $realPv * intval($v);
  343. $this->_orderGoods[] = [
  344. 'GOODS_ID' => $goods['ID'],
  345. 'PRICE' => $goods['SELL_PRICE'],
  346. 'PV' => 0,
  347. 'REAL_PRICE' => $realPrice,
  348. 'REAL_PV' => 0,
  349. 'POINT' => 0,
  350. 'BUY_NUMS' => intval($v),
  351. 'TAX_RATE' => $goods['TAX_RATE'],
  352. 'SKU_CODE' => $goods['GOODS_NO'],
  353. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  354. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  355. 'PAY_TYPE' => $this->payType,
  356. 'EMAIL' => $this->email,
  357. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  358. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  359. 'EXCHANGE_RATE' => $exchangeRate,
  360. ];
  361. }
  362. }
  363. }
  364. // 运费.奈拉
  365. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  366. // 普通商品免运费阈值.奈拉
  367. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  368. $this->_decAmount = $totalAmount;
  369. $this->_decPv = $totalPv;
  370. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  371. $this->_payAmount = $this->_decAmount + $this->_freight;
  372. $db = \Yii::$app->db;
  373. $transaction = $db->beginTransaction();
  374. try {
  375. // 创建订单
  376. $orderResult = $this->addOrder();
  377. if (!$orderResult) {
  378. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  379. }
  380. $transaction->commit();
  381. return $orderResult;
  382. } catch (\Exception $e) {
  383. $transaction->rollBack();
  384. $this->addError('add', $e->getMessage());
  385. return null;
  386. }
  387. }
  388. /**
  389. * 复销订单
  390. * @throws Exception
  391. */
  392. public function addOrder()
  393. {
  394. $periodObj = Period::instance();
  395. $nowPeriodNum = $periodObj->getNowPeriodNum();
  396. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  397. $userId = \Yii::$app->user->id;
  398. $userName = Info::getBaUserNameByUserId($userId);
  399. $userMobile = Info::getBaUserMobileByUserId($userId);
  400. $userEmail = Info::getBaUserEmailByUserId($userId);
  401. // 加入订单信息
  402. if ($this->_address['PROVINCE'] != 1) {
  403. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  404. if (!$warehouse) {
  405. // throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  406. }
  407. }else{
  408. $warehouse = '01';
  409. }
  410. $_hasPV = 0;
  411. $ordNo = $this->_generateSn();
  412. $orderModel = new BaApproachOrder();
  413. $orderModel->SN = 'OS' . $ordNo;
  414. $orderModel->DEC_SN = 'DS' . $ordNo;
  415. $orderModel->ORDER_TYPE = $this->type;
  416. $orderModel->USER_ID = $userId;
  417. $orderModel->USER_NAME = $userName;
  418. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  419. $orderModel->PV = $_hasPV;
  420. $orderModel->PAY_AMOUNT = $this->_payAmount;
  421. $orderModel->PAY_PV = 0;
  422. $orderModel->PAY_AT = 0;
  423. $orderModel->PAY_TYPE = $this->payType;
  424. $orderModel->PERIOD_NUM = $nowPeriodNum;
  425. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  426. $orderModel->FREIGHT = $this->_freight;
  427. $orderModel->PAY_FREIGHT = $this->_freight;
  428. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'] ?: $userName;
  429. $orderModel->MOBILE = $this->_address['MOBILE'] ?: $userMobile;
  430. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  431. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  432. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  433. $orderModel->FRONT_REMARK = $this->remark;
  434. $orderModel->WAREHOUSE = $warehouse;
  435. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  436. $orderModel->CREATED_AT = Date::nowTime();
  437. $orderModel->CREATE_USER = $userName;
  438. $orderModel->EMAIL = $userEmail ?: $userName . '@elken.net';
  439. $orderModel->EXPRESS_TYPE = 1;
  440. $orderModel->PROVINCE = 1;
  441. $orderModel->CITY = 1;
  442. $orderModel->COUNTY = 1;
  443. if (!$orderModel->save()) {
  444. $this->addErrors($orderModel->getErrors());
  445. return false;
  446. }
  447. // 加入商品到订单商品表
  448. foreach($this->_orderGoods as $key => $value) {
  449. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  450. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  451. }
  452. BaApproachOrderGoods::batchInsert($this->_orderGoods);
  453. return $orderModel;
  454. }
  455. /**
  456. * 生成订单流水号
  457. * @return string
  458. */
  459. private function _generateSn(): string
  460. {
  461. return Date::today('Ymd') . $this->_random(10, 1);
  462. }
  463. /**
  464. * 生成随机数
  465. * @param $length
  466. * @param int $numeric
  467. * @return string
  468. */
  469. private function _random($length, int $numeric = 0): string
  470. {
  471. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  472. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  473. $hash = '';
  474. $max = strlen($seed) - 1;
  475. for ($i = 0; $i < $length; $i++) {
  476. $hash .= $seed[mt_rand(0, $max)];
  477. }
  478. return $hash;
  479. }
  480. }