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