OrderForm.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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. ];
  448. }
  449. }
  450. }
  451. $this->_decAmount = $totalAmount;
  452. $this->_decPv = $totalPv;
  453. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  454. if($this->_address['PROVINCE']==1){
  455. $this->_freight = 0;
  456. }
  457. $this->_payAmount = $this->_decAmount + $this->_freight;
  458. $this->_decAmountStandard = $totalAmountStandard;
  459. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  460. $db = \Yii::$app->db;
  461. $transaction = $db->beginTransaction();
  462. try {
  463. //判断用户余额是否充足
  464. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  465. if ($result['code'] !== 200) {
  466. throw new Exception($result['message']);
  467. }
  468. /**
  469. * 2022-04-28
  470. * York
  471. * 支付后减少库存
  472. */
  473. foreach ($this->goodsNum as $k => $v){
  474. if ($v){
  475. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  476. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  477. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  478. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  479. $data->STORE_NUMS = $goods_store_nums;
  480. $data->update();
  481. //下单后库存小于等于0 商品下架
  482. if($goods_store_nums <= 0){
  483. $data->STATUS = 0;
  484. $data->UPDATED_AT = Date::nowTime();
  485. $data->update();
  486. }
  487. }else{
  488. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  489. }
  490. }
  491. }
  492. // exit();
  493. //写入订单
  494. if (!$orderResult = $this->addOrder()) {
  495. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  496. }
  497. $transaction->commit();
  498. return $orderResult;
  499. }catch (\Exception $e){
  500. $transaction->rollBack();
  501. $this->addError('add', $e->getMessage());
  502. return null;
  503. }
  504. }
  505. /**
  506. * 判断对应账户余额是否充足.
  507. * @param $payType string 支付方式.
  508. * @param $payAmount numeric 支付金额
  509. * @return array|int[]
  510. */
  511. public function getBalanceAdequate(string $payType, $payAmount): array
  512. {
  513. $loginUserId = \Yii::$app->user->id;
  514. if ($payType == 'cash') {
  515. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  516. return ['code' => 500, 'message' => '余额不足,无法购买商品'];
  517. }
  518. } else if ($payType =='exchange') {
  519. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  520. return ['code' => 500, 'message' => '兑换积分不足,无法购买商品'];
  521. }
  522. } else if ($payType == 'tourism_points') {
  523. if ($payAmount > Balance::getBalanceTourism($loginUserId)) {
  524. return ['code' => 500, 'message' => '旅游积分不足,无法购买商品'];
  525. }
  526. } else if ($payType == 'garage_points') {
  527. if ($payAmount > Balance::getBalanceGarage($loginUserId)) {
  528. return ['code' => 500, 'message' => '车房积分不足,无法购买商品'];
  529. }
  530. } else{
  531. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  532. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  533. // }
  534. }
  535. return ['code' => 200];
  536. }
  537. /**
  538. * 复销订单
  539. * @throws Exception
  540. */
  541. public function addOrder(){
  542. $periodObj = Period::instance();
  543. $nowPeriodNum = $periodObj->getNowPeriodNum();
  544. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  545. $userId = \Yii::$app->user->id;
  546. $userName = Info::getUserNameByUserId($userId);
  547. $userRealName = Info::getUserRealNameByUserId($userId);
  548. $userMobile = Info::getUserMobileByUserId($userId);
  549. $userEmail = Info::getUserEmailByUserId($userId);
  550. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  551. // 加入订单信息
  552. if ($this->_address['PROVINCE'] != 1) {
  553. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  554. if (!$warehouse) {
  555. throw new Exception('地区2暂时不支持配送,具体联系客服');
  556. }
  557. }else{
  558. $warehouse = '01';
  559. }
  560. $_hasPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_decPv;
  561. $ordNo = $this->_generateSn();
  562. $orderModel = new Order();
  563. $orderModel->SN = 'OS'.$ordNo;
  564. $orderModel->DEC_SN = 'DS'.$ordNo;
  565. $orderModel->ORDER_TYPE = $this->type;
  566. $orderModel->USER_ID = $userId;
  567. $orderModel->USER_NAME = $userName;
  568. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  569. $orderModel->PV = $_hasPV;
  570. $orderModel->PAY_AMOUNT = $this->_payAmount;
  571. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  572. $orderModel->PAY_AT = Date::nowTime();
  573. $orderModel->PAY_TYPE = $this->payType;
  574. $orderModel->PERIOD_NUM = $nowPeriodNum;
  575. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  576. $orderModel->FREIGHT = $this->_freight;
  577. $orderModel->PAY_FREIGHT = $this->_freight;
  578. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  579. $orderModel->MOBILE = $this->_address['MOBILE'];
  580. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  581. // $orderModel->CITY = $this->_address['CITY'];
  582. // $orderModel->COUNTY = $this->_address['COUNTY'];
  583. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  584. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  585. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  586. $orderModel->FRONT_REMARK = $this->remark;
  587. $orderModel->WAREHOUSE = $warehouse;
  588. $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  589. $orderModel->CREATED_AT = Date::nowTime();
  590. $orderModel->CREATE_USER = $userName;
  591. $orderModel->EMAIL = $userEmail ?? '';
  592. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  593. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  594. $orderModel->EXCHANGE_RATE = $exchangeRate;
  595. if($this->_address['PROVINCE']==1){
  596. $orderModel->EXPRESS_TYPE = 1;
  597. $orderModel->CONSIGNEE = $userRealName;
  598. $orderModel->MOBILE = $userMobile;
  599. $orderModel->PROVINCE = 1;
  600. $orderModel->CITY = 1;
  601. $orderModel->COUNTY = 1;
  602. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  603. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  604. $orderModel->ADDRESS = 'Self Pick-up';
  605. }
  606. if(!$orderModel->save()){
  607. $this->addErrors($orderModel->getErrors());
  608. return false;
  609. }
  610. // 加入商品到订单商品表
  611. foreach($this->_orderGoods as $key=>$value){
  612. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  613. if (in_array($orderModel->PAY_TYPE, ['exchange', 'tourism_points', 'garage_points'])) {
  614. $this->_orderGoods[$key]['REAL_PV'] = 0;
  615. }
  616. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  617. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  618. }
  619. OrderGoods::batchInsert($this->_orderGoods);
  620. //扣除会员余额/积分
  621. if($this->payType=='cash') {
  622. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  623. } else if ($this->payType=='exchange') {
  624. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
  625. } else if ($this->payType == 'tourism_points') {
  626. Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']);
  627. } else if ($this->payType == 'garage_points') {
  628. Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']);
  629. } else if ($this->payType == 'reconsume_points') {
  630. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
  631. }
  632. return $orderModel;
  633. }
  634. /**
  635. * 帮会员复销
  636. * @return bool|null
  637. * @throws Exception
  638. * @throws \yii\db\Exception
  639. */
  640. public function reconsumeAdd(){
  641. if(!$this->validate()){
  642. return null;
  643. }
  644. $ids = $this->goodsId;
  645. $totalAmount = 0;
  646. $totalPv = 0;
  647. $goodsType = ShopGoods::GOODS_TYPE;
  648. foreach ($this->goodsNum as $k => $v) {
  649. if ($v) {
  650. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  651. if($goods['STORE_NUMS']>0){
  652. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  653. $discount = $goodsType[$goods['TYPE']]['discount'];
  654. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  655. $realPv = $goods['PRICE_PV'] * $discount/100;
  656. } else {
  657. $discount = $goods['SELL_DISCOUNT'];
  658. $realPrice = $goods['SELL_PRICE'] * $discount;
  659. $realPv = $goods['PRICE_PV'] * $discount;
  660. }
  661. $totalAmount += $realPrice * intval($v);
  662. $totalPv += $realPv * intval($v);
  663. $this->_orderGoods[] = [
  664. 'GOODS_ID' => $goods['ID'],
  665. 'PRICE' => $goods['SELL_PRICE'],
  666. 'PV' => $goods['PRICE_PV'],
  667. 'REAL_PRICE' => $realPrice,
  668. 'REAL_PV' => $realPv,
  669. 'POINT' => $goods['POINT'],
  670. 'BUY_NUMS' => intval($v),
  671. 'SKU_CODE' => $goods['GOODS_NO'],
  672. 'GOODS_TITLE' => $goods['GOODS_NAME']
  673. ];
  674. }
  675. }
  676. }
  677. $this->_decAmount = $totalAmount;
  678. $this->_decPv = $totalPv;
  679. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  680. if($this->_address['PROVINCE']==1){
  681. $this->_freight = 0;
  682. }
  683. $this->_payAmount = $this->_decAmount + $this->_freight;
  684. $db = \Yii::$app->db;
  685. $transaction = $db->beginTransaction();
  686. try {
  687. $loginUserId = \Yii::$app->user->id;
  688. //是否开启伞下会员限制
  689. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  690. if($isResaleUmbrella){
  691. $userId = Info::getUserIdByUserName($this->userName);
  692. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  693. if(!$userNetwork){
  694. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  695. }
  696. }
  697. //判断用户余额是否充足
  698. if($this->payType=='cash') {
  699. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  700. throw new Exception('余额不足,无法购买商品');
  701. }
  702. }else{
  703. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  704. throw new Exception('复消积分不足,无法购买商品');
  705. }
  706. }
  707. /**
  708. * 2022-04-28
  709. * York
  710. * 支付后减少库存
  711. */
  712. foreach ($this->goodsNum as $k => $v){
  713. if ($v){
  714. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  715. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  716. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  717. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  718. $data->STORE_NUMS = $goods_store_nums;
  719. $data->update();
  720. //下单后库存小于等于0 商品下架
  721. if($goods_store_nums <= 0){
  722. $data->STATUS = 0;
  723. $data->UPDATED_AT = Date::nowTime();
  724. $data->update();
  725. }
  726. }else{
  727. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  728. }
  729. }
  730. }
  731. // exit();
  732. //写入订单
  733. if (!$orderResult = $this->addUserOrder()) {
  734. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  735. }
  736. $transaction->commit();
  737. }catch (\Exception $e){
  738. $transaction->rollBack();
  739. $this->addError('add', $e->getMessage());
  740. return null;
  741. }
  742. return true;
  743. }
  744. /**
  745. * 帮会员复消的订单
  746. */
  747. public function addUserOrder(){
  748. $periodObj = Period::instance();
  749. $nowPeriodNum = $periodObj->getNowPeriodNum();
  750. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  751. //帮复消会员Id(登陆会员)
  752. $loginUserId = \Yii::$app->user->id;
  753. $loginUserName = Info::getUserNameByUserId($loginUserId);
  754. //订单会员Id
  755. $userId = Info::getUserIdByUserName($this->userName);
  756. $email = Info::getEmailByUserId($this->userName);
  757. // 加入订单信息
  758. if($this->province!=1){
  759. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  760. if(!$warehouse){
  761. throw new Exception('地区1暂时不支持配送,具体联系客服');
  762. }
  763. }else{
  764. $warehouse = '01';
  765. }
  766. $ordNo = $this->_generateSn();
  767. $orderModel = new Order();
  768. $orderModel->SN = 'OS'.$ordNo;
  769. $orderModel->DEC_SN = 'DS'.$ordNo;
  770. $orderModel->ORDER_TYPE = $this->type;
  771. $orderModel->USER_ID = $userId;
  772. $orderModel->USER_NAME = $this->userName;
  773. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  774. $orderModel->PV = $this->_decPv;
  775. $orderModel->PAY_AMOUNT = $this->_payAmount;
  776. $orderModel->PAY_PV = $this->_decPv;
  777. $orderModel->PAY_AT = Date::nowTime();
  778. $orderModel->PAY_TYPE = $this->payType;
  779. $orderModel->PERIOD_NUM = $nowPeriodNum;
  780. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  781. $orderModel->FREIGHT = $this->_freight;
  782. $orderModel->PAY_FREIGHT = $this->_freight;
  783. $orderModel->CONSIGNEE = $this->consignee;
  784. $orderModel->MOBILE = $this->acceptMobile;
  785. $orderModel->PROVINCE = $this->province;
  786. // $orderModel->CITY = $this->city;
  787. // $orderModel->COUNTY = $this->county;
  788. $orderModel->ADDRESS = $this->detailaddress;
  789. $orderModel->FRONT_REMARK = $this->remark;
  790. $orderModel->WAREHOUSE = $warehouse;
  791. $orderModel->STATUS = 1;
  792. $orderModel->CREATED_AT = Date::nowTime();
  793. $orderModel->CREATE_USER = $loginUserName;
  794. $orderModel->EMAIL = $email?$email:'tt@qq.com';
  795. if(!$orderModel->save()){
  796. $this->addErrors($orderModel->getErrors());
  797. return false;
  798. }
  799. // 加入商品到订单商品表
  800. foreach($this->_orderGoods as $key=>$value){
  801. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  802. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  803. }
  804. OrderGoods::batchInsert($this->_orderGoods);
  805. //扣除会员余额/积分
  806. if($this->payType=='cash') {
  807. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  808. }else{
  809. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  810. }
  811. return $orderModel;
  812. }
  813. /**
  814. * 生成流水号
  815. * @return string
  816. */
  817. private function _generateSn() {
  818. return Date::today('Ymd') . $this->_random(10, 1);
  819. }
  820. /**
  821. * 生成随机数
  822. * @param $length
  823. * @param int $numeric
  824. * @return string
  825. */
  826. private function _random($length, $numeric = 0) {
  827. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  828. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  829. $hash = '';
  830. $max = strlen($seed) - 1;
  831. for ($i = 0; $i < $length; $i++) {
  832. $hash .= $seed[mt_rand(0, $max)];
  833. }
  834. return $hash;
  835. }
  836. }