ApproachOrderForm.php 18 KB

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