OrderForm.php 62 KB

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