OrderForm.php 27 KB

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