ApproachOrderForm.php 18 KB

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