OrderForm.php 30 KB

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