OrderForm.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  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\AmpPeriod;
  15. use common\models\Countries;
  16. use common\models\CurrencyConversions;
  17. use common\models\DealType;
  18. use common\models\FreeTemplate;
  19. use common\models\Instalment;
  20. use common\models\Order;
  21. use common\models\OrderGoods;
  22. use common\models\Period;
  23. use common\models\ReceiveAddress;
  24. use common\models\Region;
  25. use common\models\ShopGoods;
  26. use common\models\ShopGoodsNature;
  27. use common\models\User;
  28. use common\models\UserNetwork;
  29. use common\models\RemainPv;
  30. use common\models\FlowRemainPv;
  31. use common\models\UserPerformance;
  32. use Yii;
  33. use yii\base\Exception;
  34. /**
  35. * Login form
  36. */
  37. class OrderForm extends Model
  38. {
  39. public $sn;
  40. public $expressCompany;
  41. public $orderTrackNo;
  42. public $status;
  43. public $remark;
  44. public $type;
  45. public $addressId;
  46. public $payType;
  47. public $goodsId;
  48. public $goodsNum;
  49. public $payPassword;
  50. public $email;
  51. public $exchangeRate;
  52. public $period;
  53. public $userName;
  54. public $decUserName;
  55. public $noLoginUserId;
  56. public $consignee;
  57. public $acceptMobile;
  58. public $province;
  59. public $city;
  60. public $lgaName;
  61. public $cityName;
  62. public $county;
  63. public $autoMaintenance;
  64. public $detailaddress;
  65. private $_address;
  66. private $_decAmount;
  67. private $_decPv;
  68. private $_freight;
  69. private $_payAmount;
  70. private $_orderGoods;
  71. private $_standardAmount;
  72. private $_decAmountStandard;
  73. private $_remainPv;
  74. private $_realPv;
  75. /**
  76. * @var Order
  77. */
  78. private $_model;
  79. public function init() {
  80. parent::init();
  81. $this->adminOperateLogger = new AdminOperate([
  82. 'fetchClass' => Order::class,
  83. ]);
  84. }
  85. /**
  86. * @inheritdoc
  87. */
  88. public function rules()
  89. {
  90. return [
  91. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province'/*,'city','county'*/,'cityName','lgaName','detailaddress','email','decUserName'], 'trim'],
  92. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/,'decUserName'], 'required'],
  93. [['payPassword'], 'required', 'when' => function ($model) { return $model->scenario !== 'noLoginReconsumeOrder'; }],
  94. [['status'], 'isStatus'],
  95. [['addressId'], 'isAddress'],
  96. [['payType'], 'isPayType'],
  97. [['payPassword'], 'validatePassword'],
  98. ];
  99. }
  100. public function attributeLabels()
  101. {
  102. return [
  103. 'sn' => Yii::t('app', 'orderSn'),
  104. 'expressCompany' => Yii::t('app', 'expressCompany'),
  105. 'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
  106. 'status' => Yii::t('app', 'state'),
  107. 'remark' => Yii::t('app', 'remark'),
  108. 'type' => Yii::t('app', 'orderType'),
  109. 'addressId' => Yii::t('app', 'shippingAddress'),
  110. 'payType' => Yii::t('app', 'payType'),
  111. 'goodsId' => Yii::t('app', 'productID'),
  112. 'goodsNum' => Yii::t('app', 'quantity'),
  113. 'userName' => Yii::t('app', 'repeatSalesMemberNo'),
  114. 'consignee' => Yii::t('app', 'consignee'),
  115. 'acceptMobile' => Yii::t('app', 'acceptMobile'),
  116. 'province' => Yii::t('app', 'province'),
  117. 'city' => Yii::t('app', 'city'),
  118. 'county' => Yii::t('app', 'county'),
  119. 'lgaName' =>Yii::t('app', 'lgaName'),
  120. 'cityName' => Yii::t('app', 'cityName'),
  121. 'detailaddress' => Yii::t('app', 'detailAddress'),
  122. 'email' => Yii::t('app', 'email'),
  123. 'decUserName' => Yii::t('app', 'decUserName'),
  124. ];
  125. }
  126. /**
  127. * 指定校验场景
  128. * @return array
  129. */
  130. public function scenarios()
  131. {
  132. $parentScenarios = parent::scenarios();
  133. $customScenarios = [
  134. // 管理员发货
  135. 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  136. // 会员确认收货
  137. 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  138. // 管理员修改订单状态
  139. 'adminStatus' => ['sn', 'status'],
  140. // 管理员修改备注
  141. 'adminRemark' => ['sn', 'remark'],
  142. // 会员下单
  143. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword', 'period'],
  144. // 帮会员复消下单
  145. 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
  146. 'noLoginReconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
  147. // 管理员退款
  148. 'adminRefund' => ['sn'],
  149. // AMP
  150. 'autoMaintenanceOrder' => ['type', 'userName', 'payType', 'goodsId', 'goodsNum', 'remark', 'payPassword', 'consignee', 'acceptMobile', 'province', 'cityName', 'lgaName', 'detailaddress', 'decUserName'],
  151. ];
  152. return array_merge($parentScenarios, $customScenarios);
  153. }
  154. /**
  155. * 校验之前
  156. * @return bool
  157. */
  158. public function beforeValidate()
  159. {
  160. $parentValidate = parent::beforeValidate();
  161. if ($this->sn) {
  162. $this->_model = Order::findOne(['SN'=>$this->sn]);
  163. if (!$this->_model){
  164. $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
  165. return false;
  166. }
  167. }
  168. if ($this->scenario == 'adminDelivery'){
  169. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
  170. $this->addError('sn', Yii::t('app', 'orderHasBeenCancelCanNotDeliver'));
  171. return false;
  172. }
  173. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  174. $this->addError('sn', Yii::t('app', 'orderHasBeenDeleteCanNotDeliver'));
  175. return false;
  176. }
  177. }
  178. if ($this->scenario == 'adminRefund'){
  179. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['paid']['value']) {
  180. $this->addError('sn', Yii::t('app', 'orderPayStatusDoesNotSupportRefund'));
  181. return false;
  182. }
  183. if ($this->_model['DELIVERY_STATUS'] != \Yii::$app->params['deliveryStatus']['notDelivery']['value']) {
  184. $this->addError('sn', Yii::t('app', 'orderLogisticsStatusDoesNotSupportRefund'));
  185. return false;
  186. }
  187. if ($this->_model['PAY_TYPE'] != 'pay_stack') {
  188. $this->addError('sn', Yii::t('app', 'orderPayTypeDoesNotSupportRefund'));
  189. return false;
  190. }
  191. if (!$this->_model['REMARK']) {
  192. $this->addError('sn', Yii::t('app', 'paymentInfoDoesNotExists'));
  193. return false;
  194. }
  195. }
  196. return $parentValidate;
  197. }
  198. /**
  199. * 校验支付密码
  200. * @param $attribute
  201. * @param $params
  202. */
  203. public function validatePassword($attribute, $params) {
  204. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  205. $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
  206. }
  207. }
  208. /**
  209. * 判断收货地址是否存在
  210. * @param $attribute
  211. */
  212. public function isAddress($attribute){
  213. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  214. $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
  215. } else {
  216. $this->_address = $receiveAddress;
  217. }
  218. }
  219. /**
  220. * 判断支付方式
  221. * @param $attribute
  222. * @throws Exception
  223. */
  224. public function isPayType($attribute){
  225. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  226. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  227. return;
  228. }
  229. // 一个订单只能包含一类商品
  230. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  231. if (!$goods) {
  232. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  233. return;
  234. }
  235. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  236. if (count($goodsCategoryType) > 1) {
  237. $this->addError($attribute, Yii::t('app', 'orderCanNotHasMoreClassification'));
  238. return;
  239. }
  240. // 购买方式
  241. $sellTypeLabelMap = array_column(ShopGoods::getSaleType(), NULL, 'label');
  242. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  243. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  244. return;
  245. }
  246. // 所选支付方式必须是商品分类支持的类型
  247. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  248. // 商品类型
  249. $currCategoryType = $goodsCategoryType[0];
  250. if (!array_key_exists($currCategoryType, $categoryType)) {
  251. $this->addError($attribute, Yii::t('app', 'shopGoodClassificationError'));
  252. return;
  253. }
  254. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  255. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  256. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  257. return;
  258. }
  259. }
  260. /**
  261. * 校验类型
  262. * @param $attribute
  263. */
  264. public function isStatus($attribute){
  265. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  266. $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
  267. return ;
  268. }
  269. if ($this->scenario == 'adminStatus'){
  270. if ($this->status == $this->_model['STATUS']) {
  271. $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
  272. return ;
  273. }
  274. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  275. $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
  276. return ;
  277. }
  278. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $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']['delivery']) {
  283. $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
  284. return ;
  285. }
  286. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  287. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  288. return ;
  289. }
  290. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  291. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  292. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
  293. return ;
  294. }
  295. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  296. $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
  297. return ;
  298. }
  299. }
  300. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  301. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  302. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
  303. return ;
  304. }
  305. }
  306. }
  307. }
  308. /**
  309. * 管理员发货
  310. * @return Order|null
  311. * @throws \yii\db\Exception
  312. */
  313. public function adminDelivery(){
  314. if(!$this->validate()){
  315. return null;
  316. }
  317. $db = \Yii::$app->db;
  318. $transaction = $db->beginTransaction();
  319. try {
  320. $period = Period::instance();
  321. $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value'];
  322. $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum();
  323. $this->_model->DELIVERY_AT = Date::nowTime();
  324. $this->_model->EXPRESS_COMPANY = $this->expressCompany;
  325. $this->_model->ORDER_TRACK_NO = $this->orderTrackNo;
  326. $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value'];
  327. if(!$this->_model->save()){
  328. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  329. }
  330. $transaction->commit();
  331. } catch (Exception $e) {
  332. $transaction->rollBack();
  333. $this->addError('edit', $e->getMessage());
  334. return null;
  335. }
  336. return $this->_model;
  337. }
  338. /**
  339. * 校验支付
  340. * @return Order|null
  341. * @throws Exception
  342. */
  343. public function verifyPayStack(): ?Order
  344. {
  345. if(!$this->validate()){
  346. return null;
  347. }
  348. // 调用PayStack支付校验
  349. $payload = PayStack::transactionVerify($this->remark['reference']);
  350. if ($payload['status'] !== true) {
  351. throw new Exception(Form::formatErrorsForApi($payload['message']));
  352. }
  353. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  354. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'payAmountNotEqualOrderAmount')));
  355. }
  356. $db = \Yii::$app->db;
  357. $transaction = $db->beginTransaction();
  358. try {
  359. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  360. $this->_model->REMARK = json_encode($this->remark);
  361. $this->_model->PAY_AT = Date::nowTime();
  362. if (!$this->_model->save()) {
  363. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  364. }
  365. $transaction->commit();
  366. } catch (Exception $e) {
  367. $transaction->rollBack();
  368. $this->addError('edit', $e->getMessage());
  369. return null;
  370. }
  371. return $this->_model;
  372. }
  373. /**
  374. * 订单退款
  375. * @return Order|null
  376. * @throws Exception
  377. */
  378. public function adminRefund()
  379. {
  380. if(!$this->validate()){
  381. return null;
  382. }
  383. // 支付信息存在于remark中
  384. $remark = $this->_model->REMARK ? json_decode($this->_model->REMARK, true) : [];
  385. $reference = $remark['reference'] ?? '';
  386. if (!$reference) {
  387. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'paymentInfoDoesNotExists')));
  388. }
  389. // 退款金额. 订单支付金额 * 100
  390. $amount = $this->_model->PAY_AMOUNT * 100;
  391. // 调用PayStack支付校验
  392. $payload = PayStack::transactionRefund($reference, $amount);
  393. if ($payload['status'] !== true) {
  394. throw new Exception(Form::formatErrorsForApi($payload['message']));
  395. }
  396. $db = \Yii::$app->db;
  397. $transaction = $db->beginTransaction();
  398. try {
  399. $this->_model->STATUS = \Yii::$app->params['orderStatus']['refund']['value'];
  400. $this->_model->REMARK = json_encode([
  401. 'payment' => $remark,
  402. 'refund' => $payload['data']
  403. ]
  404. );
  405. if (!$this->_model->save()) {
  406. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  407. }
  408. $transaction->commit();
  409. } catch (Exception $e) {
  410. $transaction->rollBack();
  411. $this->addError('edit', $e->getMessage());
  412. return null;
  413. }
  414. return $this->_model;
  415. }
  416. /**
  417. * BV分期
  418. *
  419. *
  420. */
  421. private function _pvSplit($oPv){
  422. $sysConfig = Cache::getSystemConfig();
  423. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  424. if($oPv>$mesureUpCondition){
  425. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  426. $remainPv = $oPv - $currentPv;
  427. }else{
  428. $currentPv = $oPv;
  429. $remainPv = 0;
  430. }
  431. return [
  432. 'current' => $currentPv,
  433. 'remain' => $remainPv
  434. ];
  435. }
  436. /**
  437. * 复销
  438. * @throws Exception
  439. * @throws \yii\db\Exception
  440. */
  441. public function add(){
  442. if(!$this->validate()){
  443. return null;
  444. }
  445. $ids = $this->goodsId;
  446. $totalAmount = 0;
  447. $totalPv = 0;
  448. $totalRealPv = 0;
  449. $totalAmountStandard = 0;
  450. $goodsType = ShopGoods::getGoodType();
  451. $this->_remainPv = 0;
  452. $hasInstalment = 0;
  453. $loginUserId = \Yii::$app->user->id;
  454. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  455. foreach ($this->goodsNum as $k => $v) {
  456. if ($v) {
  457. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  458. if (!$goods) {
  459. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  460. }
  461. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  462. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  463. if (!$goodsNature) {
  464. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  465. }
  466. // 汇率
  467. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  468. if($goods['STORE_NUMS']>0){
  469. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  470. $discount = $goodsType[$goods['TYPE']]['discount'];
  471. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  472. $realPv = $goods['PRICE_PV'] * $discount/100;
  473. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  474. } else {
  475. $discount = $goods['SELL_DISCOUNT'];
  476. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  477. $realPv = $goods['PRICE_PV'] * $discount;
  478. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  479. }
  480. if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
  481. $pvSplit = $this->_pvSplit($realPv);
  482. $currentPv = $pvSplit['current'];
  483. $remainPv = $pvSplit['remain'];
  484. $totalPv += $currentPv * intval($v);
  485. $totalRealPv += $realPv * intval($v);
  486. $this->_remainPv += $remainPv * intval($v);
  487. }else{
  488. $currentPv = $goods['PRICE_PV'];
  489. $totalPv += $realPv * intval($v);
  490. $totalRealPv += $realPv * intval($v);
  491. $remainPv = 0;
  492. $this->_remainPv += 0;
  493. }
  494. $totalAmount += $realPrice * intval($v);
  495. $totalAmountStandard += $realPriceStandard * intval($v);
  496. // if($this->payType=='cash') {
  497. // $discount = $goodsType[$goods['TYPE']]['discount'];
  498. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  499. // $realPv = $goods['PRICE_PV'] * $discount/100;
  500. // $totalAmount += $realPrice * intval($v);
  501. // $totalPv += $realPv * intval($v);
  502. // }else{
  503. // $realPrice = $goods['SELL_PRICE'];
  504. // $realPv = $goods['PRICE_PV'];
  505. // $totalAmount += $realPrice * intval($v);
  506. // $totalPv += $realPv * intval($v);
  507. // }
  508. $this->_orderGoods[] = [
  509. 'GOODS_ID' => $goods['ID'],
  510. 'PRICE' => $goodsNature['SELL_PRICE'],
  511. 'PV' => $currentPv, // $goods['PRICE_PV'],
  512. 'REAL_PRICE' => $realPrice,
  513. 'REAL_PV' => $this->payType == 'prp' ? 0 : $realPv,
  514. 'REMAIN_PV' => $remainPv,
  515. 'POINT' => $goods['POINT'],
  516. 'BUY_NUMS' => intval($v),
  517. 'SKU_CODE' => $goods['GOODS_NO'],
  518. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  519. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  520. 'PAY_TYPE' => $this->payType,
  521. 'EMAIL' => $this->email,
  522. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  523. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  524. 'EXCHANGE_RATE' => $this->exchangeRate,
  525. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  526. ];
  527. }
  528. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  529. if($v>1){ // 不可以购买多个
  530. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  531. }
  532. $userStage = Instalment::getStage($loginUserId);
  533. $userInstalmentInfo = Instalment::getInfo($loginUserId);
  534. // 分期的总期数
  535. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  536. // 分期商品的期数不能大于总分期数限制
  537. if (intval($goods['INSTALMENT']) > $instalment) {
  538. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  539. }
  540. if ($userStage != $instalment){
  541. if ($userInstalmentInfo){
  542. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  543. throw new Exception(Yii::t('app', 'canNotBuy'));
  544. }
  545. }
  546. if ($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  547. throw new Exception(Yii::t('app', 'canNotBuy'));
  548. }
  549. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  550. throw new Exception(Yii::t('app', 'canNotBuy'));
  551. }
  552. } else {
  553. if ($goods['INSTALMENT'] != 1) {
  554. throw new Exception(Yii::t('app', 'canNotBuy'));
  555. }
  556. }
  557. $hasInstalment = $goods['INSTALMENT'];
  558. }
  559. }
  560. }
  561. // 运费模板
  562. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  563. // 运费
  564. $freight = $freeTemplate['freight'] ?? 0;
  565. // 普通商品免运费阈值
  566. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  567. $this->_decAmount = $totalAmount;
  568. $this->_decPv = $totalPv;
  569. $this->_realPv = $totalRealPv;
  570. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  571. if($this->_address['PROVINCE']==1){
  572. $this->_freight = 0;
  573. }
  574. $this->_payAmount = $this->_decAmount + $this->_freight;
  575. $this->_decAmountStandard = $totalAmountStandard;
  576. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  577. $db = \Yii::$app->db;
  578. $transaction = $db->beginTransaction();
  579. try {
  580. //判断用户余额是否充足
  581. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  582. if ($result['code'] !== 200) {
  583. throw new Exception($result['message']);
  584. }
  585. /**
  586. * 2022-04-28
  587. * York
  588. * 支付后减少库存
  589. */
  590. foreach ($this->goodsNum as $k => $v){
  591. if ($v){
  592. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  593. if (!$goods) {
  594. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  595. }
  596. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  597. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  598. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  599. $data->STORE_NUMS = $goods_store_nums;
  600. $data->update();
  601. //下单后库存小于等于0 商品下架
  602. if($goods_store_nums <= 0){
  603. $data->STATUS = 0;
  604. $data->UPDATED_AT = Date::nowTime();
  605. $data->update();
  606. }
  607. }else{
  608. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  609. }
  610. }
  611. }
  612. //写入订单
  613. if (!$orderResult = $this->addOrder()) {
  614. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  615. }
  616. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  617. $instalmentModel = Instalment::findOne(['USER_ID'=>$loginUserId]);
  618. if(!$instalmentModel) {
  619. $instalmentModel = new Instalment();
  620. }
  621. $instalmentModel->USER_ID = $loginUserId;
  622. $instalmentModel->STAGE = $hasInstalment;
  623. $instalmentModel->ORDER_TYPE = 'FX';
  624. $instalmentModel->UPDATE_TIME = time();
  625. $instalmentModel->save();
  626. }
  627. $transaction->commit();
  628. return $orderResult;
  629. }catch (\Exception $e){
  630. $transaction->rollBack();
  631. $this->addError('add', $e->getMessage());
  632. return null;
  633. }
  634. }
  635. /**
  636. * 判断对应账户余额是否充足.
  637. * @param $payType string 支付方式.
  638. * @param $payAmount numeric 支付金额
  639. * @return array|int[]
  640. */
  641. public function getBalanceAdequate(string $payType, $payAmount): array
  642. {
  643. $loginUserId = \Yii::$app->user->id;
  644. if ($payType == 'cash') {
  645. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  646. return ['code' => 500, 'message' => Yii::t('app', 'cashDoesNotAdequate')];
  647. }
  648. } else if ($payType =='exchange') {
  649. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  650. return ['code' => 500, 'message' => Yii::t('app', 'exchangePointDoesNotAdequate')];
  651. }
  652. } else if ($payType == 'prp') {
  653. if ($payAmount > UserPerformance::getAmounts($loginUserId)) {
  654. return ['code' => 500, 'message' => Yii::t('app', 'userPerformanceDoesNotAdequate')];
  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 = $this->payType == 'prp' ? 0 : $_hasRealPV; // 兑换积分不能算业绩
  697. $orderModel->REMAIN_PV = $this->payType == 'prp' ? 0 : $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 == 'prp') {
  754. UserPerformance::changeUserPerformance(\Yii::$app->user->id, $this->_payAmount, $orderModel->SN);
  755. }
  756. return $orderModel;
  757. }
  758. /**
  759. * 帮会员复销
  760. * @return bool|null
  761. * @throws Exception
  762. * @throws \yii\db\Exception
  763. */
  764. private function getReconsumeActorId()
  765. {
  766. return $this->scenario === 'noLoginReconsumeOrder' ? $this->noLoginUserId : \Yii::$app->user->id;
  767. }
  768. public function reconsumeAdd(){
  769. if(!$this->validate()){
  770. return null;
  771. }
  772. $ids = $this->goodsId;
  773. $totalAmount = 0;
  774. $totalPv = 0;
  775. $totalRealPv = 0;
  776. $totalAmountStandard = 0;
  777. $goodsType = ShopGoods::getGoodType();
  778. $hasInstalment = 0;
  779. $userId = Info::getUserIdByUserName($this->userName);
  780. $user = User::getEnCodeInfo($userId);
  781. $decUserID = Info::getUserIdByUserName($this->decUserName);
  782. $stockist_user = User::getEnCodeInfo($decUserID);
  783. if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
  784. throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
  785. }
  786. // 报单中心汇率
  787. $reconsumeActorId = $this->getReconsumeActorId();
  788. $decCountryId = User::getEnCodeInfo($reconsumeActorId)['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. //判断是否是报单中心
  795. $loginUser = User::getEnCodeInfo($reconsumeActorId);
  796. if($loginUser['IS_DEC'] == 1){
  797. if($decUserID != $reconsumeActorId){
  798. throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
  799. }
  800. }
  801. foreach ($this->goodsNum as $k => $v) {
  802. if ($v) {
  803. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  804. if (!$goods) {
  805. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  806. }
  807. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  808. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  809. if (!$goodsNature) {
  810. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  811. }
  812. // 汇率
  813. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  814. if($goods['STORE_NUMS']>0){
  815. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  816. $discount = $goodsType[$goods['TYPE']]['discount'];
  817. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  818. $realPv = $goods['PRICE_PV'] * $discount/100;
  819. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  820. } else {
  821. $discount = $goods['SELL_DISCOUNT'];
  822. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  823. $realPv = $goods['PRICE_PV'] * $discount;
  824. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  825. }
  826. if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
  827. $pvSplit = $this->_pvSplit($realPv);
  828. $currentPv = $pvSplit['current'];
  829. $remainPv = $pvSplit['remain'];
  830. $totalPv += $this->payType == 'prp' ? 0 : $currentPv * intval($v);
  831. $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  832. $this->_remainPv += $remainPv * intval($v);
  833. }else{
  834. $currentPv = $goods['PRICE_PV'];
  835. $totalPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  836. $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  837. $remainPv = 0;
  838. $this->_remainPv += 0;
  839. }
  840. $totalAmount += $realPrice * intval($v);
  841. $totalAmountStandard += $realPriceStandard * intval($v);
  842. $this->_orderGoods[] = [
  843. 'GOODS_ID' => $goods['ID'],
  844. 'PRICE' => $goodsNature['SELL_PRICE'],
  845. 'PV' => $this->payType == 'prp' ? 0 : $currentPv, // $goods['PRICE_PV'],
  846. 'REAL_PRICE' => $realPrice,
  847. 'REAL_PV' => $this->payType == 'prp' ? 0 : $realPv,
  848. 'REMAIN_PV' => $this->payType == 'prp' ? 0 : $remainPv,
  849. 'POINT' => $goods['POINT'],
  850. 'BUY_NUMS' => intval($v),
  851. 'SKU_CODE' => $goods['GOODS_NO'],
  852. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  853. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  854. 'PAY_TYPE' => $this->payType,
  855. 'EMAIL' => $this->email,
  856. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  857. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  858. 'EXCHANGE_RATE' => $currencyRate,
  859. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  860. ];
  861. }
  862. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  863. if($v>1){ // 不可以购买多个
  864. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  865. }
  866. $userStage = Instalment::getStage($userId);
  867. $userInstalmentInfo = Instalment::getInfo($userId);
  868. // 分期的总期数
  869. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  870. // 分期商品的期数不能大于总分期数限制
  871. if (intval($goods['INSTALMENT']) > $instalment) {
  872. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  873. }
  874. if ($userStage == $instalment){
  875. if ($goods['INSTALMENT'] != 1) {
  876. throw new Exception(Yii::t('app', 'canNotBuy'));
  877. }
  878. }else{
  879. if($userInstalmentInfo){
  880. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  881. throw new Exception(Yii::t('app', 'canNotBuy'));
  882. }
  883. }
  884. if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  885. throw new Exception(Yii::t('app', 'canNotBuy'));
  886. }
  887. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  888. throw new Exception(Yii::t('app', 'canNotBuy'));
  889. }
  890. }
  891. $hasInstalment = $goods['INSTALMENT'];
  892. }
  893. }
  894. }
  895. // 运费模板
  896. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  897. // 运费
  898. $freight = $freeTemplate['freight'] ?? 0;
  899. // 普通商品免运费阈值
  900. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  901. $this->_decAmount = $totalAmount;
  902. $this->_decPv = $this->payType == 'prp' ? 0 : $totalPv;
  903. $this->_realPv = $this->payType == 'prp' ? 0 : $totalRealPv;
  904. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  905. $this->_payAmount = $this->_decAmount + $this->_freight;
  906. $this->_decAmountStandard = $totalAmountStandard;
  907. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  908. $db = \Yii::$app->db;
  909. $transaction = $db->beginTransaction();
  910. try {
  911. $loginUserId = $reconsumeActorId;
  912. //是否开启伞下会员限制
  913. // $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  914. // if($isResaleUmbrella){
  915. // $userId = Info::getUserIdByUserName($this->userName);
  916. // $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  917. // if(!$userNetwork){
  918. // throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
  919. // }
  920. // }
  921. if ($this->payType == 'prp') {
  922. //看余额是否充足
  923. $decCash = UserPerformance::getAmounts($loginUserId);
  924. } else {
  925. //看现金余额是否充足
  926. $decCash = Cash::getAvailableBalance($loginUserId);
  927. }
  928. // 转换后的余额
  929. $localCash = Tool::convertAmount($decCash, $decUserCurrencyRate, $currencyRate);
  930. if ($localCash < $this->_decAmount){
  931. throw new Exception(Yii::t('app', 'applicantPrpShort'), 400);
  932. }
  933. foreach ($this->goodsNum as $k => $v){
  934. if ($v){
  935. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  936. if (!$goods) {
  937. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  938. }
  939. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  940. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  941. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  942. $data->STORE_NUMS = $goods_store_nums;
  943. $data->update();
  944. //下单后库存小于等于0 商品下架
  945. if($goods_store_nums <= 0){
  946. $data->STATUS = 0;
  947. $data->UPDATED_AT = Date::nowTime();
  948. $data->update();
  949. }
  950. }else{
  951. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  952. }
  953. }
  954. }
  955. //写入订单
  956. if (!$orderResult = $this->addUserOrder()) {
  957. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  958. }
  959. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  960. $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
  961. if(!$instalmentModel) {
  962. $instalmentModel = new Instalment();
  963. }
  964. $instalmentModel->USER_ID = $userId;
  965. $instalmentModel->STAGE = $hasInstalment;
  966. $instalmentModel->ORDER_TYPE = 'FX';
  967. $instalmentModel->UPDATE_TIME = time();
  968. $instalmentModel->save();
  969. }
  970. $transaction->commit();
  971. }catch (\Exception $e){
  972. $transaction->rollBack();
  973. $this->addError('add', $e->getMessage());
  974. return null;
  975. }
  976. return true;
  977. }
  978. /**
  979. * 帮会员复消的订单
  980. */
  981. public function addUserOrder()
  982. {
  983. $periodObj = Period::instance();
  984. $nowPeriodNum = $periodObj->getNowPeriodNum();
  985. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  986. //帮复消会员Id(登陆会员)
  987. $loginUserId = $this->getReconsumeActorId();
  988. $loginUserName = Info::getUserNameByUserId($loginUserId);
  989. //订单会员Id
  990. $userId = Info::getUserIdByUserName($this->userName);
  991. $countryId = Info::getUserCountryByUserId($userId);
  992. $email = Info::getEmailByUserId($this->userName);
  993. $country = Countries::getById($countryId);
  994. $warehouse = '01';
  995. $ordNo = $this->_generateSn();
  996. $orderModel = new Order();
  997. $orderModel->SN = 'OS'.$ordNo;
  998. $orderModel->DEC_SN = 'DS'.$ordNo;
  999. $orderModel->ORDER_TYPE = $this->type;
  1000. $orderModel->ORDER_CATEGORY = 'STUDIO';
  1001. $orderModel->USER_ID = $userId;
  1002. $orderModel->USER_NAME = $this->userName;
  1003. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  1004. $orderModel->PV = $this->payType == 'prp' ? 0 : $this->_decPv;
  1005. $orderModel->PAY_AMOUNT = $this->_payAmount;
  1006. $orderModel->PAY_PV = $this->payType == 'prp' ? 0 : $this->_decPv;
  1007. $orderModel->PAY_AT = Date::nowTime();
  1008. $orderModel->PAY_TYPE = $this->payType;
  1009. $orderModel->PERIOD_NUM = $nowPeriodNum;
  1010. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  1011. $orderModel->FREIGHT = $this->_freight;
  1012. $orderModel->PAY_FREIGHT = $this->_freight;
  1013. $orderModel->CONSIGNEE = $this->consignee;
  1014. $orderModel->MOBILE = $this->acceptMobile;
  1015. $orderModel->PROVINCE = $this->province[0];
  1016. $orderModel->LGA_NAME = $this->lgaName;
  1017. $orderModel->CITY_NAME = $this->cityName;
  1018. $orderModel->ADDRESS = $this->detailaddress;
  1019. $orderModel->FRONT_REMARK = $this->remark;
  1020. $orderModel->WAREHOUSE = $warehouse;
  1021. $orderModel->STATUS = 1;
  1022. $orderModel->CREATED_AT = Date::nowTime();
  1023. $orderModel->CREATE_USER = $loginUserName;
  1024. $orderModel->EMAIL = $email ?? '';
  1025. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  1026. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  1027. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  1028. $orderModel->COUNTRY_ID = $countryId;
  1029. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  1030. $orderModel->DEC_USER_ID = $this->decUserName;
  1031. $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
  1032. if(!$orderModel->save()){
  1033. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  1034. }
  1035. // 加入商品到订单商品表
  1036. foreach($this->_orderGoods as $key=>$value){
  1037. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  1038. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  1039. }
  1040. OrderGoods::batchInsert($this->_orderGoods);
  1041. //扣除会员余额/积分
  1042. if($this->payType=='cash') {
  1043. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => Yii::t('app', 'membersResellingBalancePayment')]);
  1044. } else if ($this->payType == 'prp') {
  1045. UserPerformance::changeUserPerformance($loginUserId, $this->_payAmount, $orderModel->SN);
  1046. } else{
  1047. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => Yii::t('app', 'membersExchangePointPayment')]);
  1048. }
  1049. if (($this->payType != 'prp') && ($this->autoMaintenance == 1)) {
  1050. $this->orderAutoMaintenance($orderModel);
  1051. }
  1052. return $orderModel;
  1053. }
  1054. /**
  1055. * 生成流水号
  1056. * @return string
  1057. */
  1058. private function _generateSn() {
  1059. return Date::today('Ymd') . $this->_random(10, 1);
  1060. }
  1061. /**
  1062. * 生成随机数
  1063. * @param $length
  1064. * @param int $numeric
  1065. * @return string
  1066. */
  1067. private function _random($length, $numeric = 0) {
  1068. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  1069. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  1070. $hash = '';
  1071. $max = strlen($seed) - 1;
  1072. for ($i = 0; $i < $length; $i++) {
  1073. $hash .= $seed[mt_rand(0, $max)];
  1074. }
  1075. return $hash;
  1076. }
  1077. public function addFakeOrder($userId, $periodNum){
  1078. $userName = Info::getUserNameByUserId($userId);
  1079. $sysConfig = Cache::getSystemConfig();
  1080. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  1081. $ordNo = $this->_generateSn();
  1082. $orderModel = new Order();
  1083. $orderModel->SN = 'OS'.$ordNo;
  1084. $orderModel->DEC_SN = 'DS'.$ordNo;
  1085. $orderModel->USER_ID = $userId;
  1086. $orderModel->USER_NAME = $userName;
  1087. $orderModel->PERIOD_NUM = $periodNum;
  1088. $orderModel->CREATE_USER = 'AUTO';
  1089. $orderModel->ORDER_TYPE = 'FX';
  1090. $orderModel->STATUS = 1;
  1091. $orderModel->PV = $mesureUpCondition;
  1092. $orderModel->PAY_PV = $mesureUpCondition;
  1093. $orderModel->P_CALC_MONTH = '1970-01-01';
  1094. $orderModel->CREATED_AT = Date::nowTime();
  1095. $orderModel->EXPRESS_TYPE = 1;
  1096. $orderModel->IS_AUTO = 1;
  1097. if(!$orderModel->save()){
  1098. $this->addErrors($orderModel->getErrors());
  1099. return false;
  1100. }
  1101. return $orderModel;
  1102. }
  1103. /**
  1104. * AMP
  1105. * @return bool|null
  1106. * @throws Exception|\Throwable
  1107. */
  1108. public function autoMaintenanceSureOrder()
  1109. {
  1110. if (!$this->validate()) {
  1111. return null;
  1112. }
  1113. $ids = $this->goodsId;
  1114. $totalAmount = 0;
  1115. $totalPv = 0;
  1116. $totalRealPv = 0;
  1117. $totalAmountStandard = 0;
  1118. $this->autoMaintenance = 1;
  1119. $goodsType = ShopGoods::getGoodType();
  1120. $hasInstalment = 0;
  1121. $userId = Info::getUserIdByUserName($this->userName);
  1122. $user = User::getEnCodeInfo($userId);
  1123. $decUserID = Info::getUserIdByUserName($this->decUserName);
  1124. $stockist_user = User::getEnCodeInfo($decUserID);
  1125. if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
  1126. throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
  1127. }
  1128. // 报单中心汇率
  1129. $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
  1130. $decCountry = Countries::getById($decCountryId);
  1131. $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
  1132. // 会员汇率
  1133. $country = Countries::getById($user['COUNTRY_ID']);
  1134. $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
  1135. // 判断是否是报单中心
  1136. $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
  1137. if ($loginUser['IS_DEC'] == 1){
  1138. if($decUserID != \Yii::$app->user->id){
  1139. throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
  1140. }
  1141. }
  1142. if ($this->payType == 'prp') {
  1143. throw new Exception(Yii::t('app', 'payTypeError'));
  1144. }
  1145. foreach ($this->goodsNum as $k => $v) {
  1146. if ($v) {
  1147. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1 AND AUTO_MAINTENANCE=1',[':ID'=> $ids[$k]]);
  1148. if (!$goods) {
  1149. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  1150. }
  1151. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  1152. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  1153. if (!$goodsNature) {
  1154. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  1155. }
  1156. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  1157. if($goods['STORE_NUMS']>0){
  1158. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  1159. $discount = $goodsType[$goods['TYPE']]['discount'];
  1160. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  1161. $realPv = $goods['PRICE_PV'] * $discount/100;
  1162. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  1163. } else {
  1164. $discount = $goods['SELL_DISCOUNT'];
  1165. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  1166. $realPv = $goods['PRICE_PV'] * $discount;
  1167. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  1168. }
  1169. $currentPv = $goods['PRICE_PV'];
  1170. $totalPv += $realPv * intval($v);
  1171. $totalRealPv += $realPv * intval($v);
  1172. $remainPv = 0;
  1173. $this->_remainPv += 0;
  1174. $totalAmount += $realPrice * intval($v);
  1175. $totalAmountStandard += $realPriceStandard * intval($v);
  1176. $this->_orderGoods[] = [
  1177. 'GOODS_ID' => $goods['ID'],
  1178. 'PRICE' => $goodsNature['SELL_PRICE'],
  1179. 'PV' => $currentPv,
  1180. 'REAL_PRICE' => $realPrice,
  1181. 'REAL_PV' => $realPv,
  1182. 'REMAIN_PV' => $remainPv,
  1183. 'POINT' => $goods['POINT'],
  1184. 'BUY_NUMS' => intval($v),
  1185. 'SKU_CODE' => $goods['GOODS_NO'],
  1186. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  1187. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  1188. 'PAY_TYPE' => $this->payType,
  1189. 'EMAIL' => $this->email,
  1190. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  1191. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  1192. 'EXCHANGE_RATE' => $currencyRate,
  1193. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  1194. ];
  1195. }
  1196. if($goods['INSTALMENT']>0){
  1197. if ($v > 1) {
  1198. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  1199. }
  1200. $userStage = Instalment::getStage($userId);
  1201. $userInstalmentInfo = Instalment::getInfo($userId);
  1202. // 分期的总期数
  1203. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  1204. // 分期商品的期数不能大于总分期数限制
  1205. if (intval($goods['INSTALMENT']) > $instalment) {
  1206. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  1207. }
  1208. if ($userStage == $instalment){
  1209. if ($goods['INSTALMENT'] != 1) {
  1210. throw new Exception(Yii::t('app', 'canNotBuy'));
  1211. }
  1212. }else{
  1213. if($userInstalmentInfo){
  1214. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  1215. throw new Exception(Yii::t('app', 'canNotBuy'));
  1216. }
  1217. }
  1218. if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  1219. throw new Exception(Yii::t('app', 'canNotBuy'));
  1220. }
  1221. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  1222. throw new Exception(Yii::t('app', 'canNotBuy'));
  1223. }
  1224. }
  1225. $hasInstalment = $goods['INSTALMENT'];
  1226. }
  1227. }
  1228. }
  1229. $sysConfig = Cache::getSystemConfig();
  1230. $ampDivideLine = (int)$sysConfig['ampBVCondition']['VALUE'];
  1231. if ($totalPv < $ampDivideLine) {
  1232. throw new Exception(Yii::t('app', 'ampOrderSubStandard', ['ampBv' => $ampDivideLine]));
  1233. }
  1234. // 运费模板
  1235. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  1236. // 运费
  1237. $freight = $freeTemplate['freight'] ?? 0;
  1238. // 普通商品免运费阈值
  1239. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  1240. $this->_decAmount = $totalAmount;
  1241. $this->_decPv = $totalPv;
  1242. $this->_realPv = $totalRealPv;
  1243. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  1244. $this->_payAmount = $this->_decAmount + $this->_freight;
  1245. $this->_decAmountStandard = $totalAmountStandard;
  1246. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  1247. $db = \Yii::$app->db;
  1248. $transaction = $db->beginTransaction();
  1249. try {
  1250. $loginUserId = \Yii::$app->user->id;
  1251. //是否开启伞下会员限制
  1252. // $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  1253. // if($isResaleUmbrella){
  1254. // $userId = Info::getUserIdByUserName($this->userName);
  1255. // $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  1256. // if(!$userNetwork){
  1257. // throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
  1258. // }
  1259. // }
  1260. $decCash = Cash::getAvailableBalance($loginUserId);
  1261. // 转换后的余额
  1262. $localCash = Tool::convertAmount($decCash, $decUserCurrencyRate, $currencyRate);
  1263. if ($localCash < $this->_decAmount){
  1264. throw new Exception(Yii::t('app', 'applicantPrpShort'), 400);
  1265. }
  1266. foreach ($this->goodsNum as $k => $v){
  1267. if ($v){
  1268. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  1269. if (!$goods) {
  1270. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  1271. }
  1272. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  1273. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  1274. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  1275. $data->STORE_NUMS = $goods_store_nums;
  1276. $data->update();
  1277. //下单后库存小于等于0 商品下架
  1278. if($goods_store_nums <= 0){
  1279. $data->STATUS = 0;
  1280. $data->UPDATED_AT = Date::nowTime();
  1281. $data->update();
  1282. }
  1283. }else{
  1284. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  1285. }
  1286. }
  1287. }
  1288. //写入订单
  1289. if (!$orderResult = $this->addUserOrder()) {
  1290. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  1291. }
  1292. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  1293. $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
  1294. if(!$instalmentModel) {
  1295. $instalmentModel = new Instalment();
  1296. }
  1297. $instalmentModel->USER_ID = $userId;
  1298. $instalmentModel->STAGE = $hasInstalment;
  1299. $instalmentModel->ORDER_TYPE = 'FX';
  1300. $instalmentModel->UPDATE_TIME = time();
  1301. $instalmentModel->save();
  1302. }
  1303. $transaction->commit();
  1304. }catch (\Exception $e){
  1305. $transaction->rollBack();
  1306. $this->addError('add', $e->getMessage());
  1307. return null;
  1308. }
  1309. return true;
  1310. }
  1311. private function orderAutoMaintenance($order)
  1312. {
  1313. $nowPeriodNum = Period::instance()->getNowPeriodNum();
  1314. try {
  1315. $sysConfig = Cache::getSystemConfig();
  1316. $divideLine = (float)$sysConfig['monthPcsPvFxCondition']['VALUE'];
  1317. $orderTotalBv = $order->PV;
  1318. if ($orderTotalBv <= $divideLine) {
  1319. return;
  1320. }
  1321. $lastAmpPeriod = AmpPeriod::find()
  1322. ->where(['USER_ID' => $order->USER_ID])
  1323. ->orderBy(['PERIOD_NUM' => SORT_DESC])
  1324. ->one();
  1325. $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
  1326. if (!$lastAmpPeriod) {
  1327. $memberOrderBv = Order::find()
  1328. ->select('SUM(PV) AS total_pv')
  1329. ->where([
  1330. 'USER_ID' => $order->USER_ID,
  1331. 'IS_DELETE' => 0,
  1332. 'PERIOD_NUM' => $nowPeriodNum
  1333. ])
  1334. ->andWhere(['!=', 'SN', $order->SN])
  1335. ->scalar();
  1336. if ($memberOrderBv >= $divideLine) {
  1337. $startPeriodNum = $nowPeriodNum + 1;
  1338. }
  1339. LoggerTool::notice([
  1340. $lastAmpPeriod, $startPeriodNum, $divideLine, $memberOrderBv, $nowPeriodNum
  1341. ]);
  1342. }
  1343. $periodCount = floor($orderTotalBv / $divideLine);
  1344. $remainderBv = $orderTotalBv % $divideLine;
  1345. $ampPeriods = [];
  1346. for ($i = 1; $i <= $periodCount; $i++) {
  1347. $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
  1348. $ampPeriods[] = [
  1349. 'USER_ID' => $order->USER_ID,
  1350. 'ORDER_SN' => $order->SN,
  1351. 'PERIOD_NUM' => $startPeriodNum,
  1352. 'BV' => $currentBv,
  1353. ];
  1354. $startPeriodNum++;
  1355. }
  1356. if (!empty($ampPeriods)) {
  1357. AmpPeriod::batchInsert($ampPeriods);
  1358. }
  1359. } catch (\Exception $e) {
  1360. // 记录日志或进行错误处理
  1361. \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
  1362. }
  1363. }
  1364. }