OrderForm.php 49 KB

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