ApproachOrderForm.php 18 KB

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