ApproachAutoMaintenanceOrderForm.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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\user\Balance;
  10. use common\helpers\user\Cash;
  11. use common\helpers\user\Info;
  12. use common\libs\logging\operate\AdminOperate;
  13. use common\models\AmpPeriod;
  14. use common\models\ApproachDecOrder;
  15. use common\models\ApproachOrder;
  16. use common\models\ApproachReconsumeOrder;
  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. class ApproachAutoMaintenanceOrderForm extends Model
  38. {
  39. public $sn;
  40. public $expressCompany;
  41. public $orderTrackNo;
  42. public $status;
  43. public $remark;
  44. public $note;
  45. public $type;
  46. public $addressId;
  47. public $payType;
  48. public $goodsId;
  49. public $goodsNum;
  50. public $payPassword;
  51. public $email;
  52. public $userName;
  53. public $decUserName;
  54. public $consignee;
  55. public $acceptMobile;
  56. public $province;
  57. public $city;
  58. public $county;
  59. public $lgaName;
  60. public $cityName;
  61. public $autoMaintenance;
  62. public $exchangeRate;
  63. public $detailaddress;
  64. private $_address;
  65. private $_decAmount;
  66. private $_decPv;
  67. private $_realPv;
  68. private $_freight;
  69. private $_payAmount;
  70. private $_orderGoods;
  71. private $_standardAmount;
  72. private $_decAmountStandard;
  73. /**
  74. * @var ApproachOrder
  75. */
  76. private $_model;
  77. public function init() {
  78. parent::init();
  79. $this->adminOperateLogger = new AdminOperate([
  80. 'fetchClass' => ApproachOrder::class,
  81. ]);
  82. }
  83. /**
  84. * @inheritdoc
  85. */
  86. public function rules()
  87. {
  88. return [
  89. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
  90. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
  91. [['status'], 'isStatus'],
  92. [['addressId'], 'isAddress'],
  93. [['payType'], 'isPayType'],
  94. [['payPassword'], 'validatePassword'],
  95. ];
  96. }
  97. public function attributeLabels()
  98. {
  99. return [
  100. 'sn' => Yii::t('app', 'orderSn'),
  101. 'expressCompany' => Yii::t('app', 'expressCompany'),
  102. 'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
  103. 'status' => Yii::t('app', 'state'),
  104. 'remark' => Yii::t('app', 'remark'),
  105. 'type' => Yii::t('app', 'orderType'),
  106. 'addressId' => Yii::t('app', 'shippingAddress'),
  107. 'payType' => Yii::t('app', 'payType'),
  108. 'goodsId' => Yii::t('app', 'productID'),
  109. 'goodsNum' => Yii::t('app', 'quantity'),
  110. 'userName' => Yii::t('app', 'repeatSalesMemberNo'),
  111. 'consignee' => Yii::t('app', 'consignee'),
  112. 'acceptMobile' => Yii::t('app', 'acceptMobile'),
  113. 'province' => Yii::t('app', 'province'),
  114. 'city' => Yii::t('app', 'city'),
  115. 'county' => Yii::t('app', 'county'),
  116. 'lgaName' =>Yii::t('app', 'lgaName'),
  117. 'cityName' => Yii::t('app', 'cityName'),
  118. 'detailaddress' => Yii::t('app', 'detailAddress'),
  119. 'email' => Yii::t('app', 'email'),
  120. ];
  121. }
  122. /**
  123. * 指定校验场景
  124. * @return array
  125. */
  126. public function scenarios()
  127. {
  128. $parentScenarios = parent::scenarios();
  129. $customScenarios = [
  130. // 管理员修改订单状态
  131. 'adminStatus' => ['sn', 'status'],
  132. // 校验订单支付
  133. 'verifyPayStack' => ['sn', 'note', 'status'],
  134. // 会员下单
  135. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
  136. // 为会员复消
  137. 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress'],
  138. ];
  139. return array_merge($parentScenarios, $customScenarios);
  140. }
  141. /**
  142. * 校验之前
  143. * @return bool
  144. */
  145. public function beforeValidate()
  146. {
  147. $parentValidate = parent::beforeValidate();
  148. if ($this->sn) {
  149. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  150. if (!$this->_model){
  151. $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
  152. return false;
  153. }
  154. }
  155. if ($this->scenario == 'verifyPayStack'){
  156. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  157. $this->addError('sn', Yii::t('app', 'payTypeError'));
  158. return false;
  159. }
  160. }
  161. return $parentValidate;
  162. }
  163. /**
  164. * 判断收货地址是否存在
  165. * @param $attribute
  166. */
  167. public function isAddress($attribute){
  168. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  169. $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
  170. } else {
  171. $this->_address = $receiveAddress;
  172. }
  173. }
  174. /**
  175. * 校验支付密码
  176. * @param $attribute
  177. * @param $params
  178. */
  179. public function validatePassword($attribute, $params) {
  180. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  181. $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
  182. }
  183. }
  184. /**
  185. * 判断支付方式
  186. * @param $attribute
  187. * @throws Exception
  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::SALE_TYPE, 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. // 修改BA会员升级状态
  335. if ($orderType === 'baUpgrade') {
  336. // 查询BA会员名
  337. $userInfo = User::findOneAsArray('ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']]);
  338. if (!BaUser::updateAll(['WHETHER_UPGRADE' => 1, 'BA_UPGRADE_AT' => time()], 'USER_NAME=:USER_NAME', [':USER_NAME' => $userInfo['USER_NAME']])) {
  339. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'brandAmbassadorUpgradeError')));
  340. }
  341. }
  342. // 正式会员-升级单
  343. if ($orderType === 'userUpgrade') {
  344. // 会员升级 报单类型:2会员升级单
  345. if ($approachDecOrder['DETAIL_TYPE'] == 2) {
  346. // 为被升级人进行升级操作
  347. $decLevelLog = new DecLevelLog();
  348. $decLog = [
  349. 'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
  350. 'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
  351. 'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
  352. 'actionId' => $approachDecOrder['USER_ID'],
  353. 'remark' => $approachDecOrder['REMARK'],
  354. 'lvPv' => $this->_model->PV,
  355. ];
  356. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  357. if (empty($modifyDecLv)) {
  358. $transaction->rollBack();
  359. throw new Exception(Yii::t('app', 'failedToUpgrade'));
  360. }
  361. }
  362. }
  363. // 删除中间表
  364. ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  365. }
  366. }
  367. // 删除中间表
  368. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  369. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  370. $transaction->commit();
  371. } catch (Exception $e) {
  372. $transaction->rollBack();
  373. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  374. return null;
  375. }
  376. return $this->_model;
  377. }
  378. /**
  379. * AMP
  380. * @throws Exception
  381. * @throws \yii\db\Exception
  382. */
  383. public function autoMaintenanceSureOrder()
  384. {
  385. if(!$this->validate()){
  386. return null;
  387. }
  388. $ids = $this->goodsId;
  389. $totalAmount = 0;
  390. $totalPv = 0;
  391. $totalRealPv = 0;
  392. $totalAmountStandard = 0;
  393. $this->autoMaintenance = 1;
  394. $goodsType = ShopGoods::getGoodType();
  395. $hasInstalment = 0;
  396. $userId = Info::getUserIdByUserName($this->userName);
  397. $user = User::getEnCodeInfo($userId);
  398. $decUserID = Info::getUserIdByUserName($this->decUserName);
  399. $stockist_user = User::getEnCodeInfo($decUserID);
  400. if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
  401. throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
  402. }
  403. // 报单中心汇率
  404. $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
  405. $decCountry = Countries::getById($decCountryId);
  406. $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
  407. // 会员汇率
  408. $country = Countries::getById($user['COUNTRY_ID']);
  409. $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
  410. // 判断是否是报单中心
  411. $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
  412. if ($loginUser['IS_DEC'] == 1){
  413. if($decUserID != \Yii::$app->user->id){
  414. throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
  415. }
  416. }
  417. foreach ($this->goodsNum as $k => $v) {
  418. if ($v) {
  419. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1 AND AUTO_MAINTENANCE=1',[':ID'=> $ids[$k]]);
  420. if (!$goods) {
  421. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  422. }
  423. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  424. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  425. if (!$goodsNature) {
  426. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  427. }
  428. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  429. if($goods['STORE_NUMS']>0){
  430. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  431. $discount = $goodsType[$goods['TYPE']]['discount'];
  432. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  433. $realPv = $goods['PRICE_PV'] * $discount/100;
  434. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  435. } else {
  436. $discount = $goods['SELL_DISCOUNT'];
  437. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  438. $realPv = $goods['PRICE_PV'] * $discount;
  439. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  440. }
  441. $currentPv = $goods['PRICE_PV'];
  442. $totalPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  443. $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  444. $totalAmount += $realPrice * intval($v);
  445. $totalAmountStandard += $realPriceStandard * intval($v);
  446. $this->_orderGoods[] = [
  447. 'GOODS_ID' => $goods['ID'],
  448. 'PRICE' => $goodsNature['SELL_PRICE'],
  449. 'PV' => $currentPv,
  450. 'REAL_PRICE' => $realPrice,
  451. 'REAL_PV' => $realPv,
  452. 'REMAIN_PV' => 0,
  453. 'POINT' => $goods['POINT'],
  454. 'BUY_NUMS' => intval($v),
  455. 'SKU_CODE' => $goods['GOODS_NO'],
  456. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  457. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  458. 'PAY_TYPE' => $this->payType,
  459. 'EMAIL' => $this->email,
  460. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  461. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  462. 'EXCHANGE_RATE' => $currencyRate,
  463. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  464. ];
  465. }
  466. if ($goods['INSTALMENT']>0) {
  467. if ($v > 1) {
  468. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  469. }
  470. $userStage = Instalment::getStage($userId);
  471. $userInstalmentInfo = Instalment::getInfo($userId);
  472. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  473. if (intval($goods['INSTALMENT']) > $instalment) {
  474. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  475. }
  476. if ($userStage == $instalment) {
  477. if ($goods['INSTALMENT'] != 1) {
  478. throw new Exception(Yii::t('app', 'canNotBuy'));
  479. }
  480. } else {
  481. if ($userInstalmentInfo) {
  482. if ($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE'] != 'FX') {
  483. throw new Exception(Yii::t('app', 'canNotBuy'));
  484. }
  485. }
  486. if ($userStage + 1 != $goods['INSTALMENT']) {
  487. throw new Exception(Yii::t('app', 'canNotBuy'));
  488. }
  489. if ($userStage + 1 > $instalment){
  490. throw new Exception(Yii::t('app', 'canNotBuy'));
  491. }
  492. }
  493. $hasInstalment = $goods['INSTALMENT'];
  494. }
  495. }
  496. }
  497. // 运费模板
  498. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  499. // 运费
  500. $freight = $freeTemplate['freight'] ?? 0;
  501. // 普通商品免运费阈值
  502. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  503. $this->_decAmount = $totalAmount;
  504. $this->_decPv = $totalPv;
  505. $this->_realPv = $totalRealPv;
  506. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  507. $this->_payAmount = $this->_decAmount + $this->_freight;
  508. $this->_decAmountStandard = $totalAmountStandard;
  509. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  510. $db = \Yii::$app->db;
  511. $transaction = $db->beginTransaction();
  512. try {
  513. //写入订单
  514. if (!$orderResult = $this->addOrder()) {
  515. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  516. }
  517. if ($hasInstalment){
  518. $instalmentModel = Instalment::findOne(['USER_ID' => $userId]);
  519. if(!$instalmentModel) {
  520. $instalmentModel = new Instalment();
  521. }
  522. $instalmentModel->USER_ID = $userId;
  523. $instalmentModel->STAGE = $hasInstalment;
  524. $instalmentModel->UPDATE_TIME = time();
  525. $instalmentModel->save();
  526. }
  527. $transaction->commit();
  528. return $orderResult;
  529. }catch (\Exception $e){
  530. $transaction->rollBack();
  531. $this->addError('add', $e->getMessage());
  532. return null;
  533. }
  534. }
  535. /**
  536. * 复销订单
  537. * @throws Exception
  538. */
  539. public function addOrder()
  540. {
  541. $periodObj = Period::instance();
  542. $nowPeriodNum = $periodObj->getNowPeriodNum();
  543. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  544. //帮复消会员Id(登陆会员)
  545. $loginUserId = \Yii::$app->user->id;
  546. $loginUserName = Info::getUserNameByUserId($loginUserId);
  547. //订单会员Id
  548. $userId = Info::getUserIdByUserName($this->userName);
  549. $countryId = Info::getUserCountryByUserId($userId);
  550. $email = Info::getEmailByUserId($this->userName);
  551. $country = Countries::getById($countryId);
  552. $warehouse = '01';
  553. $_hasPV = $this->_decPv;
  554. $ordNo = $this->_generateSn();
  555. $orderModel = new ApproachReconsumeOrder();
  556. $orderModel->SN = 'OS' . $ordNo;
  557. $orderModel->DEC_SN = 'DS' . $ordNo;
  558. $orderModel->ORDER_TYPE = $this->type;
  559. $orderModel->USER_ID = $userId;
  560. $orderModel->USER_NAME = $this->userName;
  561. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  562. $orderModel->PV = $_hasPV;
  563. $orderModel->PAY_AMOUNT = $this->_payAmount;
  564. $orderModel->PAY_PV = $_hasPV;
  565. $orderModel->PAY_AT = 0;
  566. $orderModel->PAY_TYPE = $this->payType;
  567. $orderModel->PERIOD_NUM = $nowPeriodNum;
  568. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  569. $orderModel->FREIGHT = $this->_freight;
  570. $orderModel->PAY_FREIGHT = $this->_freight;
  571. $orderModel->CONSIGNEE = $this->consignee;
  572. $orderModel->MOBILE = $this->acceptMobile;
  573. $orderModel->PROVINCE = $this->province[0];
  574. $orderModel->LGA_NAME = $this->lgaName;
  575. $orderModel->CITY_NAME = $this->cityName;
  576. $orderModel->ADDRESS = $this->detailaddress;
  577. $orderModel->FRONT_REMARK = $this->remark;
  578. $orderModel->WAREHOUSE = $warehouse;
  579. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  580. $orderModel->CREATED_AT = Date::nowTime();
  581. $orderModel->CREATE_USER = $loginUserName;
  582. $orderModel->EMAIL = $email ?? '';
  583. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  584. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  585. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  586. $orderModel->COUNTRY_ID = $countryId;
  587. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  588. $orderModel->DEC_USER_ID = $this->decUserName;
  589. $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
  590. if(!$orderModel->save()){
  591. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  592. }
  593. // 加入商品到订单商品表
  594. foreach($this->_orderGoods as $key=>$value) {
  595. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  596. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  597. }
  598. ApproachOrderGoods::batchInsert($this->_orderGoods);
  599. return $orderModel;
  600. }
  601. /**
  602. * 生成流水号
  603. * @return string
  604. */
  605. private function _generateSn() {
  606. return Date::today('Ymd') . $this->_random(10, 1);
  607. }
  608. /**
  609. * 生成随机数
  610. * @param $length
  611. * @param int $numeric
  612. * @return string
  613. */
  614. private function _random($length, $numeric = 0) {
  615. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  616. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  617. $hash = '';
  618. $max = strlen($seed) - 1;
  619. for ($i = 0; $i < $length; $i++) {
  620. $hash .= $seed[mt_rand(0, $max)];
  621. }
  622. return $hash;
  623. }
  624. private function orderAutoMaintenance($order)
  625. {
  626. $nowPeriodNum = Period::instance()->getNowPeriodNum();
  627. try {
  628. $sysConfig = Cache::getSystemConfig();
  629. $divideLine = (int)$sysConfig['monthPcsPvFxCondition']['VALUE'];
  630. $orderTotalBv = $order->PV;
  631. if ($orderTotalBv <= $divideLine) {
  632. return;
  633. }
  634. $lastAmpPeriod = AmpPeriod::find()
  635. ->where(['USER_ID' => $order->USER_ID])
  636. ->orderBy(['PERIOD_NUM' => SORT_DESC])
  637. ->one();
  638. $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
  639. if (!$lastAmpPeriod) {
  640. $memberOrderBv = Order::find()
  641. ->select('SUM(PV) AS total_pv')
  642. ->where([
  643. 'USER_ID' => $order->USER_ID,
  644. 'IS_DELETE' => 0,
  645. 'PERIOD_NUM' => $nowPeriodNum
  646. ])
  647. ->scalar();
  648. if ($memberOrderBv >= $divideLine) {
  649. $startPeriodNum = $nowPeriodNum + 1;
  650. }
  651. }
  652. $periodCount = floor($orderTotalBv / $divideLine);
  653. $remainderBv = $orderTotalBv % $divideLine;
  654. $ampPeriods = [];
  655. for ($i = 1; $i <= $periodCount; $i++) {
  656. $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
  657. $ampPeriods[] = [
  658. 'USER_ID' => $order->USER_ID,
  659. 'ORDER_SN' => $order->SN,
  660. 'PERIOD_NUM' => $startPeriodNum + $i - 1,
  661. 'BV' => $currentBv,
  662. ];
  663. }
  664. if (!empty($ampPeriods)) {
  665. AmpPeriod::batchInsert($ampPeriods);
  666. }
  667. } catch (\Exception $e) {
  668. // 记录日志或进行错误处理
  669. \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
  670. }
  671. }
  672. }