OrderForm.php 28 KB

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