OrderForm.php 28 KB

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