ApproachAutoMaintenanceOrderForm.php 30 KB

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