OrderForm.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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\user\Balance;
  8. use common\helpers\user\Cash;
  9. use common\helpers\user\Info;
  10. use common\libs\logging\operate\AdminOperate;
  11. use common\models\DealType;
  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 common\models\User;
  19. use common\models\UserNetwork;
  20. use yii\base\Exception;
  21. /**
  22. * Login form
  23. */
  24. class OrderForm extends Model
  25. {
  26. public $sn;
  27. public $expressCompany;
  28. public $orderTrackNo;
  29. public $status;
  30. public $remark;
  31. public $type;
  32. public $addressId;
  33. public $payType;
  34. public $goodsId;
  35. public $goodsNum;
  36. public $payPassword;
  37. public $userName;
  38. public $consignee;
  39. public $acceptMobile;
  40. public $province;
  41. public $city;
  42. public $county;
  43. public $detailaddress;
  44. private $_address;
  45. private $_decAmount;
  46. private $_decPv;
  47. private $_freight;
  48. private $_payAmount;
  49. private $_orderGoods;
  50. /**
  51. * @var Order
  52. */
  53. private $_model;
  54. public function init() {
  55. parent::init();
  56. $this->adminOperateLogger = new AdminOperate([
  57. 'fetchClass' => Order::class,
  58. ]);
  59. }
  60. /**
  61. * @inheritdoc
  62. */
  63. public function rules()
  64. {
  65. return [
  66. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress'], 'trim'],
  67. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress'], 'required'],
  68. [['status'], 'isStatus'],
  69. [['addressId'], 'isAddress'],
  70. [['payType'], 'isPayType'],
  71. [['payPassword'], 'validatePassword'],
  72. ];
  73. }
  74. public function attributeLabels()
  75. {
  76. return [
  77. 'sn' => '订单号',
  78. 'expressCompany' => '快递公司',
  79. 'orderTrackNo' => '快递单号',
  80. 'status' => '状态',
  81. 'remark' => '备注',
  82. 'type' => '订单类型',
  83. 'addressId' => '收货地址',
  84. 'payType' => '支付方式',
  85. 'goodsId' => '商品ID',
  86. 'goodsNum' => '商品数量',
  87. 'userName' => '复消会员编号',
  88. 'consignee' => '收货人',
  89. 'acceptMobile' => '收货电话',
  90. 'province' => '省',
  91. 'city' => '市',
  92. 'county' => '区',
  93. 'detailaddress' => '收货详细地址',
  94. ];
  95. }
  96. /**
  97. * 指定校验场景
  98. * @return array
  99. */
  100. public function scenarios()
  101. {
  102. $parentScenarios = parent::scenarios();
  103. $customScenarios = [
  104. // 管理员发货
  105. 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  106. // 会员确认收货
  107. 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  108. // 管理员修改订单状态
  109. 'adminStatus' => ['sn', 'status'],
  110. // 管理员修改备注
  111. 'adminRemark' => ['sn', 'remark'],
  112. // 会员下单
  113. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
  114. // 帮会员复消下单
  115. 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'],
  116. ];
  117. return array_merge($parentScenarios, $customScenarios);
  118. }
  119. /**
  120. * 校验之前
  121. * @return bool
  122. */
  123. public function beforeValidate()
  124. {
  125. $parentValidate = parent::beforeValidate();
  126. if ($this->sn) {
  127. $this->_model = Order::findOne(['SN'=>$this->sn]);
  128. if (!$this->_model){
  129. $this->addError('sn', '订单不存在');
  130. return false;
  131. }
  132. }
  133. if ($this->scenario == 'adminDelivery'){
  134. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
  135. $this->addError('sn', '订单已取消不能发货');
  136. return false;
  137. }
  138. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  139. $this->addError('sn', '订单已删除不能发货');
  140. return false;
  141. }
  142. }
  143. return $parentValidate;
  144. }
  145. /**
  146. * 校验支付密码
  147. * @param $attribute
  148. * @param $params
  149. */
  150. public function validatePassword($attribute, $params) {
  151. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  152. $this->addError($attribute, '支付密码不正确');
  153. }
  154. }
  155. /**
  156. * 判断收货地址是否存在
  157. * @param $attribute
  158. */
  159. public function isAddress($attribute){
  160. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  161. $this->addError($attribute, '收货地址不存在');
  162. } else {
  163. $this->_address = $receiveAddress;
  164. }
  165. }
  166. /**
  167. * 判断支付方式
  168. * @param $attribute
  169. */
  170. public function isPayType($attribute){
  171. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  172. $this->addError($attribute, '支付方式错误');
  173. return;
  174. }
  175. }
  176. /**
  177. * 校验类型
  178. * @param $attribute
  179. */
  180. public function isStatus($attribute){
  181. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  182. $this->addError($attribute, '类型错误');
  183. return ;
  184. }
  185. if ($this->scenario == 'adminStatus'){
  186. if ($this->status == $this->_model['STATUS']) {
  187. $this->addError($attribute, '订单状态没有改变');
  188. return ;
  189. }
  190. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  191. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  192. return ;
  193. }
  194. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  195. $this->addError($attribute, '订单已失效不能处理');
  196. return ;
  197. }
  198. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  199. $this->addError($attribute, '订单不能单独处理为物流状态');
  200. return ;
  201. }
  202. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  203. $this->addError($attribute, '订单已失效不能处理');
  204. return ;
  205. }
  206. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  207. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  208. $this->addError($attribute, '订单已完成不能取消');
  209. return ;
  210. }
  211. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  212. $this->addError($attribute, '订单已删除不能取消');
  213. return ;
  214. }
  215. }
  216. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  217. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  218. $this->addError($attribute, '订单已完成不能删除');
  219. return ;
  220. }
  221. }
  222. }
  223. }
  224. /**
  225. * 管理员发货
  226. * @return Order|null
  227. * @throws \yii\db\Exception
  228. */
  229. public function adminDelivery(){
  230. if(!$this->validate()){
  231. return null;
  232. }
  233. $db = \Yii::$app->db;
  234. $transaction = $db->beginTransaction();
  235. try {
  236. $period = Period::instance();
  237. $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value'];
  238. $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum();
  239. $this->_model->DELIVERY_AT = Date::nowTime();
  240. $this->_model->EXPRESS_COMPANY = $this->expressCompany;
  241. $this->_model->ORDER_TRACK_NO = $this->orderTrackNo;
  242. $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value'];
  243. if(!$this->_model->save()){
  244. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  245. }
  246. $transaction->commit();
  247. } catch (Exception $e) {
  248. $transaction->rollBack();
  249. $this->addError('edit', $e->getMessage());
  250. return null;
  251. }
  252. return $this->_model;
  253. }
  254. /**
  255. * 复销
  256. * @return bool|null
  257. * @throws Exception
  258. * @throws \yii\db\Exception
  259. */
  260. public function add(){
  261. if(!$this->validate()){
  262. return null;
  263. }
  264. $ids = $this->goodsId;
  265. $totalAmount = 0;
  266. $totalPv = 0;
  267. foreach ($this->goodsNum as $k => $v) {
  268. if ($v) {
  269. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  270. if($goods['STORE_NUMS']>0){
  271. $discount = $goods['SELL_DISCOUNT'];
  272. $realPrice = $goods['SELL_PRICE'] * $discount;
  273. $realPv = $goods['PRICE_PV'] * $discount;
  274. $totalAmount += $realPrice * intval($v);
  275. $totalPv += $realPv * intval($v);
  276. // if($this->payType=='cash') {
  277. // $discount = $goodsType[$goods['TYPE']]['discount'];
  278. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  279. // $realPv = $goods['PRICE_PV'] * $discount/100;
  280. // $totalAmount += $realPrice * intval($v);
  281. // $totalPv += $realPv * intval($v);
  282. // }else{
  283. // $realPrice = $goods['SELL_PRICE'];
  284. // $realPv = $goods['PRICE_PV'];
  285. // $totalAmount += $realPrice * intval($v);
  286. // $totalPv += $realPv * intval($v);
  287. // }
  288. $this->_orderGoods[] = [
  289. 'GOODS_ID' => $goods['ID'],
  290. 'PRICE' => $goods['SELL_PRICE'],
  291. 'PV' => $goods['PRICE_PV'],
  292. 'REAL_PRICE' => $realPrice,
  293. 'REAL_PV' => $realPv,
  294. 'POINT' => $goods['POINT'],
  295. 'BUY_NUMS' => intval($v),
  296. 'SKU_CODE' => $goods['GOODS_NO'],
  297. 'GOODS_TITLE' => $goods['GOODS_NAME']
  298. ];
  299. }
  300. }
  301. }
  302. $this->_decAmount = $totalAmount;
  303. $this->_decPv = $totalPv;
  304. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  305. $this->_payAmount = $this->_decAmount + $this->_freight;
  306. $db = \Yii::$app->db;
  307. $transaction = $db->beginTransaction();
  308. try {
  309. //判断用户余额是否充足
  310. $loginUserId = \Yii::$app->user->id;
  311. if($this->payType=='cash') {
  312. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  313. throw new Exception('余额不足,无法购买商品');
  314. }
  315. } else if ($this->payType =='exchange') {
  316. if ($this->_payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  317. throw new Exception('兑换点数不足,无法购买商品');
  318. }
  319. } else{
  320. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  321. throw new Exception('复销点数不足,无法购买商品');
  322. }
  323. }
  324. /**
  325. * 2022-04-28
  326. * York
  327. * 支付后减少库存
  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['STORE_NUMS'] >= $this->goodsNum[$k]){
  333. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  334. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  335. $data->STORE_NUMS = $goods_store_nums;
  336. $data->update();
  337. //下单后库存小于等于0 商品下架
  338. if($goods_store_nums <= 0){
  339. $data->STATUS = 0;
  340. $data->UPDATED_AT = Date::nowTime();
  341. $data->update();
  342. }
  343. }else{
  344. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  345. }
  346. }
  347. }
  348. // exit();
  349. //写入订单
  350. if (!$orderResult = $this->addOrder()) {
  351. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  352. }
  353. $transaction->commit();
  354. }catch (\Exception $e){
  355. $transaction->rollBack();
  356. $this->addError('add', $e->getMessage());
  357. return null;
  358. }
  359. return true;
  360. }
  361. /**
  362. * 复销订单
  363. */
  364. public function addOrder(){
  365. $periodObj = Period::instance();
  366. $nowPeriodNum = $periodObj->getNowPeriodNum();
  367. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  368. $userId = \Yii::$app->user->id;
  369. $userName = Info::getUserNameByUserId($userId);
  370. // 加入订单信息
  371. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  372. if(!$warehouse){
  373. throw new Exception('地区暂时不支持配送,具体联系客服');
  374. }
  375. $ordNo = $this->_generateSn();
  376. $orderModel = new Order();
  377. $orderModel->SN = 'OS'.$ordNo;
  378. $orderModel->DEC_SN = 'DS'.$ordNo;
  379. $orderModel->ORDER_TYPE = $this->type;
  380. $orderModel->USER_ID = $userId;
  381. $orderModel->USER_NAME = $userName;
  382. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  383. $orderModel->PV = $this->payType =='exchange' ? 0 : $this->_decPv;
  384. $orderModel->PAY_AMOUNT = $this->_payAmount;
  385. $orderModel->PAY_PV = $this->payType =='exchange' ? 0 : $this->_decPv; // 兑换积分不能算业绩
  386. $orderModel->PAY_AT = Date::nowTime();
  387. $orderModel->PAY_TYPE = $this->payType;
  388. $orderModel->PERIOD_NUM = $nowPeriodNum;
  389. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  390. $orderModel->FREIGHT = $this->_freight;
  391. $orderModel->PAY_FREIGHT = $this->_freight;
  392. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  393. $orderModel->MOBILE = $this->_address['MOBILE'];
  394. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  395. $orderModel->CITY = $this->_address['CITY'];
  396. $orderModel->COUNTY = $this->_address['COUNTY'];
  397. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  398. $orderModel->FRONT_REMARK = $this->remark;
  399. $orderModel->WAREHOUSE = $warehouse;
  400. $orderModel->STATUS = 1;
  401. $orderModel->CREATED_AT = Date::nowTime();
  402. $orderModel->CREATE_USER = $userName;
  403. if(!$orderModel->save()){
  404. $this->addErrors($orderModel->getErrors());
  405. return false;
  406. }
  407. // 加入商品到订单商品表
  408. foreach($this->_orderGoods as $key=>$value){
  409. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  410. if ($orderModel->PAY_TYPE == 'exchange') {
  411. $this->_orderGoods[$key]['REAL_PV'] = 0;
  412. }
  413. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  414. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  415. }
  416. OrderGoods::batchInsert($this->_orderGoods);
  417. //扣除会员余额/积分
  418. if($this->payType=='cash') {
  419. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  420. } else if ($this->payType=='exchange') {
  421. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
  422. } else{
  423. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销点数兑换']);
  424. }
  425. return $orderModel;
  426. }
  427. /**
  428. * 帮会员复销
  429. * @return bool|null
  430. * @throws Exception
  431. * @throws \yii\db\Exception
  432. */
  433. public function reconsumeAdd(){
  434. if(!$this->validate()){
  435. return null;
  436. }
  437. $ids = $this->goodsId;
  438. $totalAmount = 0;
  439. $totalPv = 0;
  440. foreach ($this->goodsNum as $k => $v) {
  441. if ($v) {
  442. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  443. if($goods['STORE_NUMS']>0){
  444. $discount = $goods['SELL_DISCOUNT'];
  445. $realPrice = $goods['SELL_PRICE'] * $discount;
  446. $realPv = $goods['PRICE_PV'] * $discount;
  447. $totalAmount += $realPrice * intval($v);
  448. $totalPv += $realPv * intval($v);
  449. $this->_orderGoods[] = [
  450. 'GOODS_ID' => $goods['ID'],
  451. 'PRICE' => $goods['SELL_PRICE'],
  452. 'PV' => $goods['PRICE_PV'],
  453. 'REAL_PRICE' => $realPrice,
  454. 'REAL_PV' => $realPv,
  455. 'POINT' => $goods['POINT'],
  456. 'BUY_NUMS' => intval($v),
  457. 'SKU_CODE' => $goods['GOODS_NO'],
  458. 'GOODS_TITLE' => $goods['GOODS_NAME']
  459. ];
  460. }
  461. }
  462. }
  463. $this->_decAmount = $totalAmount;
  464. $this->_decPv = $totalPv;
  465. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  466. $this->_payAmount = $this->_decAmount + $this->_freight;
  467. $db = \Yii::$app->db;
  468. $transaction = $db->beginTransaction();
  469. try {
  470. $loginUserId = \Yii::$app->user->id;
  471. //是否开启伞下会员限制
  472. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  473. if($isResaleUmbrella){
  474. $userId = Info::getUserIdByUserName($this->userName);
  475. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  476. if(!$userNetwork){
  477. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  478. }
  479. }
  480. //判断用户余额是否充足
  481. if($this->payType=='cash') {
  482. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  483. throw new Exception('余额不足,无法购买商品');
  484. }
  485. }else{
  486. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  487. throw new Exception('复销点数不足,无法购买商品');
  488. }
  489. }
  490. /**
  491. * 2022-04-28
  492. * York
  493. * 支付后减少库存
  494. */
  495. foreach ($this->goodsNum as $k => $v){
  496. if ($v){
  497. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  498. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  499. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  500. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  501. $data->STORE_NUMS = $goods_store_nums;
  502. $data->update();
  503. //下单后库存小于等于0 商品下架
  504. if($goods_store_nums <= 0){
  505. $data->STATUS = 0;
  506. $data->UPDATED_AT = Date::nowTime();
  507. $data->update();
  508. }
  509. }else{
  510. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  511. }
  512. }
  513. }
  514. // exit();
  515. //写入订单
  516. if (!$orderResult = $this->addUserOrder()) {
  517. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  518. }
  519. $transaction->commit();
  520. }catch (\Exception $e){
  521. $transaction->rollBack();
  522. $this->addError('add', $e->getMessage());
  523. return null;
  524. }
  525. return true;
  526. }
  527. /**
  528. * 帮会员复消的订单
  529. */
  530. public function addUserOrder(){
  531. $periodObj = Period::instance();
  532. $nowPeriodNum = $periodObj->getNowPeriodNum();
  533. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  534. //帮复消会员Id(登陆会员)
  535. $loginUserId = \Yii::$app->user->id;
  536. $loginUserName = Info::getUserNameByUserId($loginUserId);
  537. //订单会员Id
  538. $userId = Info::getUserIdByUserName($this->userName);
  539. // 加入订单信息
  540. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  541. if(!$warehouse){
  542. throw new Exception('地区暂时不支持配送,具体联系客服');
  543. }
  544. $ordNo = $this->_generateSn();
  545. $orderModel = new Order();
  546. $orderModel->SN = 'OS'.$ordNo;
  547. $orderModel->DEC_SN = 'DS'.$ordNo;
  548. $orderModel->ORDER_TYPE = $this->type;
  549. $orderModel->USER_ID = $userId;
  550. $orderModel->USER_NAME = $this->userName;
  551. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  552. $orderModel->PV = $this->_decPv;
  553. $orderModel->PAY_AMOUNT = $this->_payAmount;
  554. $orderModel->PAY_PV = $this->_decPv;
  555. $orderModel->PAY_AT = Date::nowTime();
  556. $orderModel->PAY_TYPE = $this->payType;
  557. $orderModel->PERIOD_NUM = $nowPeriodNum;
  558. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  559. $orderModel->FREIGHT = $this->_freight;
  560. $orderModel->PAY_FREIGHT = $this->_freight;
  561. $orderModel->CONSIGNEE = $this->consignee;
  562. $orderModel->MOBILE = $this->acceptMobile;
  563. $orderModel->PROVINCE = $this->province;
  564. $orderModel->CITY = $this->city;
  565. $orderModel->COUNTY = $this->county;
  566. $orderModel->ADDRESS = $this->detailaddress;
  567. $orderModel->FRONT_REMARK = $this->remark;
  568. $orderModel->WAREHOUSE = $warehouse;
  569. $orderModel->STATUS = 1;
  570. $orderModel->CREATED_AT = Date::nowTime();
  571. $orderModel->CREATE_USER = $loginUserName;
  572. if(!$orderModel->save()){
  573. $this->addErrors($orderModel->getErrors());
  574. return false;
  575. }
  576. // 加入商品到订单商品表
  577. foreach($this->_orderGoods as $key=>$value){
  578. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  579. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  580. }
  581. OrderGoods::batchInsert($this->_orderGoods);
  582. //扣除会员余额/积分
  583. if($this->payType=='cash') {
  584. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  585. }else{
  586. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销点数兑换']);
  587. }
  588. return $orderModel;
  589. }
  590. /**
  591. * 生成流水号
  592. * @return string
  593. */
  594. private function _generateSn() {
  595. return Date::today('Ymd') . $this->_random(10, 1);
  596. }
  597. /**
  598. * 生成随机数
  599. * @param $length
  600. * @param int $numeric
  601. * @return string
  602. */
  603. private function _random($length, $numeric = 0) {
  604. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  605. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  606. $hash = '';
  607. $max = strlen($seed) - 1;
  608. for ($i = 0; $i < $length; $i++) {
  609. $hash .= $seed[mt_rand(0, $max)];
  610. }
  611. return $hash;
  612. }
  613. }