OrderForm.php 49 KB

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