BaApproachOrderForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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\BaApproachOrder;
  17. use common\models\BaApproachOrderGoods;
  18. use common\models\BaOrder;
  19. use common\models\BaOrderGoods;
  20. use common\models\BaReceiveAddress;
  21. use common\models\DealType;
  22. use common\models\DecLevelLog;
  23. use common\models\DecOrder;
  24. use common\models\Order;
  25. use common\models\OrderGoods;
  26. use common\models\Period;
  27. use common\models\ReceiveAddress;
  28. use common\models\Region;
  29. use common\models\ShopGoods;
  30. use common\models\User;
  31. use common\models\UserNetwork;
  32. use yii\base\Exception;
  33. /**
  34. * BAApproachOrderForm
  35. */
  36. class BaApproachOrderForm extends Model
  37. {
  38. public $sn;
  39. public $expressCompany;
  40. public $orderTrackNo;
  41. public $status;
  42. public $remark;
  43. public $note;
  44. public $type;
  45. public $addressId;
  46. public $payType;
  47. public $goodsId;
  48. public $goodsNum;
  49. public $payPassword;
  50. public $email;
  51. public $userName;
  52. public $consignee;
  53. public $acceptMobile;
  54. public $province;
  55. public $city;
  56. public $county;
  57. public $lgaName;
  58. public $cityName;
  59. public $detailaddress;
  60. private $_address;
  61. private $_decAmount;
  62. private $_decPv;
  63. private $_freight;
  64. private $_payAmount;
  65. private $_orderGoods;
  66. private $_model;
  67. public function init()
  68. {
  69. parent::init();
  70. $this->adminOperateLogger = new AdminOperate([
  71. 'fetchClass' => BaApproachOrder::class,
  72. ]);
  73. $this->payType = ShopGoods::SALE_TYPE[7]['label'];
  74. }
  75. /**
  76. * @inheritdoc
  77. */
  78. public function rules(): array
  79. {
  80. return [
  81. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','lgaName','cityName','detailaddress','email'], 'trim'],
  82. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','detailaddress'], 'required'],
  83. [['status'], 'isStatus'],
  84. [['addressId'], 'isAddress'],
  85. [['payPassword'], 'validatePassword'],
  86. ];
  87. }
  88. public function attributeLabels(): array
  89. {
  90. return [
  91. 'sn' => 'Order code',//订单号
  92. 'expressCompany' => 'Express Company',//快递公司
  93. 'orderTrackNo' => 'Track Code',//快递单号
  94. 'status' => 'Status',//状态
  95. 'remark' => 'Remark',//备注
  96. 'type' => 'Order Type',//订单类型
  97. 'addressId' => 'AddressId',//收货地址
  98. 'payType' => 'PayType',//支付方式
  99. 'goodsId' => 'Product ID',// 商品编号
  100. 'goodsNum' => 'Quantity',//
  101. 'userName' => 'UserName',//复消会员编号
  102. 'consignee' => 'Consignee',//收货人
  103. 'acceptMobile' => 'Accept Mobile',//收货电话
  104. 'lgaName' => 'LgaName',
  105. 'cityName' => 'CityName',
  106. 'detailaddress' => 'Detail Address',// 收货详细地址
  107. 'email' => 'Email',
  108. ];
  109. }
  110. /**
  111. * 指定校验场景
  112. * @return array
  113. */
  114. public function scenarios(): array
  115. {
  116. $parentScenarios = parent::scenarios();
  117. $customScenarios = [
  118. // 管理员修改订单状态
  119. 'adminStatus' => ['sn', 'status'],
  120. // 校验订单支付
  121. 'verifyPayStack' => ['sn', 'note', 'status'],
  122. // 会员下单
  123. 'userOrder' => ['type', 'addressId', '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 = BaApproachOrder::findOne(['SN' => $this->sn]);
  136. if (!$this->_model){
  137. $this->addError('sn', 'Order does not exist');// 订单不存在
  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. * @param $params
  153. */
  154. public function isAddress($attribute, $params)
  155. {
  156. if (!$receiveAddress = BaReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  157. $this->addError($attribute, 'Receive address does not exist'); // 收货地址不存在
  158. } else {
  159. $this->_address = $receiveAddress;
  160. }
  161. }
  162. /**
  163. * 校验支付密码
  164. * @param $attribute
  165. * @param $params
  166. */
  167. public function validatePassword($attribute, $params) {
  168. // TODO
  169. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  170. $this->addError($attribute, 'The payment password is incorrect');//支付密码不正确
  171. }
  172. }
  173. /**
  174. * 判断支付方式
  175. * @param $attribute
  176. */
  177. public function isPayType($attribute)
  178. {
  179. if ($this->payType != 'pay_stack'){
  180. $this->addError($attribute, '只允许PayStack方式支付');
  181. return;
  182. }
  183. // 一个订单只能包含一类商品
  184. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  185. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  186. if (count($goodsCategoryType) != 1) {
  187. $this->addError($attribute, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
  188. }
  189. }
  190. /**
  191. * 校验类型
  192. * @param $attribute
  193. */
  194. public function isStatus($attribute)
  195. {
  196. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  197. $this->addError($attribute, '订单状态类型错误');
  198. return ;
  199. }
  200. if ($this->scenario == 'adminStatus'){
  201. if ($this->status == $this->_model['STATUS']) {
  202. $this->addError($attribute, '订单状态没有改变');
  203. return ;
  204. }
  205. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  206. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  207. return ;
  208. }
  209. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  210. $this->addError($attribute, '订单已失效不能处理');
  211. return ;
  212. }
  213. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  214. $this->addError($attribute, '订单不能单独处理为物流状态');
  215. return ;
  216. }
  217. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  218. $this->addError($attribute, '订单已失效不能处理');
  219. return ;
  220. }
  221. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  222. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  223. $this->addError($attribute, '订单已完成不能取消');
  224. return ;
  225. }
  226. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  227. $this->addError($attribute, '订单已删除不能取消');
  228. return ;
  229. }
  230. }
  231. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  232. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  233. $this->addError($attribute, '订单已完成不能删除');
  234. return ;
  235. }
  236. }
  237. }
  238. }
  239. /**
  240. * 校验PayStack支付,更新订单状态.同步到正式订单.
  241. * @throws Exception
  242. */
  243. public function verifyPayStack(): ?ApproachOrder
  244. {
  245. if (!$this->validate()) {
  246. return null;
  247. }
  248. // 调用PayStack支付校验
  249. LoggerTool::info([$this->note['reference'], $this->note]);
  250. $payload = PayStack::transactionVerify($this->note['reference']);
  251. LoggerTool::info($payload);
  252. if ($payload['status'] !== true) {
  253. throw new Exception(Form::formatErrorsForApi($payload['message']));
  254. }
  255. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  256. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  257. }
  258. $db = \Yii::$app->db;
  259. $transaction = $db->beginTransaction();
  260. try {
  261. // 更新准订单状态为已支付
  262. $this->_model->STATUS = $this->status;
  263. $this->_model->NOTE = json_encode($this->note);
  264. $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
  265. $this->_model->EMAIL = $this->note['email'];
  266. if (!$this->_model->save()) {
  267. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  268. }
  269. // 更新订单商品的支付Email
  270. BaApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  271. // 同步准订单到正式订单
  272. BaOrder::insertOne($this->_model->toArray());
  273. // 同步准订单商品到正式订单商品
  274. $approachOrderGoods = BaApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  275. foreach ($approachOrderGoods as &$approachOrderGood) {
  276. $approachOrderGood['EMAIL'] = $this->email;
  277. }
  278. BaOrderGoods::batchInsert($approachOrderGoods);
  279. // 删除中间表
  280. BaApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  281. BaApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  282. $transaction->commit();
  283. } catch (Exception $e) {
  284. $transaction->rollBack();
  285. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  286. return null;
  287. }
  288. return $this->_model;
  289. }
  290. /**
  291. * 复销
  292. */
  293. public function add()
  294. {
  295. if(!$this->validate()){
  296. return null;
  297. }
  298. $ids = $this->goodsId;
  299. $totalAmount = 0;
  300. $totalPv = 0;
  301. $goodsType = ShopGoods::GOODS_TYPE;
  302. foreach ($this->goodsNum as $k => $v) {
  303. if ($v) {
  304. $goods = ShopGoods::findOneAsArray('ID = :ID AND STATUS = 1', [':ID' => $ids[$k]]);
  305. if ($goods['STORE_NUMS'] > 0) {
  306. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  307. $discount = $goodsType[$goods['TYPE']]['discount'];
  308. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  309. $realPv = $goods['PRICE_PV'] * $discount/100;
  310. } else {
  311. $discount = $goods['SELL_DISCOUNT'];
  312. $realPrice = $goods['SELL_PRICE'] * $discount;
  313. $realPv = $goods['PRICE_PV'] * $discount;
  314. }
  315. $totalAmount += $realPrice * intval($v);
  316. $totalPv += $realPv * intval($v);
  317. $this->_orderGoods[] = [
  318. 'GOODS_ID' => $goods['ID'],
  319. 'PRICE' => $goods['SELL_PRICE'],
  320. 'PV' => 0,
  321. 'REAL_PRICE' => $realPrice,
  322. 'REAL_PV' => 0,
  323. 'POINT' => 0,
  324. 'BUY_NUMS' => intval($v),
  325. 'TAX_RATE' => $goods['TAX_RATE'],
  326. 'SKU_CODE' => $goods['GOODS_NO'],
  327. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  328. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  329. 'PAY_TYPE' => $this->payType,
  330. 'EMAIL' => $this->email,
  331. ];
  332. }
  333. }
  334. }
  335. // 运费.奈拉
  336. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  337. // 普通商品免运费阈值.奈拉
  338. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  339. $this->_decAmount = $totalAmount;
  340. $this->_decPv = $totalPv;
  341. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  342. $this->_payAmount = $this->_decAmount + $this->_freight;
  343. $db = \Yii::$app->db;
  344. $transaction = $db->beginTransaction();
  345. try {
  346. // 创建订单
  347. $orderResult = $this->addOrder();
  348. if (!$orderResult) {
  349. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  350. }
  351. $transaction->commit();
  352. return $orderResult;
  353. } catch (\Exception $e) {
  354. $transaction->rollBack();
  355. $this->addError('add', $e->getMessage());
  356. return null;
  357. }
  358. }
  359. /**
  360. * 复销订单
  361. * @throws Exception
  362. */
  363. public function addOrder()
  364. {
  365. $periodObj = Period::instance();
  366. $nowPeriodNum = $periodObj->getNowPeriodNum();
  367. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  368. $userId = \Yii::$app->user->id;
  369. $userName = Info::getUserNameByUserId($userId); // TODO
  370. $userMobile = Info::getUserMobileByUserId($userId); // TODO
  371. $userEmail = Info::getUserEmailByUserId($userId); // TODO
  372. // 加入订单信息
  373. if ($this->_address['PROVINCE'] != 1) {
  374. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  375. if (!$warehouse) {
  376. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  377. }
  378. }else{
  379. $warehouse = '01';
  380. }
  381. $_hasPV = 0;
  382. $ordNo = $this->_generateSn();
  383. $orderModel = new BaApproachOrder();
  384. $orderModel->SN = 'OS' . $ordNo;
  385. $orderModel->DEC_SN = 'DS' . $ordNo;
  386. $orderModel->ORDER_TYPE = $this->type;
  387. $orderModel->USER_ID = $userId;
  388. $orderModel->USER_NAME = $userName;
  389. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  390. $orderModel->PV = $_hasPV;
  391. $orderModel->PAY_AMOUNT = $this->_payAmount;
  392. $orderModel->PAY_PV = 0;
  393. $orderModel->PAY_AT = 0;
  394. $orderModel->PAY_TYPE = $this->payType;
  395. $orderModel->PERIOD_NUM = $nowPeriodNum;
  396. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  397. $orderModel->FREIGHT = $this->_freight;
  398. $orderModel->PAY_FREIGHT = $this->_freight;
  399. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'] ?: $userName;
  400. $orderModel->MOBILE = $this->_address['MOBILE'] ?: $userMobile;
  401. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  402. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  403. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  404. $orderModel->FRONT_REMARK = $this->remark;
  405. $orderModel->WAREHOUSE = $warehouse;
  406. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  407. $orderModel->CREATED_AT = Date::nowTime();
  408. $orderModel->CREATE_USER = $userName;
  409. $orderModel->EMAIL = $userEmail ?: $userName . '@elken.net';
  410. $orderModel->EXPRESS_TYPE = 1;
  411. $orderModel->PROVINCE = 1;
  412. $orderModel->CITY = 1;
  413. $orderModel->COUNTY = 1;
  414. if (!$orderModel->save()) {
  415. $this->addErrors($orderModel->getErrors());
  416. return false;
  417. }
  418. // 加入商品到订单商品表
  419. foreach($this->_orderGoods as $key => $value) {
  420. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  421. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  422. }
  423. BaApproachOrderGoods::batchInsert($this->_orderGoods);
  424. return $orderModel;
  425. }
  426. /**
  427. * 生成订单流水号
  428. * @return string
  429. */
  430. private function _generateSn(): string
  431. {
  432. return Date::today('Ymd') . $this->_random(10, 1);
  433. }
  434. /**
  435. * 生成随机数
  436. * @param $length
  437. * @param int $numeric
  438. * @return string
  439. */
  440. private function _random($length, int $numeric = 0): string
  441. {
  442. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  443. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  444. $hash = '';
  445. $max = strlen($seed) - 1;
  446. for ($i = 0; $i < $length; $i++) {
  447. $hash .= $seed[mt_rand(0, $max)];
  448. }
  449. return $hash;
  450. }
  451. }