OrderForm.php 49 KB

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