OrderForm.php 28 KB

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