OrderForm.php 36 KB

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