OrderForm.php 35 KB

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