OrderForm.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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' => 'Order Code', // 订单号
  87. 'expressCompany' => '快递公司',
  88. 'orderTrackNo' => '快递单号',
  89. 'status' => 'State', // 状态
  90. 'remark' => 'Remark', // 备注
  91. 'type' => 'Order Type',// 订单类型
  92. 'addressId' => 'Shipping address',// 收货地址
  93. 'payType' => 'Pay Type',// 支付方式
  94. 'goodsId' => 'Product ID',//商品ID
  95. 'goodsNum' => 'Product quantity',//商品数量
  96. 'userName' => 'Repeat sales Member No. does not exist',//复消会员编号
  97. 'consignee' => 'Consignee',// 收货人
  98. 'acceptMobile' => 'Accept Mobile',// 收货电话
  99. 'province' => 'Province',// 省
  100. 'city' => 'City',// 市
  101. 'county' => 'County',// 区
  102. 'lgaName' => 'Lga Name',
  103. 'cityName' => 'City Name',
  104. 'detailaddress' => 'Address',// 收货详细地址
  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. $sysConfig = Cache::getSystemConfig();
  397. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  398. if($oPv>$mesureUpCondition){
  399. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  400. $remainPv = $oPv - $currentPv;
  401. }else{
  402. $currentPv = $oPv;
  403. $remainPv = 0;
  404. }
  405. return [
  406. 'current' => $currentPv,
  407. 'remain' => $remainPv
  408. ];
  409. }
  410. /**
  411. * 复销
  412. * @throws Exception
  413. * @throws \yii\db\Exception
  414. */
  415. public function add(){
  416. if(!$this->validate()){
  417. return null;
  418. }
  419. $ids = $this->goodsId;
  420. $totalAmount = 0;
  421. $totalPv = 0;
  422. $totalRealPv = 0;
  423. $totalAmountStandard = 0;
  424. $goodsType = ShopGoods::GOODS_TYPE;
  425. $this->_remainPv = 0;
  426. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  427. foreach ($this->goodsNum as $k => $v) {
  428. if ($v) {
  429. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  430. if (!$goods) {
  431. throw new Exception('Products does not exists!');
  432. }
  433. if($goods['STORE_NUMS']>0){
  434. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  435. $discount = $goodsType[$goods['TYPE']]['discount'];
  436. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  437. $realPv = $goods['PRICE_PV'] * $discount/100;
  438. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  439. } else {
  440. $discount = $goods['SELL_DISCOUNT'];
  441. $realPrice = $goods['SELL_PRICE'] * $discount;
  442. $realPv = $goods['PRICE_PV'] * $discount;
  443. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  444. }
  445. if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
  446. $pvSplit = $this->_pvSplit($realPv);
  447. $currentPv = $pvSplit['current'];
  448. $remainPv = $pvSplit['remain'];
  449. $totalPv += $currentPv * intval($v);
  450. $totalRealPv += $realPv * intval($v);
  451. $this->_remainPv += $remainPv * intval($v);
  452. }else{
  453. $currentPv = $goods['PRICE_PV'];
  454. $totalPv += $realPv * intval($v);
  455. $totalRealPv += $realPv * intval($v);
  456. $remainPv = 0;
  457. $this->_remainPv += 0;
  458. }
  459. $totalAmount += $realPrice * intval($v);
  460. $totalAmountStandard += $realPriceStandard * intval($v);
  461. // if($this->payType=='cash') {
  462. // $discount = $goodsType[$goods['TYPE']]['discount'];
  463. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  464. // $realPv = $goods['PRICE_PV'] * $discount/100;
  465. // $totalAmount += $realPrice * intval($v);
  466. // $totalPv += $realPv * intval($v);
  467. // }else{
  468. // $realPrice = $goods['SELL_PRICE'];
  469. // $realPv = $goods['PRICE_PV'];
  470. // $totalAmount += $realPrice * intval($v);
  471. // $totalPv += $realPv * intval($v);
  472. // }
  473. $this->_orderGoods[] = [
  474. 'GOODS_ID' => $goods['ID'],
  475. 'PRICE' => $goods['SELL_PRICE'],
  476. 'PV' => $currentPv, // $goods['PRICE_PV'],
  477. 'REAL_PRICE' => $realPrice,
  478. 'REAL_PV' => $realPv,
  479. 'REMAIN_PV' => $remainPv,
  480. 'POINT' => $goods['POINT'],
  481. 'BUY_NUMS' => intval($v),
  482. 'SKU_CODE' => $goods['GOODS_NO'],
  483. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  484. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  485. 'PAY_TYPE' => $this->payType,
  486. 'EMAIL' => $this->email,
  487. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  488. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  489. 'EXCHANGE_RATE' => $exchangeRate,
  490. 'TAX_RATE' => $goods['TAX_RATE'],
  491. ];
  492. }
  493. }
  494. }
  495. // 汇率
  496. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  497. // 运费.美元转奈拉
  498. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  499. // 普通商品免运费阈值.美元转奈拉
  500. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  501. $this->_decAmount = $totalAmount;
  502. $this->_decPv = $totalPv;
  503. $this->_realPv = $totalRealPv;
  504. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  505. if($this->_address['PROVINCE']==1){
  506. $this->_freight = 0;
  507. }
  508. $this->_payAmount = $this->_decAmount + $this->_freight;
  509. $this->_decAmountStandard = $totalAmountStandard;
  510. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  511. $db = \Yii::$app->db;
  512. $transaction = $db->beginTransaction();
  513. try {
  514. //判断用户余额是否充足
  515. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  516. if ($result['code'] !== 200) {
  517. throw new Exception($result['message']);
  518. }
  519. /**
  520. * 2022-04-28
  521. * York
  522. * 支付后减少库存
  523. */
  524. foreach ($this->goodsNum as $k => $v){
  525. if ($v){
  526. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  527. if (!$goods) {
  528. throw new Exception('Products does not exists!');
  529. }
  530. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  531. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  532. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  533. $data->STORE_NUMS = $goods_store_nums;
  534. $data->update();
  535. //下单后库存小于等于0 商品下架
  536. if($goods_store_nums <= 0){
  537. $data->STATUS = 0;
  538. $data->UPDATED_AT = Date::nowTime();
  539. $data->update();
  540. }
  541. }else{
  542. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  543. }
  544. }
  545. }
  546. //写入订单
  547. if (!$orderResult = $this->addOrder()) {
  548. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  549. }
  550. $transaction->commit();
  551. return $orderResult;
  552. }catch (\Exception $e){
  553. $transaction->rollBack();
  554. $this->addError('add', $e->getMessage());
  555. return null;
  556. }
  557. }
  558. /**
  559. * 判断对应账户余额是否充足.
  560. * @param $payType string 支付方式.
  561. * @param $payAmount numeric 支付金额
  562. * @return array|int[]
  563. */
  564. public function getBalanceAdequate(string $payType, $payAmount): array
  565. {
  566. $loginUserId = \Yii::$app->user->id;
  567. if ($payType == 'cash') {
  568. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  569. return ['code' => 500, 'message' => '余额不足,无法购买商品'];
  570. }
  571. } else if ($payType =='exchange') {
  572. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  573. return ['code' => 500, 'message' => '兑换积分不足,无法购买商品'];
  574. }
  575. } else if ($payType == 'tourism_points') {
  576. if ($payAmount > Balance::getBalanceTourism($loginUserId)) {
  577. return ['code' => 500, 'message' => '旅游积分不足,无法购买商品'];
  578. }
  579. } else if ($payType == 'garage_points') {
  580. if ($payAmount > Balance::getBalanceGarage($loginUserId)) {
  581. return ['code' => 500, 'message' => '车房积分不足,无法购买商品'];
  582. }
  583. // } else{
  584. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  585. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  586. // }
  587. }
  588. return ['code' => 200];
  589. }
  590. /**
  591. * 复销订单
  592. * @throws Exception
  593. */
  594. public function addOrder(){
  595. $periodObj = Period::instance();
  596. $nowPeriodNum = $periodObj->getNowPeriodNum();
  597. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  598. $userId = \Yii::$app->user->id;
  599. $userName = Info::getUserNameByUserId($userId);
  600. $userRealName = Info::getUserRealNameByUserId($userId);
  601. $userMobile = Info::getUserMobileByUserId($userId);
  602. $userEmail = Info::getUserEmailByUserId($userId);
  603. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  604. // 加入订单信息
  605. if ($this->_address['PROVINCE'] != 1) {
  606. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  607. if (!$warehouse) {
  608. throw new Exception('地区2暂时不支持配送,具体联系客服');
  609. }
  610. }else{
  611. $warehouse = '01';
  612. }
  613. $_hasPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_decPv;
  614. $_hasRealPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_realPv;
  615. $ordNo = $this->_generateSn();
  616. $orderModel = new Order();
  617. $orderModel->SN = 'OS'.$ordNo;
  618. $orderModel->DEC_SN = 'DS'.$ordNo;
  619. $orderModel->ORDER_TYPE = $this->type;
  620. $orderModel->USER_ID = $userId;
  621. $orderModel->USER_NAME = $userName;
  622. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  623. $orderModel->PV = $_hasPV;
  624. $orderModel->PAY_AMOUNT = $this->_payAmount;
  625. $orderModel->PAY_PV = $_hasRealPV; // 兑换积分不能算业绩
  626. $orderModel->REMAIN_PV = $this->_remainPv;
  627. $orderModel->PAY_AT = Date::nowTime();
  628. $orderModel->PAY_TYPE = $this->payType;
  629. $orderModel->PERIOD_NUM = $nowPeriodNum;
  630. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  631. $orderModel->FREIGHT = $this->_freight;
  632. $orderModel->PAY_FREIGHT = $this->_freight;
  633. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  634. $orderModel->MOBILE = $this->_address['MOBILE'];
  635. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  636. // $orderModel->CITY = $this->_address['CITY'];
  637. // $orderModel->COUNTY = $this->_address['COUNTY'];
  638. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  639. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  640. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  641. $orderModel->FRONT_REMARK = $this->remark;
  642. $orderModel->WAREHOUSE = $warehouse;
  643. $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  644. $orderModel->CREATED_AT = Date::nowTime();
  645. $orderModel->CREATE_USER = $userName;
  646. $orderModel->EMAIL = $userEmail ?? '';
  647. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  648. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  649. $orderModel->EXCHANGE_RATE = $exchangeRate;
  650. if($this->_address['PROVINCE']==1){
  651. $orderModel->EXPRESS_TYPE = 1;
  652. $orderModel->CONSIGNEE = $userRealName;
  653. $orderModel->MOBILE = $userMobile;
  654. $orderModel->PROVINCE = 1;
  655. $orderModel->CITY = 1;
  656. $orderModel->COUNTY = 1;
  657. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  658. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  659. $orderModel->ADDRESS = 'Self Pick-up';
  660. }
  661. if(!$orderModel->save()){
  662. $this->addErrors($orderModel->getErrors());
  663. return false;
  664. }
  665. // 加入商品到订单商品表
  666. foreach($this->_orderGoods as $key=>$value){
  667. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  668. if (in_array($orderModel->PAY_TYPE, ['exchange', 'tourism_points', 'garage_points'])) {
  669. $this->_orderGoods[$key]['REAL_PV'] = 0;
  670. }
  671. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  672. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  673. }
  674. OrderGoods::batchInsert($this->_orderGoods);
  675. //扣除会员余额/积分
  676. if($this->payType=='cash') {
  677. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment']); // 会员复销余额支付
  678. } else if ($this->payType=='exchange') {
  679. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
  680. } else if ($this->payType == 'tourism_points') {
  681. Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']);
  682. } else if ($this->payType == 'garage_points') {
  683. Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']);
  684. } else if ($this->payType == 'villa_points') {
  685. Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换']);
  686. } else if ($this->payType == 'reconsume_points') {
  687. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
  688. }
  689. // if($this->_remainPv>0) {
  690. // $oRemainPv = RemainPv::find()->where(['USER_ID' => $userId])->one();
  691. //
  692. // $transactionRemain = \Yii::$app->db->beginTransaction();
  693. // try{
  694. // $flowRemainPvModel = new FlowRemainPv();
  695. // $flowRemainPvModel->ID = $this->_generateSn();
  696. // $flowRemainPvModel->USER_ID = $userId;
  697. // $flowRemainPvModel->REMAIN_PV_FLOW = $this->_remainPv;
  698. // $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv['REMAIN_PV'] + $this->_remainPv;
  699. // $flowRemainPvModel->PERIOD_NUM = $nowPeriodNum;
  700. // $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  701. // $flowRemainPvModel->ORDER_SN = 'OS'.$ordNo;
  702. // if(!$flowRemainPvModel->save()){
  703. // $this->addErrors($flowRemainPvModel->getErrors());
  704. // return false;
  705. // }
  706. //
  707. // $oRemainPv = RemainPv::find()->where(['USER_ID' => $userId])->one();
  708. // if($oRemainPv){
  709. // $oRemainPv->updateCounters(['REMAIN_PV'=>$this->_remainPv]);
  710. // }else{
  711. // $remainPvModel = new RemainPv();
  712. // $remainPvModel->ID = $this->_generateSn();
  713. // $remainPvModel->USER_ID = $userId;
  714. // $remainPvModel->UPDATED_AT = Date::nowTime();
  715. // $remainPvModel->REMAIN_PV = $this->_remainPv;
  716. // $remainPvModel->STATUS = 1;
  717. // if(!$remainPvModel->save()){
  718. // $this->addErrors($remainPvModel->getErrors());
  719. // return false;
  720. // }
  721. // }
  722. // $transactionRemain->commit();
  723. // } catch (Exception $e) {
  724. // $transactionRemain->rollBack();
  725. // $this->addError('add', $e->getMessage());
  726. // return null;
  727. // }
  728. // }
  729. return $orderModel;
  730. }
  731. /**
  732. * 帮会员复销
  733. * @return bool|null
  734. * @throws Exception
  735. * @throws \yii\db\Exception
  736. */
  737. public function reconsumeAdd(){
  738. if(!$this->validate()){
  739. return null;
  740. }
  741. $ids = $this->goodsId;
  742. $totalAmount = 0;
  743. $totalPv = 0;
  744. $goodsType = ShopGoods::GOODS_TYPE;
  745. foreach ($this->goodsNum as $k => $v) {
  746. if ($v) {
  747. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  748. if (!$goods) {
  749. throw new Exception('Products does not exists!');
  750. }
  751. if($goods['STORE_NUMS']>0){
  752. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  753. $discount = $goodsType[$goods['TYPE']]['discount'];
  754. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  755. $realPv = $goods['PRICE_PV'] * $discount/100;
  756. } else {
  757. $discount = $goods['SELL_DISCOUNT'];
  758. $realPrice = $goods['SELL_PRICE'] * $discount;
  759. $realPv = $goods['PRICE_PV'] * $discount;
  760. }
  761. $totalAmount += $realPrice * intval($v);
  762. $totalPv += $realPv * intval($v);
  763. $this->_orderGoods[] = [
  764. 'GOODS_ID' => $goods['ID'],
  765. 'PRICE' => $goods['SELL_PRICE'],
  766. 'PV' => $goods['PRICE_PV'],
  767. 'REAL_PRICE' => $realPrice,
  768. 'REAL_PV' => $realPv,
  769. 'POINT' => $goods['POINT'],
  770. 'BUY_NUMS' => intval($v),
  771. 'SKU_CODE' => $goods['GOODS_NO'],
  772. 'GOODS_TITLE' => $goods['GOODS_NAME']
  773. ];
  774. }
  775. }
  776. }
  777. $this->_decAmount = $totalAmount;
  778. $this->_decPv = $totalPv;
  779. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  780. if($this->_address['PROVINCE']==1){
  781. $this->_freight = 0;
  782. }
  783. $this->_payAmount = $this->_decAmount + $this->_freight;
  784. $db = \Yii::$app->db;
  785. $transaction = $db->beginTransaction();
  786. try {
  787. $loginUserId = \Yii::$app->user->id;
  788. //是否开启伞下会员限制
  789. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  790. if($isResaleUmbrella){
  791. $userId = Info::getUserIdByUserName($this->userName);
  792. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  793. if(!$userNetwork){
  794. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  795. }
  796. }
  797. //判断用户余额是否充足
  798. if($this->payType=='cash') {
  799. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  800. throw new Exception('余额不足,无法购买商品');
  801. }
  802. }else{
  803. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  804. throw new Exception('复消积分不足,无法购买商品');
  805. }
  806. }
  807. /**
  808. * 2022-04-28
  809. * York
  810. * 支付后减少库存
  811. */
  812. foreach ($this->goodsNum as $k => $v){
  813. if ($v){
  814. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  815. if (!$goods) {
  816. throw new Exception('Products does not exists!');
  817. }
  818. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  819. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  820. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  821. $data->STORE_NUMS = $goods_store_nums;
  822. $data->update();
  823. //下单后库存小于等于0 商品下架
  824. if($goods_store_nums <= 0){
  825. $data->STATUS = 0;
  826. $data->UPDATED_AT = Date::nowTime();
  827. $data->update();
  828. }
  829. }else{
  830. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  831. }
  832. }
  833. }
  834. // exit();
  835. //写入订单
  836. if (!$orderResult = $this->addUserOrder()) {
  837. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  838. }
  839. $transaction->commit();
  840. }catch (\Exception $e){
  841. $transaction->rollBack();
  842. $this->addError('add', $e->getMessage());
  843. return null;
  844. }
  845. return true;
  846. }
  847. /**
  848. * 帮会员复消的订单
  849. */
  850. public function addUserOrder(){
  851. $periodObj = Period::instance();
  852. $nowPeriodNum = $periodObj->getNowPeriodNum();
  853. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  854. //帮复消会员Id(登陆会员)
  855. $loginUserId = \Yii::$app->user->id;
  856. $loginUserName = Info::getUserNameByUserId($loginUserId);
  857. //订单会员Id
  858. $userId = Info::getUserIdByUserName($this->userName);
  859. $email = Info::getEmailByUserId($this->userName);
  860. // 加入订单信息
  861. if($this->province!=1){
  862. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  863. if(!$warehouse){
  864. throw new Exception('地区1暂时不支持配送,具体联系客服');
  865. }
  866. }else{
  867. $warehouse = '01';
  868. }
  869. $ordNo = $this->_generateSn();
  870. $orderModel = new Order();
  871. $orderModel->SN = 'OS'.$ordNo;
  872. $orderModel->DEC_SN = 'DS'.$ordNo;
  873. $orderModel->ORDER_TYPE = $this->type;
  874. $orderModel->USER_ID = $userId;
  875. $orderModel->USER_NAME = $this->userName;
  876. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  877. $orderModel->PV = $this->_decPv;
  878. $orderModel->PAY_AMOUNT = $this->_payAmount;
  879. $orderModel->PAY_PV = $this->_decPv;
  880. $orderModel->PAY_AT = Date::nowTime();
  881. $orderModel->PAY_TYPE = $this->payType;
  882. $orderModel->PERIOD_NUM = $nowPeriodNum;
  883. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  884. $orderModel->FREIGHT = $this->_freight;
  885. $orderModel->PAY_FREIGHT = $this->_freight;
  886. $orderModel->CONSIGNEE = $this->consignee;
  887. $orderModel->MOBILE = $this->acceptMobile;
  888. $orderModel->PROVINCE = $this->province;
  889. // $orderModel->CITY = $this->city;
  890. // $orderModel->COUNTY = $this->county;
  891. $orderModel->ADDRESS = $this->detailaddress;
  892. $orderModel->FRONT_REMARK = $this->remark;
  893. $orderModel->WAREHOUSE = $warehouse;
  894. $orderModel->STATUS = 1;
  895. $orderModel->CREATED_AT = Date::nowTime();
  896. $orderModel->CREATE_USER = $loginUserName;
  897. $orderModel->EMAIL = $email;
  898. if(!$orderModel->save()){
  899. $this->addErrors($orderModel->getErrors());
  900. return false;
  901. }
  902. // 加入商品到订单商品表
  903. foreach($this->_orderGoods as $key=>$value){
  904. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  905. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  906. }
  907. OrderGoods::batchInsert($this->_orderGoods);
  908. //扣除会员余额/积分
  909. if($this->payType=='cash') {
  910. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment']); // 会员复销余额支付
  911. }else{
  912. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  913. }
  914. return $orderModel;
  915. }
  916. /**
  917. * 生成流水号
  918. * @return string
  919. */
  920. private function _generateSn() {
  921. return Date::today('Ymd') . $this->_random(10, 1);
  922. }
  923. /**
  924. * 生成随机数
  925. * @param $length
  926. * @param int $numeric
  927. * @return string
  928. */
  929. private function _random($length, $numeric = 0) {
  930. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  931. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  932. $hash = '';
  933. $max = strlen($seed) - 1;
  934. for ($i = 0; $i < $length; $i++) {
  935. $hash .= $seed[mt_rand(0, $max)];
  936. }
  937. return $hash;
  938. }
  939. public function addFakeOrder($userId, $periodNum){
  940. $userName = Info::getUserNameByUserId($userId);
  941. $sysConfig = Cache::getSystemConfig();
  942. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  943. $ordNo = $this->_generateSn();
  944. $orderModel = new Order();
  945. $orderModel->SN = 'OS'.$ordNo;
  946. $orderModel->DEC_SN = 'DS'.$ordNo;
  947. $orderModel->USER_ID = $userId;
  948. $orderModel->USER_NAME = $userName;
  949. $orderModel->PERIOD_NUM = $periodNum;
  950. $orderModel->CREATE_USER = 'AUTO';
  951. $orderModel->ORDER_TYPE = 'FX';
  952. $orderModel->STATUS = 1;
  953. $orderModel->PV = $mesureUpCondition;
  954. $orderModel->PAY_PV = $mesureUpCondition;
  955. $orderModel->P_CALC_MONTH = '1970-01-01';
  956. $orderModel->CREATED_AT = Date::nowTime();
  957. $orderModel->EXPRESS_TYPE = 1;
  958. $orderModel->IS_AUTO = 1;
  959. if(!$orderModel->save()){
  960. $this->addErrors($orderModel->getErrors());
  961. return false;
  962. }
  963. return $orderModel;
  964. }
  965. }