OrderForm.php 27 KB

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