BaApproachOrderForm.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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\base\Exception;
  36. /**
  37. * BAApproachOrderForm
  38. */
  39. class BaApproachOrderForm extends Model
  40. {
  41. public $sn;
  42. public $expressCompany;
  43. public $orderTrackNo;
  44. public $status;
  45. public $remark;
  46. public $note;
  47. public $type;
  48. public $addressId;
  49. public $payType;
  50. public $goodsId;
  51. public $goodsNum;
  52. public $payPassword;
  53. public $email;
  54. public $userName;
  55. public $consignee;
  56. public $acceptMobile;
  57. public $province;
  58. public $city;
  59. public $county;
  60. public $lgaName;
  61. public $cityName;
  62. public $detailaddress;
  63. private $_address;
  64. private $_decAmount;
  65. private $_decPv;
  66. private $_freight;
  67. private $_payAmount;
  68. private $_orderGoods;
  69. private $_model;
  70. public function init()
  71. {
  72. parent::init();
  73. $this->adminOperateLogger = new AdminOperate([
  74. 'fetchClass' => BaApproachOrder::class,
  75. ]);
  76. $this->payType = ShopGoods::SALE_TYPE[7]['label'];
  77. }
  78. /**
  79. * @inheritdoc
  80. */
  81. public function rules(): array
  82. {
  83. return [
  84. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','lgaName','cityName','detailaddress','email'], 'trim'],
  85. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','detailaddress'], 'required'],
  86. [['status'], 'isStatus'],
  87. [['addressId'], 'isAddress'],
  88. [['payPassword'], 'validatePassword'],
  89. ];
  90. }
  91. public function attributeLabels(): array
  92. {
  93. return [
  94. 'sn' => 'Order code',//订单号
  95. 'expressCompany' => 'Express Company',//快递公司
  96. 'orderTrackNo' => 'Track Code',//快递单号
  97. 'status' => 'Status',//状态
  98. 'remark' => 'Remark',//备注
  99. 'type' => 'Order Type',//订单类型
  100. 'addressId' => 'AddressId',//收货地址
  101. 'payType' => 'PayType',//支付方式
  102. 'goodsId' => 'Product ID',// 商品编号
  103. 'goodsNum' => 'Quantity',//
  104. 'userName' => 'UserName',//复消会员编号
  105. 'consignee' => 'Consignee',//收货人
  106. 'acceptMobile' => 'Accept Mobile',//收货电话
  107. 'lgaName' => 'LgaName',
  108. 'cityName' => 'CityName',
  109. 'detailaddress' => 'Detail Address',// 收货详细地址
  110. 'email' => 'Email',
  111. ];
  112. }
  113. /**
  114. * 指定校验场景
  115. * @return array
  116. */
  117. public function scenarios(): array
  118. {
  119. $parentScenarios = parent::scenarios();
  120. $customScenarios = [
  121. // 管理员修改订单状态
  122. 'adminStatus' => ['sn', 'status'],
  123. // 校验订单支付
  124. 'verifyPayStack' => ['sn', 'note', 'status'],
  125. // 会员下单
  126. 'userOrder' => ['type', 'addressId', 'goodsId', 'goodsNum', 'note', 'payPassword'],
  127. ];
  128. return array_merge($parentScenarios, $customScenarios);
  129. }
  130. /**
  131. * 校验之前
  132. * @return bool
  133. */
  134. public function beforeValidate()
  135. {
  136. $parentValidate = parent::beforeValidate();
  137. if ($this->sn) {
  138. $this->_model = BaApproachOrder::findOne(['SN' => $this->sn]);
  139. if (!$this->_model){
  140. $this->addError('sn', 'Order does not exist');// 订单不存在
  141. return false;
  142. }
  143. }
  144. if ($this->scenario == 'verifyPayStack'){
  145. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  146. $this->addError('sn', '订单支付状态错误');
  147. return false;
  148. }
  149. }
  150. return $parentValidate;
  151. }
  152. /**
  153. * 判断收货地址是否存在
  154. * @param $attribute
  155. * @param $params
  156. */
  157. public function isAddress($attribute, $params)
  158. {
  159. if (!$receiveAddress = BaReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  160. $this->addError($attribute, 'Receive address does not exist'); // 收货地址不存在
  161. } else {
  162. $this->_address = $receiveAddress;
  163. }
  164. }
  165. /**
  166. * 校验支付密码
  167. * @param $attribute
  168. * @param $params
  169. */
  170. public function validatePassword($attribute, $params) {
  171. if (!BaUser::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  172. $this->addError($attribute, 'The payment password is incorrect');//支付密码不正确
  173. }
  174. }
  175. /**
  176. * 判断支付方式
  177. * @param $attribute
  178. */
  179. public function isPayType($attribute)
  180. {
  181. if ($this->payType != 'pay_stack'){
  182. $this->addError($attribute, '只允许PayStack方式支付');
  183. return;
  184. }
  185. // 一个订单只能包含一类商品
  186. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  187. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  188. if (count($goodsCategoryType) != 1) {
  189. $this->addError($attribute, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
  190. }
  191. }
  192. /**
  193. * 校验类型
  194. * @param $attribute
  195. */
  196. public function isStatus($attribute)
  197. {
  198. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  199. $this->addError($attribute, '订单状态类型错误');
  200. return ;
  201. }
  202. if ($this->scenario == 'adminStatus'){
  203. if ($this->status == $this->_model['STATUS']) {
  204. $this->addError($attribute, '订单状态没有改变');
  205. return ;
  206. }
  207. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  208. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  209. return ;
  210. }
  211. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  212. $this->addError($attribute, '订单已失效不能处理');
  213. return ;
  214. }
  215. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  216. $this->addError($attribute, '订单不能单独处理为物流状态');
  217. return ;
  218. }
  219. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  220. $this->addError($attribute, '订单已失效不能处理');
  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, '订单已完成不能取消');
  226. return ;
  227. }
  228. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  229. $this->addError($attribute, '订单已删除不能取消');
  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, '订单已完成不能删除');
  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('支付金额与订单金额不符'));
  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('Update Brand Ambassador status error'));
  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. */
  312. public function add()
  313. {
  314. if(!$this->validate()){
  315. return null;
  316. }
  317. $ids = $this->goodsId;
  318. $totalAmount = 0;
  319. $totalPv = 0;
  320. $goodsType = ShopGoods::GOODS_TYPE;
  321. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  322. foreach ($this->goodsNum as $k => $v) {
  323. if ($v) {
  324. $goods = ShopGoods::findOneAsArray('ID = :ID AND STATUS = 1', [':ID' => $ids[$k]]);
  325. if ($goods['STORE_NUMS'] > 0) {
  326. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  327. $discount = $goodsType[$goods['TYPE']]['discount'];
  328. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  329. $realPv = $goods['PRICE_PV'] * $discount/100;
  330. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  331. } else {
  332. $discount = $goods['SELL_DISCOUNT'];
  333. $realPrice = $goods['SELL_PRICE'] * $discount;
  334. $realPv = $goods['PRICE_PV'] * $discount;
  335. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  336. }
  337. $totalAmount += $realPrice * intval($v);
  338. $totalPv += $realPv * intval($v);
  339. $this->_orderGoods[] = [
  340. 'GOODS_ID' => $goods['ID'],
  341. 'PRICE' => $goods['SELL_PRICE'],
  342. 'PV' => 0,
  343. 'REAL_PRICE' => $realPrice,
  344. 'REAL_PV' => 0,
  345. 'POINT' => 0,
  346. 'BUY_NUMS' => intval($v),
  347. 'TAX_RATE' => $goods['TAX_RATE'],
  348. 'SKU_CODE' => $goods['GOODS_NO'],
  349. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  350. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  351. 'PAY_TYPE' => $this->payType,
  352. 'EMAIL' => $this->email,
  353. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  354. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  355. 'EXCHANGE_RATE' => $exchangeRate,
  356. ];
  357. }
  358. }
  359. }
  360. // 运费.奈拉
  361. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  362. // 普通商品免运费阈值.奈拉
  363. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  364. $this->_decAmount = $totalAmount;
  365. $this->_decPv = $totalPv;
  366. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  367. $this->_payAmount = $this->_decAmount + $this->_freight;
  368. $db = \Yii::$app->db;
  369. $transaction = $db->beginTransaction();
  370. try {
  371. // 创建订单
  372. $orderResult = $this->addOrder();
  373. if (!$orderResult) {
  374. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  375. }
  376. $transaction->commit();
  377. return $orderResult;
  378. } catch (\Exception $e) {
  379. $transaction->rollBack();
  380. $this->addError('add', $e->getMessage());
  381. return null;
  382. }
  383. }
  384. /**
  385. * 复销订单
  386. * @throws Exception
  387. */
  388. public function addOrder()
  389. {
  390. $periodObj = Period::instance();
  391. $nowPeriodNum = $periodObj->getNowPeriodNum();
  392. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  393. $userId = \Yii::$app->user->id;
  394. $userName = Info::getBaUserNameByUserId($userId);
  395. $userMobile = Info::getBaUserMobileByUserId($userId);
  396. $userEmail = Info::getBaUserEmailByUserId($userId);
  397. // 加入订单信息
  398. if ($this->_address['PROVINCE'] != 1) {
  399. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  400. if (!$warehouse) {
  401. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  402. }
  403. }else{
  404. $warehouse = '01';
  405. }
  406. $_hasPV = 0;
  407. $ordNo = $this->_generateSn();
  408. $orderModel = new BaApproachOrder();
  409. $orderModel->SN = 'OS' . $ordNo;
  410. $orderModel->DEC_SN = 'DS' . $ordNo;
  411. $orderModel->ORDER_TYPE = $this->type;
  412. $orderModel->USER_ID = $userId;
  413. $orderModel->USER_NAME = $userName;
  414. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  415. $orderModel->PV = $_hasPV;
  416. $orderModel->PAY_AMOUNT = $this->_payAmount;
  417. $orderModel->PAY_PV = 0;
  418. $orderModel->PAY_AT = 0;
  419. $orderModel->PAY_TYPE = $this->payType;
  420. $orderModel->PERIOD_NUM = $nowPeriodNum;
  421. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  422. $orderModel->FREIGHT = $this->_freight;
  423. $orderModel->PAY_FREIGHT = $this->_freight;
  424. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'] ?: $userName;
  425. $orderModel->MOBILE = $this->_address['MOBILE'] ?: $userMobile;
  426. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  427. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  428. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  429. $orderModel->FRONT_REMARK = $this->remark;
  430. $orderModel->WAREHOUSE = $warehouse;
  431. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  432. $orderModel->CREATED_AT = Date::nowTime();
  433. $orderModel->CREATE_USER = $userName;
  434. $orderModel->EMAIL = $userEmail ?: $userName . '@elken.net';
  435. $orderModel->EXPRESS_TYPE = 1;
  436. $orderModel->PROVINCE = 1;
  437. $orderModel->CITY = 1;
  438. $orderModel->COUNTY = 1;
  439. if (!$orderModel->save()) {
  440. $this->addErrors($orderModel->getErrors());
  441. return false;
  442. }
  443. // 加入商品到订单商品表
  444. foreach($this->_orderGoods as $key => $value) {
  445. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  446. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  447. }
  448. BaApproachOrderGoods::batchInsert($this->_orderGoods);
  449. return $orderModel;
  450. }
  451. /**
  452. * 生成订单流水号
  453. * @return string
  454. */
  455. private function _generateSn(): string
  456. {
  457. return Date::today('Ymd') . $this->_random(10, 1);
  458. }
  459. /**
  460. * 生成随机数
  461. * @param $length
  462. * @param int $numeric
  463. * @return string
  464. */
  465. private function _random($length, int $numeric = 0): string
  466. {
  467. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  468. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  469. $hash = '';
  470. $max = strlen($seed) - 1;
  471. for ($i = 0; $i < $length; $i++) {
  472. $hash .= $seed[mt_rand(0, $max)];
  473. }
  474. return $hash;
  475. }
  476. }