OrderForm.php 49 KB

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