OrderForm.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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. }
  531. $hasInstalment = $goods['INSTALMENT'];
  532. }
  533. }
  534. }
  535. // 运费.美元转奈拉
  536. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  537. // 普通商品免运费阈值.美元转奈拉
  538. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  539. $this->_decAmount = $totalAmount;
  540. $this->_decPv = $totalPv;
  541. $this->_realPv = $totalRealPv;
  542. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  543. if($this->_address['PROVINCE']==1){
  544. $this->_freight = 0;
  545. }
  546. $this->_payAmount = $this->_decAmount + $this->_freight;
  547. $this->_decAmountStandard = $totalAmountStandard;
  548. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  549. $db = \Yii::$app->db;
  550. $transaction = $db->beginTransaction();
  551. try {
  552. //判断用户余额是否充足
  553. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  554. if ($result['code'] !== 200) {
  555. throw new Exception($result['message']);
  556. }
  557. /**
  558. * 2022-04-28
  559. * York
  560. * 支付后减少库存
  561. */
  562. foreach ($this->goodsNum as $k => $v){
  563. if ($v){
  564. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  565. if (!$goods) {
  566. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  567. }
  568. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  569. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  570. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  571. $data->STORE_NUMS = $goods_store_nums;
  572. $data->update();
  573. //下单后库存小于等于0 商品下架
  574. if($goods_store_nums <= 0){
  575. $data->STATUS = 0;
  576. $data->UPDATED_AT = Date::nowTime();
  577. $data->update();
  578. }
  579. }else{
  580. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  581. }
  582. }
  583. }
  584. //写入订单
  585. if (!$orderResult = $this->addOrder()) {
  586. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  587. }
  588. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  589. $instalmentModel = Instalment::findOne(['USER_ID'=>$loginUserId]);
  590. if(!$instalmentModel) {
  591. $instalmentModel = new Instalment();
  592. }
  593. $instalmentModel->USER_ID = $loginUserId;
  594. $instalmentModel->STAGE = $hasInstalment;
  595. $instalmentModel->ORDER_TYPE = 'FX';
  596. $instalmentModel->UPDATE_TIME = time();
  597. $instalmentModel->save();
  598. }
  599. $transaction->commit();
  600. return $orderResult;
  601. }catch (\Exception $e){
  602. $transaction->rollBack();
  603. $this->addError('add', $e->getMessage());
  604. return null;
  605. }
  606. }
  607. /**
  608. * 判断对应账户余额是否充足.
  609. * @param $payType string 支付方式.
  610. * @param $payAmount numeric 支付金额
  611. * @return array|int[]
  612. */
  613. public function getBalanceAdequate(string $payType, $payAmount): array
  614. {
  615. $loginUserId = \Yii::$app->user->id;
  616. if ($payType == 'cash') {
  617. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  618. return ['code' => 500, 'message' => Yii::t('app', 'cashDoesNotAdequate')];
  619. }
  620. } else if ($payType =='exchange') {
  621. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  622. return ['code' => 500, 'message' => Yii::t('app', 'exchangePointDoesNotAdequate')];
  623. }
  624. } else if ($payType == 'tourism_points') {
  625. if ($payAmount > Balance::getBalanceTourism($loginUserId)) {
  626. return ['code' => 500, 'message' => Yii::t('app', 'travelPointDoesNotAdequate')];
  627. }
  628. } else if ($payType == 'garage_points') {
  629. if ($payAmount > Balance::getBalanceGarage($loginUserId)) {
  630. return ['code' => 500, 'message' => Yii::t('app', 'carFundPointDoesNotAdequate')];
  631. }
  632. // } else{
  633. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  634. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  635. // }
  636. }
  637. return ['code' => 200];
  638. }
  639. /**
  640. * 复销订单
  641. * @throws Exception
  642. */
  643. public function addOrder(){
  644. $periodObj = Period::instance();
  645. $nowPeriodNum = $periodObj->getNowPeriodNum();
  646. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  647. $userId = \Yii::$app->user->id;
  648. $userName = Info::getUserNameByUserId($userId);
  649. $userRealName = Info::getUserRealNameByUserId($userId);
  650. $userMobile = Info::getUserMobileByUserId($userId);
  651. $userEmail = Info::getUserEmailByUserId($userId);
  652. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  653. // 加入订单信息
  654. if ($this->_address['PROVINCE'] != 1) {
  655. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  656. if (!$warehouse) {
  657. throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  658. }
  659. }else{
  660. $warehouse = '01';
  661. }
  662. $_hasPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_decPv;
  663. $_hasRealPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_realPv;
  664. $ordNo = $this->_generateSn();
  665. $orderModel = new Order();
  666. $orderModel->SN = 'OS'.$ordNo;
  667. $orderModel->DEC_SN = 'DS'.$ordNo;
  668. $orderModel->ORDER_TYPE = $this->type;
  669. $orderModel->USER_ID = $userId;
  670. $orderModel->USER_NAME = $userName;
  671. $orderModel->DEC_USER_ID = $this->decUserName;;
  672. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  673. $orderModel->PV = $_hasPV;
  674. $orderModel->PAY_AMOUNT = $this->_payAmount;
  675. $orderModel->PAY_PV = $_hasRealPV; // 兑换积分不能算业绩
  676. $orderModel->REMAIN_PV = $this->_remainPv;
  677. $orderModel->PAY_AT = Date::nowTime();
  678. $orderModel->PAY_TYPE = $this->payType;
  679. $orderModel->PERIOD_NUM = $nowPeriodNum;
  680. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  681. $orderModel->FREIGHT = $this->_freight;
  682. $orderModel->PAY_FREIGHT = $this->_freight;
  683. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  684. $orderModel->MOBILE = $this->_address['MOBILE'];
  685. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  686. // $orderModel->CITY = $this->_address['CITY'];
  687. // $orderModel->COUNTY = $this->_address['COUNTY'];
  688. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  689. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  690. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  691. $orderModel->FRONT_REMARK = $this->remark;
  692. $orderModel->WAREHOUSE = $warehouse;
  693. $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  694. $orderModel->CREATED_AT = Date::nowTime();
  695. $orderModel->CREATE_USER = $userName;
  696. $orderModel->EMAIL = $userEmail ?? '';
  697. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  698. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  699. $orderModel->EXCHANGE_RATE = $exchangeRate;
  700. if($this->_address['PROVINCE']==1){
  701. $orderModel->EXPRESS_TYPE = 1;
  702. $orderModel->CONSIGNEE = $userRealName;
  703. $orderModel->MOBILE = $userMobile;
  704. $orderModel->PROVINCE = 1;
  705. $orderModel->CITY = 1;
  706. $orderModel->COUNTY = 1;
  707. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  708. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  709. $orderModel->ADDRESS = 'Self Pick-up';
  710. }
  711. if(!$orderModel->save()){
  712. $this->addErrors($orderModel->getErrors());
  713. return false;
  714. }
  715. // 加入商品到订单商品表
  716. foreach($this->_orderGoods as $key=>$value){
  717. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  718. if (in_array($orderModel->PAY_TYPE, ['exchange', 'tourism_points', 'garage_points'])) {
  719. $this->_orderGoods[$key]['REAL_PV'] = 0;
  720. }
  721. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  722. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  723. }
  724. OrderGoods::batchInsert($this->_orderGoods);
  725. //扣除会员余额/积分
  726. if($this->payType=='cash') {
  727. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment', 'ORDER_SN' => $orderModel->SN]); // 会员复销余额支付
  728. } else if ($this->payType=='exchange') {
  729. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换', 'ORDER_SN' => $orderModel->SN]);
  730. } else if ($this->payType == 'tourism_points') {
  731. Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换', 'ORDER_SN' => $orderModel->SN]);
  732. } else if ($this->payType == 'garage_points') {
  733. Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换', 'ORDER_SN' => $orderModel->SN]);
  734. } else if ($this->payType == 'villa_points') {
  735. Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换', 'ORDER_SN' => $orderModel->SN]);
  736. } else if ($this->payType == 'reconsume_points') {
  737. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换', 'ORDER_SN' => $orderModel->SN]);
  738. }
  739. // if($this->_remainPv>0) {
  740. // $oRemainPv = RemainPv::find()->where(['USER_ID' => $userId])->one();
  741. //
  742. // $transactionRemain = \Yii::$app->db->beginTransaction();
  743. // try{
  744. // $flowRemainPvModel = new FlowRemainPv();
  745. // $flowRemainPvModel->ID = $this->_generateSn();
  746. // $flowRemainPvModel->USER_ID = $userId;
  747. // $flowRemainPvModel->REMAIN_PV_FLOW = $this->_remainPv;
  748. // $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv['REMAIN_PV'] + $this->_remainPv;
  749. // $flowRemainPvModel->PERIOD_NUM = $nowPeriodNum;
  750. // $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  751. // $flowRemainPvModel->ORDER_SN = 'OS'.$ordNo;
  752. // if(!$flowRemainPvModel->save()){
  753. // $this->addErrors($flowRemainPvModel->getErrors());
  754. // return false;
  755. // }
  756. //
  757. // $oRemainPv = RemainPv::find()->where(['USER_ID' => $userId])->one();
  758. // if($oRemainPv){
  759. // $oRemainPv->updateCounters(['REMAIN_PV'=>$this->_remainPv]);
  760. // }else{
  761. // $remainPvModel = new RemainPv();
  762. // $remainPvModel->ID = $this->_generateSn();
  763. // $remainPvModel->USER_ID = $userId;
  764. // $remainPvModel->UPDATED_AT = Date::nowTime();
  765. // $remainPvModel->REMAIN_PV = $this->_remainPv;
  766. // $remainPvModel->STATUS = 1;
  767. // if(!$remainPvModel->save()){
  768. // $this->addErrors($remainPvModel->getErrors());
  769. // return false;
  770. // }
  771. // }
  772. // $transactionRemain->commit();
  773. // } catch (Exception $e) {
  774. // $transactionRemain->rollBack();
  775. // $this->addError('add', $e->getMessage());
  776. // return null;
  777. // }
  778. // }
  779. return $orderModel;
  780. }
  781. /**
  782. * 帮会员复销
  783. * @return bool|null
  784. * @throws Exception
  785. * @throws \yii\db\Exception
  786. */
  787. public function reconsumeAdd(){
  788. if(!$this->validate()){
  789. return null;
  790. }
  791. $ids = $this->goodsId;
  792. $totalAmount = 0;
  793. $totalPv = 0;
  794. $goodsType = ShopGoods::getGoodType();
  795. $hasInstalment = 0;
  796. $userId = Info::getUserIdByUserName($this->userName);
  797. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  798. foreach ($this->goodsNum as $k => $v) {
  799. if ($v) {
  800. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  801. if (!$goods) {
  802. throw new Exception('Products does not exists!');
  803. }
  804. if($goods['STORE_NUMS']>0){
  805. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  806. $discount = $goodsType[$goods['TYPE']]['discount'];
  807. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  808. $realPv = $goods['PRICE_PV'] * $discount/100;
  809. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  810. } else {
  811. $discount = $goods['SELL_DISCOUNT'];
  812. $realPrice = $goods['SELL_PRICE'] * $discount;
  813. $realPv = $goods['PRICE_PV'] * $discount;
  814. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  815. }
  816. $totalAmount += $realPrice * intval($v);
  817. $totalPv += $realPv * intval($v);
  818. $this->_orderGoods[] = [
  819. 'GOODS_ID' => $goods['ID'],
  820. 'PRICE' => $goods['SELL_PRICE'],
  821. 'PV' => $goods['PRICE_PV'],
  822. 'REAL_PRICE' => $realPrice,
  823. 'REAL_PV' => $realPv,
  824. 'POINT' => $goods['POINT'],
  825. 'BUY_NUMS' => intval($v),
  826. 'SKU_CODE' => $goods['GOODS_NO'],
  827. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  828. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  829. 'TAX_RATE' => $goods['TAX_RATE'],
  830. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  831. 'PAY_TYPE' => $this->payType ?? '',
  832. 'EMAIL' => $this->email ?? '',
  833. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  834. 'EXCHANGE_RATE' => $exchangeRate,
  835. ];
  836. }
  837. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  838. if($v>1){ // 不可以购买多个
  839. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  840. }
  841. $userStage = Instalment::getStage($userId);
  842. $userInstalmentInfo = Instalment::getInfo($userId);
  843. // 分期的总期数
  844. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  845. // 分期商品的期数不能大于总分期数限制
  846. if (intval($goods['INSTALMENT']) > $instalment) {
  847. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  848. }
  849. if ($userStage == $instalment){
  850. }else{
  851. if($userInstalmentInfo){
  852. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  853. throw new Exception(Yii::t('app', 'canNotBuy'));
  854. }
  855. }
  856. if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  857. throw new Exception(Yii::t('app', 'canNotBuy'));
  858. }
  859. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  860. throw new Exception(Yii::t('app', 'canNotBuy'));
  861. }
  862. }
  863. $hasInstalment = $goods['INSTALMENT'];
  864. }
  865. }
  866. }
  867. $this->_decAmount = $totalAmount;
  868. $this->_decPv = $totalPv;
  869. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  870. $this->_payAmount = $this->_decAmount + $this->_freight;
  871. $db = \Yii::$app->db;
  872. $transaction = $db->beginTransaction();
  873. try {
  874. $loginUserId = \Yii::$app->user->id;
  875. //是否开启伞下会员限制
  876. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  877. if($isResaleUmbrella){
  878. $userId = Info::getUserIdByUserName($this->userName);
  879. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  880. if(!$userNetwork){
  881. throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
  882. }
  883. }
  884. //判断用户余额是否充足
  885. if($this->payType=='cash') {
  886. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  887. throw new Exception(Yii::t('app', 'cashDoesNotAdequate'));
  888. }
  889. }else{
  890. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  891. throw new Exception(Yii::t('app', 'exchangePointDoesNotAdequate'));
  892. }
  893. }
  894. /**
  895. * 2022-04-28
  896. * York
  897. * 支付后减少库存
  898. */
  899. foreach ($this->goodsNum as $k => $v){
  900. if ($v){
  901. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  902. if (!$goods) {
  903. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  904. }
  905. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  906. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  907. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  908. $data->STORE_NUMS = $goods_store_nums;
  909. $data->update();
  910. //下单后库存小于等于0 商品下架
  911. if($goods_store_nums <= 0){
  912. $data->STATUS = 0;
  913. $data->UPDATED_AT = Date::nowTime();
  914. $data->update();
  915. }
  916. }else{
  917. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  918. }
  919. }
  920. }
  921. //写入订单
  922. if (!$orderResult = $this->addUserOrder()) {
  923. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  924. }
  925. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  926. $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
  927. if(!$instalmentModel) {
  928. $instalmentModel = new Instalment();
  929. }
  930. $instalmentModel->USER_ID = $userId;
  931. $instalmentModel->STAGE = $hasInstalment;
  932. $instalmentModel->ORDER_TYPE = 'FX';
  933. $instalmentModel->UPDATE_TIME = time();
  934. $instalmentModel->save();
  935. }
  936. $transaction->commit();
  937. }catch (\Exception $e){
  938. $transaction->rollBack();
  939. $this->addError('add', $e->getMessage());
  940. return null;
  941. }
  942. return true;
  943. }
  944. /**
  945. * 帮会员复消的订单
  946. */
  947. public function addUserOrder(){
  948. $periodObj = Period::instance();
  949. $nowPeriodNum = $periodObj->getNowPeriodNum();
  950. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  951. //帮复消会员Id(登陆会员)
  952. $loginUserId = \Yii::$app->user->id;
  953. $loginUserName = Info::getUserNameByUserId($loginUserId);
  954. //订单会员Id
  955. $userId = Info::getUserIdByUserName($this->userName);
  956. $email = Info::getEmailByUserId($this->userName);
  957. // 加入订单信息
  958. // if($this->province!=1){
  959. // $warehouse = Region::getWarehouseByCode($this->province);//仓库
  960. // if(!$warehouse){
  961. // throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  962. // }
  963. // }else{
  964. $warehouse = '01';
  965. // }
  966. $ordNo = $this->_generateSn();
  967. $orderModel = new Order();
  968. $orderModel->SN = 'OS'.$ordNo;
  969. $orderModel->DEC_SN = 'DS'.$ordNo;
  970. $orderModel->ORDER_TYPE = $this->type;
  971. $orderModel->ORDER_CATEGORY = 'STUDIO';
  972. $orderModel->USER_ID = $userId;
  973. $orderModel->USER_NAME = $this->userName;
  974. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  975. $orderModel->PV = $this->_decPv;
  976. $orderModel->PAY_AMOUNT = $this->_payAmount;
  977. $orderModel->PAY_PV = $this->_decPv;
  978. $orderModel->PAY_AT = Date::nowTime();
  979. $orderModel->PAY_TYPE = $this->payType;
  980. $orderModel->PERIOD_NUM = $nowPeriodNum;
  981. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  982. $orderModel->FREIGHT = $this->_freight;
  983. $orderModel->PAY_FREIGHT = $this->_freight;
  984. $orderModel->CONSIGNEE = $this->consignee;
  985. $orderModel->MOBILE = $this->acceptMobile;
  986. $orderModel->PROVINCE = $this->province[0];
  987. $orderModel->LGA_NAME = $this->lgaName;
  988. $orderModel->CITY_NAME = $this->cityName;
  989. $orderModel->ADDRESS = $this->detailaddress;
  990. $orderModel->FRONT_REMARK = $this->remark;
  991. $orderModel->WAREHOUSE = $warehouse;
  992. $orderModel->STATUS = 1;
  993. $orderModel->CREATED_AT = Date::nowTime();
  994. $orderModel->CREATE_USER = $loginUserName;
  995. $orderModel->EMAIL = $email;
  996. if(!$orderModel->save()){
  997. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  998. }
  999. // 加入商品到订单商品表
  1000. foreach($this->_orderGoods as $key=>$value){
  1001. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  1002. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  1003. }
  1004. OrderGoods::batchInsert($this->_orderGoods);
  1005. //扣除会员余额/积分
  1006. if($this->payType=='cash') {
  1007. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => Yii::t('app', 'membersResellingBalancePayment')]);
  1008. }else{
  1009. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => Yii::t('app', 'membersExchangePointPayment')]);
  1010. }
  1011. return $orderModel;
  1012. }
  1013. /**
  1014. * 生成流水号
  1015. * @return string
  1016. */
  1017. private function _generateSn() {
  1018. return Date::today('Ymd') . $this->_random(10, 1);
  1019. }
  1020. /**
  1021. * 生成随机数
  1022. * @param $length
  1023. * @param int $numeric
  1024. * @return string
  1025. */
  1026. private function _random($length, $numeric = 0) {
  1027. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  1028. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  1029. $hash = '';
  1030. $max = strlen($seed) - 1;
  1031. for ($i = 0; $i < $length; $i++) {
  1032. $hash .= $seed[mt_rand(0, $max)];
  1033. }
  1034. return $hash;
  1035. }
  1036. public function addFakeOrder($userId, $periodNum){
  1037. $userName = Info::getUserNameByUserId($userId);
  1038. $sysConfig = Cache::getSystemConfig();
  1039. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  1040. $ordNo = $this->_generateSn();
  1041. $orderModel = new Order();
  1042. $orderModel->SN = 'OS'.$ordNo;
  1043. $orderModel->DEC_SN = 'DS'.$ordNo;
  1044. $orderModel->USER_ID = $userId;
  1045. $orderModel->USER_NAME = $userName;
  1046. $orderModel->PERIOD_NUM = $periodNum;
  1047. $orderModel->CREATE_USER = 'AUTO';
  1048. $orderModel->ORDER_TYPE = 'FX';
  1049. $orderModel->STATUS = 1;
  1050. $orderModel->PV = $mesureUpCondition;
  1051. $orderModel->PAY_PV = $mesureUpCondition;
  1052. $orderModel->P_CALC_MONTH = '1970-01-01';
  1053. $orderModel->CREATED_AT = Date::nowTime();
  1054. $orderModel->EXPRESS_TYPE = 1;
  1055. $orderModel->IS_AUTO = 1;
  1056. if(!$orderModel->save()){
  1057. $this->addErrors($orderModel->getErrors());
  1058. return false;
  1059. }
  1060. return $orderModel;
  1061. }
  1062. }