OrderForm.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  1163. $totalRealPv += $this->payType == 'prp' ? 0 : $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' => $this->payType == 'prp' ? 0 : $currentPv, // $goods['PRICE_PV'],
  1172. 'REAL_PRICE' => $realPrice,
  1173. 'REAL_PV' => $this->payType == 'prp' ? 0 : $realPv,
  1174. 'REMAIN_PV' => $this->payType == 'prp' ? 0 : $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', ['']));
  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 = $this->payType == 'prp' ? 0 : $totalPv;
  1234. $this->_realPv = $this->payType == 'prp' ? 0 : $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 = (int)$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. ->scalar();
  1327. if ($memberOrderBv >= $divideLine) {
  1328. $startPeriodNum = $nowPeriodNum + 1;
  1329. }
  1330. }
  1331. $periodCount = floor($orderTotalBv / $divideLine);
  1332. $remainderBv = $orderTotalBv % $divideLine;
  1333. $ampPeriods = [];
  1334. for ($i = 1; $i <= $periodCount; $i++) {
  1335. $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
  1336. $ampPeriods[] = [
  1337. 'USER_ID' => $order->USER_ID,
  1338. 'ORDER_SN' => $order->SN,
  1339. 'PERIOD_NUM' => $startPeriodNum + $i - 1,
  1340. 'BV' => $currentBv,
  1341. ];
  1342. }
  1343. if (!empty($ampPeriods)) {
  1344. AmpPeriod::batchInsert($ampPeriods);
  1345. }
  1346. } catch (\Exception $e) {
  1347. // 记录日志或进行错误处理
  1348. \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
  1349. }
  1350. }
  1351. }