ApproachOrderForm.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. <?php
  2. namespace common\models\forms;
  3. use Codeception\Module\Db;
  4. use common\helpers\Cache;
  5. use common\helpers\Date;
  6. use common\components\Model;
  7. use common\helpers\Form;
  8. use common\helpers\LoggerTool;
  9. use common\helpers\PayStack;
  10. use common\helpers\user\Balance;
  11. use common\helpers\user\Cash;
  12. use common\helpers\user\Info;
  13. use common\libs\logging\operate\AdminOperate;
  14. use common\models\AmpPeriod;
  15. use common\models\ApproachDecOrder;
  16. use common\models\ApproachOrder;
  17. use common\models\ApproachOrderGoods;
  18. use common\models\BaUser;
  19. use common\models\Countries;
  20. use common\models\CurrencyConversions;
  21. use common\models\DealType;
  22. use common\models\DecLevelLog;
  23. use common\models\DecOrder;
  24. use common\models\FreeTemplate;
  25. use common\models\Order;
  26. use common\models\OrderGoods;
  27. use common\models\Period;
  28. use common\models\ReceiveAddress;
  29. use common\models\Region;
  30. use common\models\ShopGoods;
  31. use common\models\ShopGoodsNature;
  32. use common\models\User;
  33. use common\models\UserNetwork;
  34. use common\models\Instalment;
  35. use Yii;
  36. use yii\base\Exception;
  37. /**
  38. * Login form
  39. */
  40. class ApproachOrderForm extends Model
  41. {
  42. public $sn;
  43. public $expressCompany;
  44. public $orderTrackNo;
  45. public $status;
  46. public $remark;
  47. public $note;
  48. public $type;
  49. public $addressId;
  50. public $payType;
  51. public $goodsId;
  52. public $goodsNum;
  53. public $payPassword;
  54. public $email;
  55. public $exchangeRate;
  56. public $period;
  57. public $userName;
  58. public $decUserName;
  59. public $consignee;
  60. public $acceptMobile;
  61. public $province;
  62. public $city;
  63. public $county;
  64. public $lgaName;
  65. public $cityName;
  66. public $detailaddress;
  67. private $_address;
  68. private $_decAmount;
  69. private $_decPv;
  70. private $_freight;
  71. private $_payAmount;
  72. private $_orderGoods;
  73. private $_standardAmount;
  74. private $_decAmountStandard;
  75. /**
  76. * @var ApproachOrder
  77. */
  78. private $_model;
  79. public function init() {
  80. parent::init();
  81. $this->adminOperateLogger = new AdminOperate([
  82. 'fetchClass' => ApproachOrder::class,
  83. ]);
  84. }
  85. /**
  86. * @inheritdoc
  87. */
  88. public function rules()
  89. {
  90. return [
  91. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
  92. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
  93. [['status'], 'isStatus'],
  94. [['addressId'], 'isAddress'],
  95. [['payType'], 'isPayType'],
  96. [['payPassword'], 'validatePassword'],
  97. ];
  98. }
  99. public function attributeLabels()
  100. {
  101. return [
  102. 'sn' => Yii::t('app', 'orderSn'),
  103. 'expressCompany' => Yii::t('app', 'expressCompany'),
  104. 'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
  105. 'status' => Yii::t('app', 'state'),
  106. 'remark' => Yii::t('app', 'remark'),
  107. 'type' => Yii::t('app', 'orderType'),
  108. 'addressId' => Yii::t('app', 'shippingAddress'),
  109. 'payType' => Yii::t('app', 'payType'),
  110. 'goodsId' => Yii::t('app', 'productID'),
  111. 'goodsNum' => Yii::t('app', 'quantity'),
  112. 'userName' => Yii::t('app', 'repeatSalesMemberNo'),
  113. 'consignee' => Yii::t('app', 'consignee'),
  114. 'acceptMobile' => Yii::t('app', 'acceptMobile'),
  115. 'province' => Yii::t('app', 'province'),
  116. 'city' => Yii::t('app', 'city'),
  117. 'county' => Yii::t('app', 'county'),
  118. 'lgaName' =>Yii::t('app', 'lgaName'),
  119. 'cityName' => Yii::t('app', 'cityName'),
  120. 'detailaddress' => Yii::t('app', 'detailAddress'),
  121. 'email' => Yii::t('app', 'email'),
  122. 'autoMaintenance' => Yii::t('app', 'amp'),
  123. ];
  124. }
  125. /**
  126. * 指定校验场景
  127. * @return array
  128. */
  129. public function scenarios()
  130. {
  131. $parentScenarios = parent::scenarios();
  132. $customScenarios = [
  133. // 管理员修改订单状态
  134. 'adminStatus' => ['sn', 'status'],
  135. // 校验订单支付
  136. 'verifyPayStack' => ['sn', 'note', 'status'],
  137. // 会员下单
  138. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
  139. ];
  140. return array_merge($parentScenarios, $customScenarios);
  141. }
  142. /**
  143. * 校验之前
  144. * @return bool
  145. */
  146. public function beforeValidate()
  147. {
  148. $parentValidate = parent::beforeValidate();
  149. if ($this->sn) {
  150. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  151. if (!$this->_model){
  152. $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
  153. return false;
  154. }
  155. }
  156. if ($this->scenario == 'verifyPayStack'){
  157. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  158. $this->addError('sn', Yii::t('app', 'payTypeError'));
  159. return false;
  160. }
  161. }
  162. return $parentValidate;
  163. }
  164. /**
  165. * 判断收货地址是否存在
  166. * @param $attribute
  167. */
  168. public function isAddress($attribute){
  169. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  170. $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
  171. } else {
  172. $this->_address = $receiveAddress;
  173. }
  174. }
  175. /**
  176. * 校验支付密码
  177. * @param $attribute
  178. * @param $params
  179. */
  180. public function validatePassword($attribute, $params) {
  181. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  182. $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
  183. }
  184. }
  185. /**
  186. * 判断支付方式
  187. * @param $attribute
  188. */
  189. public function isPayType($attribute)
  190. {
  191. if ($this->payType != 'pay_stack'){
  192. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  193. return;
  194. }
  195. // 一个订单只能包含一类商品
  196. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  197. if (!$goods) {
  198. throw new Exception(Yii::t('app', 'orderCanNotContainMultipleProductCategories'));
  199. return;
  200. }
  201. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  202. if (count($goodsCategoryType) > 1) {
  203. $this->addError($attribute, Yii::t('app', 'orderCanNotHasMoreClassification'));
  204. return;
  205. }
  206. // 购买方式
  207. $sellTypeLabelMap = array_column(ShopGoods::getSaleType(), NULL, 'label');
  208. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  209. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  210. return;
  211. }
  212. // 所选支付方式必须是商品分类支持的类型
  213. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  214. // 商品类型
  215. $currCategoryType = $goodsCategoryType[0];
  216. if (!array_key_exists($currCategoryType, $categoryType)) {
  217. $this->addError($attribute, Yii::t('app', 'shopGoodClassificationError'));
  218. return;
  219. }
  220. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  221. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  222. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  223. }
  224. }
  225. /**
  226. * 校验类型
  227. * @param $attribute
  228. */
  229. public function isStatus($attribute){
  230. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  231. $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
  232. return ;
  233. }
  234. if ($this->scenario == 'adminStatus'){
  235. if ($this->status == $this->_model['STATUS']) {
  236. $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
  237. return ;
  238. }
  239. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  240. $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
  241. return ;
  242. }
  243. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  244. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  245. return ;
  246. }
  247. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  248. $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
  249. return ;
  250. }
  251. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  252. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  253. return ;
  254. }
  255. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  256. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  257. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
  258. return ;
  259. }
  260. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  261. $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
  262. return ;
  263. }
  264. }
  265. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  266. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  267. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
  268. return ;
  269. }
  270. }
  271. }
  272. }
  273. /**
  274. * 校验PayStack支付,更新订单状态.同步到正式订单.
  275. * @throws Exception
  276. */
  277. public function verifyPayStack(): ?ApproachOrder
  278. {
  279. if (!$this->validate()) {
  280. return null;
  281. }
  282. // 调用PayStack支付校验
  283. LoggerTool::info([$this->note['reference'], $this->note]);
  284. // $payload = PayStack::transactionVerify($this->note['reference']);
  285. // LoggerTool::info($payload);
  286. // if ($payload['status'] !== true) {
  287. // throw new Exception(Form::formatErrorsForApi($payload['message']));
  288. // }
  289. // if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  290. // throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'payAmountNotEqualOrderAmount')));
  291. // }
  292. // 订单类型:userOrder(会员订单)、userUpgrade(会员升级)、userDec(会员报单)
  293. $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
  294. $db = \Yii::$app->db;
  295. $transaction = $db->beginTransaction();
  296. try {
  297. // 更新准订单状态为已支付
  298. $this->_model->STATUS = $this->status;
  299. $this->_model->NOTE = json_encode($this->note);
  300. $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
  301. $this->_model->EMAIL = $this->note['email'];
  302. if (!$this->_model->save()) {
  303. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  304. }
  305. // 更新订单商品的支付Email
  306. ApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  307. // 同步准订单到正式订单
  308. Order::insertOne($this->_model->toArray());
  309. // 同步准订单商品到正式订单商品
  310. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  311. foreach ($approachOrderGoods as &$approachOrderGood) {
  312. $approachOrderGood['EMAIL'] = $this->email;
  313. }
  314. OrderGoods::batchInsert($approachOrderGoods);
  315. // AMP订单
  316. $order = Order::findOne($this->_model->ID);
  317. if ($order['AUTO_MAINTENANCE'] == 1) {
  318. $this->orderAutoMaintenance($order);
  319. }
  320. // 会员报单、BA升级
  321. if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
  322. // 同步报单
  323. $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  324. if ($approachDecOrder) {
  325. unset($approachDecOrder['STATUS']);
  326. // 同步报单
  327. DecOrder::insertOne($approachDecOrder);
  328. // 修改会员锁定状态
  329. if (in_array($orderType, ['userDec', 'baUpgrade'])) {
  330. if (!User::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
  331. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'changeUserStatusError')));
  332. }
  333. }
  334. // 正式会员-升级单
  335. if ($orderType === 'userUpgrade') {
  336. // 会员升级 报单类型:2会员升级单
  337. if ($approachDecOrder['DETAIL_TYPE'] == 2) {
  338. // 为被升级人进行升级操作
  339. $decLevelLog = new DecLevelLog();
  340. $decLog = [
  341. 'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
  342. 'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
  343. 'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
  344. 'actionId' => $approachDecOrder['USER_ID'],
  345. 'remark' => $approachDecOrder['REMARK'],
  346. 'lvPv' => $this->_model->PV,
  347. ];
  348. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  349. if (empty($modifyDecLv)) {
  350. $transaction->rollBack();
  351. throw new Exception(Yii::t('app', 'failedToUpgrade'));
  352. }
  353. }
  354. }
  355. // 删除中间表
  356. ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  357. }
  358. }
  359. // 删除中间表
  360. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  361. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  362. $transaction->commit();
  363. } catch (Exception $e) {
  364. $transaction->rollBack();
  365. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  366. return null;
  367. }
  368. return $this->_model;
  369. }
  370. /**
  371. * 复销
  372. * @throws Exception
  373. * @throws \yii\db\Exception
  374. */
  375. public function add(){
  376. if(!$this->validate()){
  377. return null;
  378. }
  379. $ids = $this->goodsId;
  380. $totalAmount = 0;
  381. $totalPv = 0;
  382. $totalAmountStandard = 0;
  383. $goodsType = ShopGoods::getGoodType();
  384. $hasInstalment = 0;
  385. $loginUserId = \Yii::$app->user->id;
  386. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  387. foreach ($this->goodsNum as $k => $v) {
  388. if ($v) {
  389. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  390. if (!$goods) {
  391. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  392. }
  393. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  394. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  395. if (!$goodsNature) {
  396. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  397. }
  398. // 汇率
  399. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  400. if($goods['STORE_NUMS']>0){
  401. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  402. $discount = $goodsType[$goods['TYPE']]['discount'];
  403. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  404. $realPv = $goods['PRICE_PV'] * $discount/100;
  405. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  406. } else {
  407. $discount = $goods['SELL_DISCOUNT'];
  408. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  409. $realPv = $goods['PRICE_PV'] * $discount;
  410. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  411. }
  412. $totalAmount += $realPrice * intval($v);
  413. $totalPv += $realPv * intval($v);
  414. $totalAmountStandard += $realPriceStandard * intval($v);
  415. $this->_orderGoods[] = [
  416. 'GOODS_ID' => $goods['ID'],
  417. 'PRICE' => $goodsNature['SELL_PRICE'],
  418. 'PV' => $goods['PRICE_PV'],
  419. 'REAL_PRICE' => $realPrice,
  420. 'REAL_PV' => $realPv,
  421. 'POINT' => $goods['POINT'],
  422. 'BUY_NUMS' => intval($v),
  423. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  424. 'SKU_CODE' => $goods['GOODS_NO'],
  425. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  426. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  427. 'PAY_TYPE' => $this->payType,
  428. 'EMAIL' => $this->email,
  429. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  430. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  431. 'EXCHANGE_RATE' => $goodsNature['TAX_RATE'],
  432. ];
  433. }
  434. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  435. if($v>1){ // 不可以购买多个
  436. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  437. }
  438. $userStage = Instalment::getStage($loginUserId);
  439. // 分期的总期数
  440. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  441. // 分期商品的期数不能大于总分期数限制
  442. if (intval($goods['INSTALMENT']) > $instalment) {
  443. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  444. }
  445. if ($userStage==0){
  446. } else if ($userStage == $instalment) {
  447. if ($goods['INSTALMENT'] != 1) {
  448. throw new Exception(Yii::t('app', 'canNotBuy'));
  449. }
  450. }else{
  451. if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  452. throw new Exception(Yii::t('app', 'canNotBuy'));
  453. }
  454. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  455. throw new Exception(Yii::t('app', 'canNotBuy'));
  456. }
  457. }
  458. $hasInstalment = $goods['INSTALMENT'];
  459. }
  460. }
  461. }
  462. // 运费模板
  463. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  464. // 运费
  465. $freight = $freeTemplate['freight'] ?? 0;
  466. // 普通商品免运费阈值
  467. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  468. $this->_decAmount = $totalAmount;
  469. $this->_decPv = $totalPv;
  470. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  471. if($this->_address['PROVINCE']==1){
  472. $this->_freight = 0;
  473. }
  474. $this->_payAmount = $this->_decAmount + $this->_freight;
  475. $this->_decAmountStandard = $totalAmountStandard;
  476. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  477. $db = \Yii::$app->db;
  478. $transaction = $db->beginTransaction();
  479. try {
  480. //写入订单
  481. if (!$orderResult = $this->addOrder()) {
  482. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  483. }
  484. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  485. $instalmentModel = Instalment::findOne(['USER_ID'=>$loginUserId]);
  486. if(!$instalmentModel) {
  487. $instalmentModel = new Instalment();
  488. }
  489. $instalmentModel->USER_ID = $loginUserId;
  490. $instalmentModel->STAGE = $hasInstalment;
  491. $instalmentModel->UPDATE_TIME = time();
  492. $instalmentModel->save();
  493. }
  494. $transaction->commit();
  495. return $orderResult;
  496. }catch (\Exception $e){
  497. $transaction->rollBack();
  498. $this->addError('add', $e->getMessage());
  499. return null;
  500. }
  501. }
  502. /**
  503. * 复销订单
  504. * @throws Exception
  505. */
  506. public function addOrder()
  507. {
  508. $periodObj = Period::instance();
  509. $nowPeriodNum = $this->period ?: $periodObj->getNowPeriodNum();
  510. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  511. $userId = \Yii::$app->user->id;
  512. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  513. $userName = Info::getUserNameByUserId($userId);
  514. $userRealName = Info::getUserRealNameByUserId($userId);
  515. $userMobile = Info::getUserMobileByUserId($userId);
  516. $userEmail = Info::getUserEmailByUserId($userId);
  517. $country = Countries::getById($user['COUNTRY_ID']);
  518. // 加入订单信息
  519. if ($this->_address['PROVINCE'] != 1) {
  520. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  521. if (!$warehouse) {
  522. // throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  523. }
  524. }else{
  525. $warehouse = '01';
  526. }
  527. $_hasPV = $this->_decPv;
  528. $ordNo = $this->_generateSn();
  529. $orderModel = new ApproachOrder();
  530. $orderModel->SN = 'OS' . $ordNo;
  531. $orderModel->DEC_SN = 'DS' . $ordNo;
  532. $orderModel->ORDER_TYPE = $this->type;
  533. $orderModel->USER_ID = $userId;
  534. $orderModel->USER_NAME = $userName;
  535. $orderModel->DEC_USER_ID = $this->decUserName;
  536. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  537. $orderModel->PV = $_hasPV;
  538. $orderModel->PAY_AMOUNT = $this->_payAmount;
  539. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  540. $orderModel->PAY_AT = 0;
  541. $orderModel->PAY_TYPE = $this->payType;
  542. $orderModel->PERIOD_NUM = $nowPeriodNum;
  543. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  544. $orderModel->FREIGHT = $this->_freight;
  545. $orderModel->PAY_FREIGHT = $this->_freight;
  546. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  547. $orderModel->MOBILE = $this->_address['MOBILE'];
  548. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  549. // $orderModel->CITY = $this->_address['CITY'];
  550. // $orderModel->COUNTY = $this->_address['COUNTY'];
  551. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  552. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  553. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  554. $orderModel->FRONT_REMARK = $this->remark;
  555. $orderModel->WAREHOUSE = $warehouse;
  556. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  557. $orderModel->CREATED_AT = Date::nowTime();
  558. $orderModel->CREATE_USER = $userName;
  559. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
  560. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  561. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  562. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  563. $orderModel->COUNTRY_ID = $user['COUNTRY_ID'];
  564. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  565. if($this->_address['PROVINCE']==1){
  566. $orderModel->EXPRESS_TYPE = 1;
  567. $orderModel->CONSIGNEE = $userRealName;
  568. $orderModel->MOBILE = $userMobile;
  569. $orderModel->PROVINCE = 1;
  570. $orderModel->CITY = 1;
  571. $orderModel->COUNTY = 1;
  572. $orderModel->ADDRESS = '';
  573. }
  574. if(!$orderModel->save()){
  575. $this->addErrors($orderModel->getErrors());
  576. return false;
  577. }
  578. // 加入商品到订单商品表
  579. foreach($this->_orderGoods as $key=>$value) {
  580. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  581. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  582. }
  583. ApproachOrderGoods::batchInsert($this->_orderGoods);
  584. return $orderModel;
  585. }
  586. /**
  587. * 生成流水号
  588. * @return string
  589. */
  590. private function _generateSn() {
  591. return Date::today('Ymd') . $this->_random(10, 1);
  592. }
  593. /**
  594. * 生成随机数
  595. * @param $length
  596. * @param int $numeric
  597. * @return string
  598. */
  599. private function _random($length, $numeric = 0) {
  600. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  601. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  602. $hash = '';
  603. $max = strlen($seed) - 1;
  604. for ($i = 0; $i < $length; $i++) {
  605. $hash .= $seed[mt_rand(0, $max)];
  606. }
  607. return $hash;
  608. }
  609. private function orderAutoMaintenance($order)
  610. {
  611. $nowPeriodNum = Period::instance()->getNowPeriodNum();
  612. try {
  613. $sysConfig = Cache::getSystemConfig();
  614. $divideLine = (int)$sysConfig['monthPcsPvFxCondition']['VALUE'];
  615. $orderTotalBv = $order->PV;
  616. if ($orderTotalBv <= $divideLine) {
  617. return;
  618. }
  619. $lastAmpPeriod = AmpPeriod::find()
  620. ->where(['USER_ID' => $order->USER_ID])
  621. ->orderBy(['PERIOD_NUM' => SORT_DESC])
  622. ->one();
  623. $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
  624. if (!$lastAmpPeriod) {
  625. $memberOrderBv = Order::find()
  626. ->select('SUM(PV) AS total_pv')
  627. ->where([
  628. 'USER_ID' => $order->USER_ID,
  629. 'IS_DELETE' => 0,
  630. 'PERIOD_NUM' => $nowPeriodNum
  631. ])
  632. ->scalar();
  633. if ($memberOrderBv >= $divideLine) {
  634. $startPeriodNum = $nowPeriodNum + 1;
  635. }
  636. }
  637. $periodCount = floor($orderTotalBv / $divideLine);
  638. $remainderBv = $orderTotalBv % $divideLine;
  639. $ampPeriods = [];
  640. for ($i = 1; $i <= $periodCount; $i++) {
  641. $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
  642. $ampPeriods[] = [
  643. 'USER_ID' => $order->USER_ID,
  644. 'ORDER_SN' => $order->SN,
  645. 'PERIOD_NUM' => $startPeriodNum + $i - 1,
  646. 'BV' => $currentBv,
  647. ];
  648. }
  649. if (!empty($ampPeriods)) {
  650. AmpPeriod::batchInsert($ampPeriods);
  651. }
  652. } catch (\Exception $e) {
  653. // 记录日志或进行错误处理
  654. \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
  655. }
  656. }
  657. }