OrderForm.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 $period;
  45. public $userName;
  46. public $decUserName;
  47. public $consignee;
  48. public $acceptMobile;
  49. public $province;
  50. public $city;
  51. public $lgaName;
  52. public $cityName;
  53. public $county;
  54. public $detailaddress;
  55. private $_address;
  56. private $_decAmount;
  57. private $_decPv;
  58. private $_freight;
  59. private $_payAmount;
  60. private $_orderGoods;
  61. private $_standardAmount;
  62. private $_decAmountStandard;
  63. private $_exchangeRate;
  64. private $_remainPv;
  65. private $_realPv;
  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', 'period'],
  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. }