OrderForm.php 40 KB

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