ApproachOrderForm.php 18 KB

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