OrderForm.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. $goodsType = ShopGoods::GOODS_TYPE;
  268. foreach ($this->goodsNum as $k => $v) {
  269. if ($v) {
  270. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  271. if($goods['STORE_NUMS']>0){
  272. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  273. $discount = $goodsType[$goods['TYPE']]['discount'];
  274. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  275. $realPv = $goods['PRICE_PV'] * $discount/100;
  276. } else {
  277. $discount = $goods['SELL_DISCOUNT'];
  278. $realPrice = $goods['SELL_PRICE'] * $discount;
  279. $realPv = $goods['PRICE_PV'] * $discount;
  280. }
  281. $totalAmount += $realPrice * intval($v);
  282. $totalPv += $realPv * intval($v);
  283. // if($this->payType=='cash') {
  284. // $discount = $goodsType[$goods['TYPE']]['discount'];
  285. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  286. // $realPv = $goods['PRICE_PV'] * $discount/100;
  287. // $totalAmount += $realPrice * intval($v);
  288. // $totalPv += $realPv * intval($v);
  289. // }else{
  290. // $realPrice = $goods['SELL_PRICE'];
  291. // $realPv = $goods['PRICE_PV'];
  292. // $totalAmount += $realPrice * intval($v);
  293. // $totalPv += $realPv * intval($v);
  294. // }
  295. $this->_orderGoods[] = [
  296. 'GOODS_ID' => $goods['ID'],
  297. 'PRICE' => $goods['SELL_PRICE'],
  298. 'PV' => $goods['PRICE_PV'],
  299. 'REAL_PRICE' => $realPrice,
  300. 'REAL_PV' => $realPv,
  301. 'POINT' => $goods['POINT'],
  302. 'BUY_NUMS' => intval($v),
  303. 'SKU_CODE' => $goods['GOODS_NO'],
  304. 'GOODS_TITLE' => $goods['GOODS_NAME']
  305. ];
  306. }
  307. }
  308. }
  309. $this->_decAmount = $totalAmount;
  310. $this->_decPv = $totalPv;
  311. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  312. $this->_payAmount = $this->_decAmount + $this->_freight;
  313. $db = \Yii::$app->db;
  314. $transaction = $db->beginTransaction();
  315. try {
  316. //判断用户余额是否充足
  317. $loginUserId = \Yii::$app->user->id;
  318. if($this->payType=='cash') {
  319. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  320. throw new Exception('余额不足,无法购买商品');
  321. }
  322. } else if ($this->payType =='exchange') {
  323. if ($this->_payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  324. throw new Exception('兑换点数不足,无法购买商品');
  325. }
  326. } else{
  327. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  328. throw new Exception('复消积分不足,无法购买商品');
  329. }
  330. }
  331. /**
  332. * 2022-04-28
  333. * York
  334. * 支付后减少库存
  335. */
  336. foreach ($this->goodsNum as $k => $v){
  337. if ($v){
  338. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  339. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  340. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  341. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  342. $data->STORE_NUMS = $goods_store_nums;
  343. $data->update();
  344. //下单后库存小于等于0 商品下架
  345. if($goods_store_nums <= 0){
  346. $data->STATUS = 0;
  347. $data->UPDATED_AT = Date::nowTime();
  348. $data->update();
  349. }
  350. }else{
  351. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  352. }
  353. }
  354. }
  355. // exit();
  356. //写入订单
  357. if (!$orderResult = $this->addOrder()) {
  358. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  359. }
  360. $transaction->commit();
  361. }catch (\Exception $e){
  362. $transaction->rollBack();
  363. $this->addError('add', $e->getMessage());
  364. return null;
  365. }
  366. return true;
  367. }
  368. /**
  369. * 复销订单
  370. */
  371. public function addOrder(){
  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. // 加入订单信息
  378. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  379. if(!$warehouse){
  380. throw new Exception('地区暂时不支持配送,具体联系客服');
  381. }
  382. $ordNo = $this->_generateSn();
  383. $orderModel = new Order();
  384. $orderModel->SN = 'OS'.$ordNo;
  385. $orderModel->DEC_SN = 'DS'.$ordNo;
  386. $orderModel->ORDER_TYPE = $this->type;
  387. $orderModel->USER_ID = $userId;
  388. $orderModel->USER_NAME = $userName;
  389. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  390. $orderModel->PV = $this->payType =='exchange' ? 0 : $this->_decPv;
  391. $orderModel->PAY_AMOUNT = $this->_payAmount;
  392. $orderModel->PAY_PV = $this->payType =='exchange' ? 0 : $this->_decPv; // 兑换积分不能算业绩
  393. $orderModel->PAY_AT = Date::nowTime();
  394. $orderModel->PAY_TYPE = $this->payType;
  395. $orderModel->PERIOD_NUM = $nowPeriodNum;
  396. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  397. $orderModel->FREIGHT = $this->_freight;
  398. $orderModel->PAY_FREIGHT = $this->_freight;
  399. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  400. $orderModel->MOBILE = $this->_address['MOBILE'];
  401. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  402. $orderModel->CITY = $this->_address['CITY'];
  403. $orderModel->COUNTY = $this->_address['COUNTY'];
  404. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  405. $orderModel->FRONT_REMARK = $this->remark;
  406. $orderModel->WAREHOUSE = $warehouse;
  407. $orderModel->STATUS = 1;
  408. $orderModel->CREATED_AT = Date::nowTime();
  409. $orderModel->CREATE_USER = $userName;
  410. if(!$orderModel->save()){
  411. $this->addErrors($orderModel->getErrors());
  412. return false;
  413. }
  414. // 加入商品到订单商品表
  415. foreach($this->_orderGoods as $key=>$value){
  416. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  417. if ($orderModel->PAY_TYPE == 'exchange') {
  418. $this->_orderGoods[$key]['REAL_PV'] = 0;
  419. }
  420. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  421. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  422. }
  423. OrderGoods::batchInsert($this->_orderGoods);
  424. //扣除会员余额/积分
  425. if($this->payType=='cash') {
  426. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  427. } else if ($this->payType=='exchange') {
  428. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
  429. } else{
  430. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
  431. }
  432. return $orderModel;
  433. }
  434. /**
  435. * 帮会员复销
  436. * @return bool|null
  437. * @throws Exception
  438. * @throws \yii\db\Exception
  439. */
  440. public function reconsumeAdd(){
  441. if(!$this->validate()){
  442. return null;
  443. }
  444. $ids = $this->goodsId;
  445. $totalAmount = 0;
  446. $totalPv = 0;
  447. $goodsType = ShopGoods::GOODS_TYPE;
  448. foreach ($this->goodsNum as $k => $v) {
  449. if ($v) {
  450. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  451. if($goods['STORE_NUMS']>0){
  452. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  453. $discount = $goodsType[$goods['TYPE']]['discount'];
  454. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  455. $realPv = $goods['PRICE_PV'] * $discount/100;
  456. } else {
  457. $discount = $goods['SELL_DISCOUNT'];
  458. $realPrice = $goods['SELL_PRICE'] * $discount;
  459. $realPv = $goods['PRICE_PV'] * $discount;
  460. }
  461. $totalAmount += $realPrice * intval($v);
  462. $totalPv += $realPv * intval($v);
  463. $this->_orderGoods[] = [
  464. 'GOODS_ID' => $goods['ID'],
  465. 'PRICE' => $goods['SELL_PRICE'],
  466. 'PV' => $goods['PRICE_PV'],
  467. 'REAL_PRICE' => $realPrice,
  468. 'REAL_PV' => $realPv,
  469. 'POINT' => $goods['POINT'],
  470. 'BUY_NUMS' => intval($v),
  471. 'SKU_CODE' => $goods['GOODS_NO'],
  472. 'GOODS_TITLE' => $goods['GOODS_NAME']
  473. ];
  474. }
  475. }
  476. }
  477. $this->_decAmount = $totalAmount;
  478. $this->_decPv = $totalPv;
  479. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  480. $this->_payAmount = $this->_decAmount + $this->_freight;
  481. $db = \Yii::$app->db;
  482. $transaction = $db->beginTransaction();
  483. try {
  484. $loginUserId = \Yii::$app->user->id;
  485. //是否开启伞下会员限制
  486. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  487. if($isResaleUmbrella){
  488. $userId = Info::getUserIdByUserName($this->userName);
  489. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  490. if(!$userNetwork){
  491. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  492. }
  493. }
  494. //判断用户余额是否充足
  495. if($this->payType=='cash') {
  496. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  497. throw new Exception('余额不足,无法购买商品');
  498. }
  499. }else{
  500. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  501. throw new Exception('复消积分不足,无法购买商品');
  502. }
  503. }
  504. /**
  505. * 2022-04-28
  506. * York
  507. * 支付后减少库存
  508. */
  509. foreach ($this->goodsNum as $k => $v){
  510. if ($v){
  511. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  512. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  513. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  514. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  515. $data->STORE_NUMS = $goods_store_nums;
  516. $data->update();
  517. //下单后库存小于等于0 商品下架
  518. if($goods_store_nums <= 0){
  519. $data->STATUS = 0;
  520. $data->UPDATED_AT = Date::nowTime();
  521. $data->update();
  522. }
  523. }else{
  524. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  525. }
  526. }
  527. }
  528. // exit();
  529. //写入订单
  530. if (!$orderResult = $this->addUserOrder()) {
  531. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  532. }
  533. $transaction->commit();
  534. }catch (\Exception $e){
  535. $transaction->rollBack();
  536. $this->addError('add', $e->getMessage());
  537. return null;
  538. }
  539. return true;
  540. }
  541. /**
  542. * 帮会员复消的订单
  543. */
  544. public function addUserOrder(){
  545. $periodObj = Period::instance();
  546. $nowPeriodNum = $periodObj->getNowPeriodNum();
  547. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  548. //帮复消会员Id(登陆会员)
  549. $loginUserId = \Yii::$app->user->id;
  550. $loginUserName = Info::getUserNameByUserId($loginUserId);
  551. //订单会员Id
  552. $userId = Info::getUserIdByUserName($this->userName);
  553. // 加入订单信息
  554. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  555. if(!$warehouse){
  556. throw new Exception('地区暂时不支持配送,具体联系客服');
  557. }
  558. $ordNo = $this->_generateSn();
  559. $orderModel = new Order();
  560. $orderModel->SN = 'OS'.$ordNo;
  561. $orderModel->DEC_SN = 'DS'.$ordNo;
  562. $orderModel->ORDER_TYPE = $this->type;
  563. $orderModel->USER_ID = $userId;
  564. $orderModel->USER_NAME = $this->userName;
  565. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  566. $orderModel->PV = $this->_decPv;
  567. $orderModel->PAY_AMOUNT = $this->_payAmount;
  568. $orderModel->PAY_PV = $this->_decPv;
  569. $orderModel->PAY_AT = Date::nowTime();
  570. $orderModel->PAY_TYPE = $this->payType;
  571. $orderModel->PERIOD_NUM = $nowPeriodNum;
  572. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  573. $orderModel->FREIGHT = $this->_freight;
  574. $orderModel->PAY_FREIGHT = $this->_freight;
  575. $orderModel->CONSIGNEE = $this->consignee;
  576. $orderModel->MOBILE = $this->acceptMobile;
  577. $orderModel->PROVINCE = $this->province;
  578. $orderModel->CITY = $this->city;
  579. $orderModel->COUNTY = $this->county;
  580. $orderModel->ADDRESS = $this->detailaddress;
  581. $orderModel->FRONT_REMARK = $this->remark;
  582. $orderModel->WAREHOUSE = $warehouse;
  583. $orderModel->STATUS = 1;
  584. $orderModel->CREATED_AT = Date::nowTime();
  585. $orderModel->CREATE_USER = $loginUserName;
  586. if(!$orderModel->save()){
  587. $this->addErrors($orderModel->getErrors());
  588. return false;
  589. }
  590. // 加入商品到订单商品表
  591. foreach($this->_orderGoods as $key=>$value){
  592. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  593. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  594. }
  595. OrderGoods::batchInsert($this->_orderGoods);
  596. //扣除会员余额/积分
  597. if($this->payType=='cash') {
  598. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  599. }else{
  600. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  601. }
  602. return $orderModel;
  603. }
  604. /**
  605. * 生成流水号
  606. * @return string
  607. */
  608. private function _generateSn() {
  609. return Date::today('Ymd') . $this->_random(10, 1);
  610. }
  611. /**
  612. * 生成随机数
  613. * @param $length
  614. * @param int $numeric
  615. * @return string
  616. */
  617. private function _random($length, $numeric = 0) {
  618. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  619. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  620. $hash = '';
  621. $max = strlen($seed) - 1;
  622. for ($i = 0; $i < $length; $i++) {
  623. $hash .= $seed[mt_rand(0, $max)];
  624. }
  625. return $hash;
  626. }
  627. }