ApproachOrderForm.php 17 KB

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