OrderForm.php 27 KB

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