OrderForm.php 37 KB

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