OrderForm.php 48 KB

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