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