OrderForm.php 48 KB

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