OrderForm.php 48 KB

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