BaApproachOrderForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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\BaUser;
  22. use common\models\DealType;
  23. use common\models\DecLevelLog;
  24. use common\models\DecOrder;
  25. use common\models\Order;
  26. use common\models\OrderGoods;
  27. use common\models\Period;
  28. use common\models\ReceiveAddress;
  29. use common\models\Region;
  30. use common\models\ShopGoods;
  31. use common\models\User;
  32. use common\models\UserNetwork;
  33. use yii\base\Exception;
  34. /**
  35. * BAApproachOrderForm
  36. */
  37. class BaApproachOrderForm extends Model
  38. {
  39. public $sn;
  40. public $expressCompany;
  41. public $orderTrackNo;
  42. public $status;
  43. public $remark;
  44. public $note;
  45. public $type;
  46. public $addressId;
  47. public $payType;
  48. public $goodsId;
  49. public $goodsNum;
  50. public $payPassword;
  51. public $email;
  52. public $userName;
  53. public $consignee;
  54. public $acceptMobile;
  55. public $province;
  56. public $city;
  57. public $county;
  58. public $lgaName;
  59. public $cityName;
  60. public $detailaddress;
  61. private $_address;
  62. private $_decAmount;
  63. private $_decPv;
  64. private $_freight;
  65. private $_payAmount;
  66. private $_orderGoods;
  67. private $_model;
  68. public function init()
  69. {
  70. parent::init();
  71. $this->adminOperateLogger = new AdminOperate([
  72. 'fetchClass' => BaApproachOrder::class,
  73. ]);
  74. $this->payType = ShopGoods::SALE_TYPE[7]['label'];
  75. }
  76. /**
  77. * @inheritdoc
  78. */
  79. public function rules(): array
  80. {
  81. return [
  82. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','lgaName','cityName','detailaddress','email'], 'trim'],
  83. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','detailaddress'], 'required'],
  84. [['status'], 'isStatus'],
  85. [['addressId'], 'isAddress'],
  86. [['payPassword'], 'validatePassword'],
  87. ];
  88. }
  89. public function attributeLabels(): array
  90. {
  91. return [
  92. 'sn' => 'Order code',//订单号
  93. 'expressCompany' => 'Express Company',//快递公司
  94. 'orderTrackNo' => 'Track Code',//快递单号
  95. 'status' => 'Status',//状态
  96. 'remark' => 'Remark',//备注
  97. 'type' => 'Order Type',//订单类型
  98. 'addressId' => 'AddressId',//收货地址
  99. 'payType' => 'PayType',//支付方式
  100. 'goodsId' => 'Product ID',// 商品编号
  101. 'goodsNum' => 'Quantity',//
  102. 'userName' => 'UserName',//复消会员编号
  103. 'consignee' => 'Consignee',//收货人
  104. 'acceptMobile' => 'Accept Mobile',//收货电话
  105. 'lgaName' => 'LgaName',
  106. 'cityName' => 'CityName',
  107. 'detailaddress' => 'Detail Address',// 收货详细地址
  108. 'email' => 'Email',
  109. ];
  110. }
  111. /**
  112. * 指定校验场景
  113. * @return array
  114. */
  115. public function scenarios(): array
  116. {
  117. $parentScenarios = parent::scenarios();
  118. $customScenarios = [
  119. // 管理员修改订单状态
  120. 'adminStatus' => ['sn', 'status'],
  121. // 校验订单支付
  122. 'verifyPayStack' => ['sn', 'note', 'status'],
  123. // 会员下单
  124. 'userOrder' => ['type', 'addressId', 'goodsId', 'goodsNum', 'note', 'payPassword'],
  125. ];
  126. return array_merge($parentScenarios, $customScenarios);
  127. }
  128. /**
  129. * 校验之前
  130. * @return bool
  131. */
  132. public function beforeValidate()
  133. {
  134. $parentValidate = parent::beforeValidate();
  135. if ($this->sn) {
  136. $this->_model = BaApproachOrder::findOne(['SN' => $this->sn]);
  137. if (!$this->_model){
  138. $this->addError('sn', 'Order does not exist');// 订单不存在
  139. return false;
  140. }
  141. }
  142. if ($this->scenario == 'verifyPayStack'){
  143. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  144. $this->addError('sn', '订单支付状态错误');
  145. return false;
  146. }
  147. }
  148. return $parentValidate;
  149. }
  150. /**
  151. * 判断收货地址是否存在
  152. * @param $attribute
  153. * @param $params
  154. */
  155. public function isAddress($attribute, $params)
  156. {
  157. if (!$receiveAddress = BaReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  158. $this->addError($attribute, 'Receive address does not exist'); // 收货地址不存在
  159. } else {
  160. $this->_address = $receiveAddress;
  161. }
  162. }
  163. /**
  164. * 校验支付密码
  165. * @param $attribute
  166. * @param $params
  167. */
  168. public function validatePassword($attribute, $params) {
  169. if (!BaUser::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()
  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. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  303. foreach ($this->goodsNum as $k => $v) {
  304. if ($v) {
  305. $goods = ShopGoods::findOneAsArray('ID = :ID AND STATUS = 1', [':ID' => $ids[$k]]);
  306. if ($goods['STORE_NUMS'] > 0) {
  307. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  308. $discount = $goodsType[$goods['TYPE']]['discount'];
  309. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  310. $realPv = $goods['PRICE_PV'] * $discount/100;
  311. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  312. } else {
  313. $discount = $goods['SELL_DISCOUNT'];
  314. $realPrice = $goods['SELL_PRICE'] * $discount;
  315. $realPv = $goods['PRICE_PV'] * $discount;
  316. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  317. }
  318. $totalAmount += $realPrice * intval($v);
  319. $totalPv += $realPv * intval($v);
  320. $this->_orderGoods[] = [
  321. 'GOODS_ID' => $goods['ID'],
  322. 'PRICE' => $goods['SELL_PRICE'],
  323. 'PV' => 0,
  324. 'REAL_PRICE' => $realPrice,
  325. 'REAL_PV' => 0,
  326. 'POINT' => 0,
  327. 'BUY_NUMS' => intval($v),
  328. 'TAX_RATE' => $goods['TAX_RATE'],
  329. 'SKU_CODE' => $goods['GOODS_NO'],
  330. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  331. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  332. 'PAY_TYPE' => $this->payType,
  333. 'EMAIL' => $this->email,
  334. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  335. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  336. 'EXCHANGE_RATE' => $exchangeRate,
  337. ];
  338. }
  339. }
  340. }
  341. // 运费.奈拉
  342. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  343. // 普通商品免运费阈值.奈拉
  344. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  345. $this->_decAmount = $totalAmount;
  346. $this->_decPv = $totalPv;
  347. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  348. $this->_payAmount = $this->_decAmount + $this->_freight;
  349. $db = \Yii::$app->db;
  350. $transaction = $db->beginTransaction();
  351. try {
  352. // 创建订单
  353. $orderResult = $this->addOrder();
  354. if (!$orderResult) {
  355. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  356. }
  357. $transaction->commit();
  358. return $orderResult;
  359. } catch (\Exception $e) {
  360. $transaction->rollBack();
  361. $this->addError('add', $e->getMessage());
  362. return null;
  363. }
  364. }
  365. /**
  366. * 复销订单
  367. * @throws Exception
  368. */
  369. public function addOrder()
  370. {
  371. $periodObj = Period::instance();
  372. $nowPeriodNum = $periodObj->getNowPeriodNum();
  373. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  374. $userId = \Yii::$app->user->id;
  375. $userName = Info::getBaUserNameByUserId($userId);
  376. $userMobile = Info::getBaUserMobileByUserId($userId);
  377. $userEmail = Info::getBaUserEmailByUserId($userId);
  378. // 加入订单信息
  379. if ($this->_address['PROVINCE'] != 1) {
  380. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  381. if (!$warehouse) {
  382. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  383. }
  384. }else{
  385. $warehouse = '01';
  386. }
  387. $_hasPV = 0;
  388. $ordNo = $this->_generateSn();
  389. $orderModel = new BaApproachOrder();
  390. $orderModel->SN = 'OS' . $ordNo;
  391. $orderModel->DEC_SN = 'DS' . $ordNo;
  392. $orderModel->ORDER_TYPE = $this->type;
  393. $orderModel->USER_ID = $userId;
  394. $orderModel->USER_NAME = $userName;
  395. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  396. $orderModel->PV = $_hasPV;
  397. $orderModel->PAY_AMOUNT = $this->_payAmount;
  398. $orderModel->PAY_PV = 0;
  399. $orderModel->PAY_AT = 0;
  400. $orderModel->PAY_TYPE = $this->payType;
  401. $orderModel->PERIOD_NUM = $nowPeriodNum;
  402. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  403. $orderModel->FREIGHT = $this->_freight;
  404. $orderModel->PAY_FREIGHT = $this->_freight;
  405. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'] ?: $userName;
  406. $orderModel->MOBILE = $this->_address['MOBILE'] ?: $userMobile;
  407. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  408. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  409. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  410. $orderModel->FRONT_REMARK = $this->remark;
  411. $orderModel->WAREHOUSE = $warehouse;
  412. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  413. $orderModel->CREATED_AT = Date::nowTime();
  414. $orderModel->CREATE_USER = $userName;
  415. $orderModel->EMAIL = $userEmail ?: $userName . '@elken.net';
  416. $orderModel->EXPRESS_TYPE = 1;
  417. $orderModel->PROVINCE = 1;
  418. $orderModel->CITY = 1;
  419. $orderModel->COUNTY = 1;
  420. if (!$orderModel->save()) {
  421. $this->addErrors($orderModel->getErrors());
  422. return false;
  423. }
  424. // 加入商品到订单商品表
  425. foreach($this->_orderGoods as $key => $value) {
  426. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  427. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  428. }
  429. BaApproachOrderGoods::batchInsert($this->_orderGoods);
  430. return $orderModel;
  431. }
  432. /**
  433. * 生成订单流水号
  434. * @return string
  435. */
  436. private function _generateSn(): string
  437. {
  438. return Date::today('Ymd') . $this->_random(10, 1);
  439. }
  440. /**
  441. * 生成随机数
  442. * @param $length
  443. * @param int $numeric
  444. * @return string
  445. */
  446. private function _random($length, int $numeric = 0): string
  447. {
  448. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  449. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  450. $hash = '';
  451. $max = strlen($seed) - 1;
  452. for ($i = 0; $i < $length; $i++) {
  453. $hash .= $seed[mt_rand(0, $max)];
  454. }
  455. return $hash;
  456. }
  457. }