OrderForm.php 40 KB

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