ApproachOrderForm.php 18 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\user\Info;
  9. use common\libs\logging\operate\AdminOperate;
  10. use common\models\ApproachOrder;
  11. use common\models\ApproachOrderGoods;
  12. use common\models\Order;
  13. use common\models\OrderGoods;
  14. use common\models\Period;
  15. use common\models\ReceiveAddress;
  16. use common\models\Region;
  17. use common\models\ShopGoods;
  18. use yii\base\Exception;
  19. /**
  20. * Login form
  21. */
  22. class ApproachOrderForm extends Model
  23. {
  24. public $sn;
  25. public $status;
  26. public $remark;
  27. public $note;
  28. public $type;
  29. public $addressId;
  30. public $payType;
  31. public $goodsId;
  32. public $goodsNum;
  33. public $userName;
  34. public $consignee;
  35. public $province;
  36. public $city;
  37. public $county;
  38. public $consigneeIdNo;
  39. public $consigneeRealName;
  40. private $_address;
  41. private $_decAmount;
  42. private $_decPv;
  43. private $_freight;
  44. private $_payAmount;
  45. private $_orderGoods;
  46. private $_remainPv;
  47. private $_realPv;
  48. /**
  49. * @var ApproachOrder
  50. */
  51. private $_model;
  52. public function init() {
  53. parent::init();
  54. $this->adminOperateLogger = new AdminOperate([
  55. 'fetchClass' => ApproachOrder::class,
  56. ]);
  57. }
  58. /**
  59. * @inheritdoc
  60. */
  61. public function rules()
  62. {
  63. return [
  64. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','cityName','detailaddress', 'consigneeIdNo', 'consigneeRealName'], 'trim'],
  65. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress', 'consigneeIdNo', 'consigneeRealName'], 'required'],
  66. [['status'], 'isStatus'],
  67. [['addressId'], 'isAddress'],
  68. [['payType'], 'isPayType'],
  69. ];
  70. }
  71. public function attributeLabels()
  72. {
  73. return [
  74. 'sn' => '订单号',
  75. 'expressCompany' => '快递公司',
  76. 'orderTrackNo' => '快递单号',
  77. 'status' => '状态',
  78. 'remark' => '备注',
  79. 'type' => '订单类型',
  80. 'addressId' => '收货地址',
  81. 'payType' => '支付方式',
  82. 'goodsId' => '商品ID',
  83. 'goodsNum' => '商品数量',
  84. 'userName' => '复消会员编号',
  85. 'consignee' => '收货人',
  86. 'acceptMobile' => '收货电话',
  87. 'province' => '省',
  88. 'city' => '市',
  89. 'county' => '区',
  90. 'detailaddress' => '收货详细地址',
  91. ];
  92. }
  93. /**
  94. * 指定校验场景
  95. * @return array
  96. */
  97. public function scenarios()
  98. {
  99. $parentScenarios = parent::scenarios();
  100. $customScenarios = [
  101. // 管理员修改订单状态
  102. 'adminStatus' => ['sn', 'status'],
  103. // 校验订单支付
  104. 'verifyPay' => ['sn', 'status', 'note'],
  105. // 会员下单
  106. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'consigneeIdNo', 'consigneeRealName'],
  107. ];
  108. return array_merge($parentScenarios, $customScenarios);
  109. }
  110. /**
  111. * 校验之前
  112. * @return bool
  113. */
  114. public function beforeValidate()
  115. {
  116. LoggerTool::error(['UPOP - webhook: (beforeValidate 1).']);
  117. $parentValidate = parent::beforeValidate();
  118. if ($this->sn) {
  119. LoggerTool::error(['UPOP - webhook: (beforeValidate 2).', $this->sn]);
  120. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  121. LoggerTool::error(['UPOP - webhook: (beforeValidate 3).', $this->_model]);
  122. if (!$this->_model) {
  123. LoggerTool::error(['UPOP - webhook: (beforeValidate 4).', $this->_model]);
  124. $this->addError('sn', '订单不存在');
  125. return false;
  126. }
  127. }
  128. LoggerTool::error(['UPOP - webhook: (beforeValidate 5).', $this->_model]);
  129. return $parentValidate;
  130. }
  131. /**
  132. * 判断收货地址是否存在
  133. * @param $attribute
  134. */
  135. public function isAddress($attribute){
  136. LoggerTool::error(['UPOP - webhook: (isAddress 1).']);
  137. if (!$receiveAddress = ReceiveAddress::find()->where('ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  138. $this->addError($attribute, '收货地址不存在');
  139. } else {
  140. if (!$receiveAddress['ZIP_CODE']){
  141. $this->addError($attribute, '收货地址没有填写邮编');
  142. } else {
  143. $this->_address = $receiveAddress;
  144. }
  145. }
  146. LoggerTool::error(['UPOP - webhook: (isAddress 2).']);
  147. }
  148. /**
  149. * 判断支付方式
  150. * @param $attribute
  151. * @throws Exception
  152. */
  153. public function isPayType($attribute)
  154. {
  155. LoggerTool::error(['UPOP - webhook: (isPayType 1).']);
  156. if ($this->payType && !in_array($this->payType, array_values(ShopGoods::BANK_CODE))) {
  157. $this->addError('支付方式错误');
  158. return;
  159. }
  160. // 一个订单只能包含一类商品
  161. $goods = ShopGoods::find()->select('ID,CATE_ID')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  162. if (!$goods) {
  163. throw new Exception('商品已下架');
  164. return;
  165. }
  166. $goodsCategoryType = array_unique(array_column($goods, 'CATE_ID'));
  167. if (count($goodsCategoryType) > 1) {
  168. $this->addError($attribute, '订单不能包含多种商品分类');
  169. return;
  170. }
  171. LoggerTool::error(['UPOP - webhook: (isPayType 2).']);
  172. }
  173. /**
  174. * 校验类型
  175. * @param $attribute
  176. * @throws Exception
  177. */
  178. public function isStatus($attribute){
  179. LoggerTool::error(['UPOP - webhook: (isStatus 1).', $this->status]);
  180. if ($this->status && ($this->status != \Yii::$app->params['orderStatus']['notPaid']['value']) && ($this->status != \Yii::$app->params['orderStatus']['paid']['value'])) {
  181. LoggerTool::error(['UPOP - webhook: (isStatus 2).']);
  182. $this->addError($attribute, '订单状态类型错误');
  183. throw new Exception('商品已下架');
  184. }
  185. LoggerTool::error(['UPOP - webhook: (isStatus 3).']);
  186. }
  187. /**
  188. * 校验iPay88支付,更新订单状态.同步到正式订单.
  189. */
  190. public function verifyPayOnline(): ?ApproachOrder
  191. {
  192. if (!$this->validate()) {
  193. return null;
  194. }
  195. LoggerTool::info([$this->sn, $this->note]);
  196. // TODO: 支付校验
  197. $db = \Yii::$app->db;
  198. $transaction = $db->beginTransaction();
  199. try {
  200. // 更新准订单状态为已支付
  201. $this->_model->STATUS = $this->status;
  202. $this->_model->NOTE = json_encode($this->note);
  203. $this->_model->PAY_AT = time();
  204. // $this->_model->PAY_AT = Date::utcToTime($this->note['TranDate']);
  205. if (!$this->_model->save()) {
  206. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  207. }
  208. // 同步准订单到正式订单
  209. Order::insertOne($this->_model->toArray());
  210. // 同步准订单商品到正式订单商品
  211. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  212. OrderGoods::batchInsert($approachOrderGoods);
  213. // 删除中间表
  214. ApproachOrder::deleteAll('SN=:SN', [':SN' => $this->sn]);
  215. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  216. $transaction->commit();
  217. } catch (Exception $e) {
  218. $transaction->rollBack();
  219. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  220. return null;
  221. }
  222. return $this->_model;
  223. }
  224. public function verifyPayUPOP(): ?bool
  225. {
  226. if (!$this->validate()) {
  227. LoggerTool::error(['UPOP - webhook: (validate).']);
  228. return null;
  229. }
  230. // 支付校验
  231. $db = \Yii::$app->db;
  232. $transaction = $db->beginTransaction();
  233. try {
  234. // 更新准订单状态为已支付
  235. $this->_model->STATUS = $this->status;
  236. $this->_model->NOTE = json_encode($this->note);
  237. $this->_model->PAY_AT = strtotime($this->note['pay_time']);
  238. if (!$this->_model->save()) {
  239. LoggerTool::error(['UPOP - webhook: (update).']);
  240. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  241. }
  242. // 同步准订单到正式订单
  243. Order::insertOne($this->_model->toArray());
  244. // 同步准订单商品到正式订单商品
  245. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  246. OrderGoods::batchInsert($approachOrderGoods);
  247. // 删除中间表
  248. ApproachOrder::deleteAll('SN=:SN', [':SN' => $this->sn]);
  249. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  250. $transaction->commit();
  251. return true;
  252. } catch (Exception $e) {
  253. LoggerTool::error(['UPOP - webhook: (exp).' . $e->getFile() . ' ' . $e->getMessage()]);
  254. $transaction->rollBack();
  255. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  256. return null;
  257. }
  258. }
  259. /**
  260. * BV分期
  261. *
  262. *
  263. */
  264. private function _pvSplit($oPv){
  265. $sysConfig = Cache::getSystemConfig();
  266. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  267. if ($oPv > $mesureUpCondition) {
  268. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  269. $remainPv = $oPv - $currentPv;
  270. } else {
  271. $currentPv = $oPv;
  272. $remainPv = 0;
  273. }
  274. return [
  275. 'current' => $currentPv,
  276. 'remain' => $remainPv
  277. ];
  278. }
  279. /**
  280. * 复销
  281. * @throws Exception
  282. * @throws \yii\db\Exception
  283. */
  284. public function add() {
  285. if(!$this->validate()){
  286. return null;
  287. }
  288. $ids = $this->goodsId;
  289. $totalAmount = 0;
  290. $totalPv = 0;
  291. $totalRealPv = 0;
  292. $this->_remainPv = 0;
  293. $cateId = [];
  294. foreach ($this->goodsNum as $k => $v) {
  295. if ($v) {
  296. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  297. if (!$goods) {
  298. throw new Exception('商品已下架');
  299. }
  300. $cateId[] = $goods['CATE_ID'];
  301. if ($goods['STORE_NUMS'] > 0) {
  302. $discount = $goods['SELL_DISCOUNT'];
  303. $realPrice = $goods['SELL_PRICE'] * $discount;
  304. $realPv = $goods['PRICE_PV'] * $discount;
  305. if ($goods['PV_SPLIT'] == 1) { // 当商品为PV分期时
  306. $pvSplit = $this->_pvSplit($realPv);
  307. $currentPv = $pvSplit['current'];
  308. $remainPv = $pvSplit['remain'];
  309. $totalPv += $currentPv * intval($v);
  310. $totalRealPv += $realPv * intval($v);
  311. $this->_remainPv += $remainPv * intval($v);
  312. } else {
  313. $currentPv = $goods['PRICE_PV'];
  314. $totalPv += $realPv * intval($v);
  315. $totalRealPv += $realPv * intval($v);
  316. $remainPv = 0;
  317. $this->_remainPv += 0;
  318. }
  319. $totalAmount += $realPrice * intval($v);
  320. $this->_orderGoods[] = [
  321. 'GOODS_ID' => $goods['ID'],
  322. 'PRICE' => $goods['SELL_PRICE'],
  323. 'PV' => $currentPv,
  324. 'REAL_PRICE' => $realPrice,
  325. 'REAL_PV' => $realPv,
  326. 'REMAIN_PV' => $remainPv,
  327. 'POINT' => $goods['POINT'],
  328. 'BUY_NUMS' => intval($v),
  329. 'SKU_CODE' => $goods['GOODS_NO'],
  330. 'GOODS_TITLE' => $goods['GOODS_NAME']
  331. ];
  332. }
  333. }
  334. }
  335. if (count(array_unique($cateId)) > 1) {
  336. throw new Exception('海内商品、海外商品只能选择一种');
  337. }
  338. $this->_decAmount = $totalAmount;
  339. $this->_decPv = $totalPv;
  340. $this->_realPv = $totalRealPv;
  341. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  342. $this->_payAmount = $this->_decAmount + $this->_freight;
  343. $db = \Yii::$app->db;
  344. $transaction = $db->beginTransaction();
  345. // 支付减库存
  346. foreach ($this->goodsNum as $k => $v) {
  347. if ($v) {
  348. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=> $ids[$k]]);
  349. if (!$goods) {
  350. throw new Exception('商品已下架');
  351. }
  352. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]) {
  353. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  354. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  355. $data->STORE_NUMS = $goods_store_nums;
  356. $data->update();
  357. //下单后库存小于等于0 商品下架
  358. if ($goods_store_nums <= 0) {
  359. $data->STATUS = 0;
  360. $data->UPDATED_AT = Date::nowTime();
  361. $data->update();
  362. }
  363. } else {
  364. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  365. }
  366. }
  367. }
  368. try {
  369. // 写入订单
  370. if (!$orderResult = $this->addOrder()) {
  371. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  372. }
  373. // TODO: 获取iPay88所需参数
  374. // $orderSn = $orderResult->SN;
  375. $transaction->commit();
  376. return $orderResult;
  377. }catch (\Exception $e){
  378. $transaction->rollBack();
  379. $this->addError('add', $e->getMessage());
  380. return null;
  381. }
  382. }
  383. /**
  384. * 复销订单
  385. * @throws Exception
  386. */
  387. public function addOrder()
  388. {
  389. $periodObj = Period::instance();
  390. $nowPeriodNum = $periodObj->getNowPeriodNum();
  391. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  392. $userId = \Yii::$app->user->id;
  393. $userName = Info::getUserNameByUserId($userId);
  394. $userRealName = Info::getUserRealNameByUserId($userId);
  395. $userMobile = Info::getUserMobileByUserId($userId);
  396. $userEmail = Info::getUserEmailByUserId($userId);
  397. // 加入订单信息
  398. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  399. if(!$warehouse){
  400. throw new Exception('地区暂时不支持配送,具体联系客服');
  401. }
  402. $ordNo = $this->_generateSn();
  403. $orderModel = new ApproachOrder();
  404. $orderModel->SN = 'OS' . $ordNo;
  405. $orderModel->DEC_SN = 'DS' . $ordNo;
  406. $orderModel->ORDER_TYPE = $this->type;
  407. $orderModel->USER_ID = $userId;
  408. $orderModel->USER_NAME = $userName;
  409. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  410. $orderModel->PV = $this->_decPv;
  411. $orderModel->PAY_AMOUNT = $this->_payAmount;
  412. $orderModel->PAY_PV = $this->_decPv;
  413. $orderModel->REMAIN_PV = $this->_remainPv;
  414. $orderModel->PAY_AT = 0;
  415. $orderModel->PAY_TYPE = $this->payType;
  416. $orderModel->PERIOD_NUM = $nowPeriodNum;
  417. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  418. $orderModel->FREIGHT = $this->_freight;
  419. $orderModel->PAY_FREIGHT = $this->_freight;
  420. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  421. $orderModel->MOBILE = $this->_address['MOBILE'];
  422. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  423. $orderModel->CITY = $this->_address['CITY'];
  424. $orderModel->COUNTY = $this->_address['COUNTY'];
  425. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  426. $orderModel->FRONT_REMARK = $this->remark;
  427. $orderModel->WAREHOUSE = $warehouse;
  428. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  429. $orderModel->CREATED_AT = Date::nowTime();
  430. $orderModel->CREATE_USER = $userName;
  431. $orderModel->EMAIL = $userEmail ?: $userName.'@elken.net';
  432. $orderModel->CONSIGNEE_ID_NO = $this->consigneeIdNo;
  433. $orderModel->CONSIGNEE_REAL_NAME = $this->consigneeRealName;
  434. $orderModel->ZIP_CODE = $this->_address['ZIP_CODE'];
  435. if(!$orderModel->save()){
  436. $this->addErrors($orderModel->getErrors());
  437. return false;
  438. }
  439. // 加入商品到订单商品表
  440. foreach($this->_orderGoods as $key=>$value) {
  441. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  442. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  443. }
  444. ApproachOrderGoods::batchInsert($this->_orderGoods);
  445. return $orderModel;
  446. }
  447. /**
  448. * 生成流水号
  449. * @return string
  450. */
  451. private function _generateSn() {
  452. return Date::today('Ymd') . $this->_random(10, 1);
  453. }
  454. /**
  455. * 生成随机数
  456. * @param $length
  457. * @param int $numeric
  458. * @return string
  459. */
  460. private function _random($length, $numeric = 0) {
  461. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  462. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  463. $hash = '';
  464. $max = strlen($seed) - 1;
  465. for ($i = 0; $i < $length; $i++) {
  466. $hash .= $seed[mt_rand(0, $max)];
  467. }
  468. return $hash;
  469. }
  470. }