ApproachOrderForm.php 19 KB

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