ApproachAutoMaintenanceOrderForm.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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. }
  202. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  203. if (count($goodsCategoryType) > 1) {
  204. $this->addError($attribute, Yii::t('app', 'orderCanNotHasMoreClassification'));
  205. return;
  206. }
  207. // 购买方式
  208. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  209. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  210. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  211. return;
  212. }
  213. // 所选支付方式必须是商品分类支持的类型
  214. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  215. // 商品类型
  216. $currCategoryType = $goodsCategoryType[0];
  217. if (!array_key_exists($currCategoryType, $categoryType)) {
  218. $this->addError($attribute, Yii::t('app', 'shopGoodClassificationError'));
  219. return;
  220. }
  221. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  222. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  223. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  224. }
  225. }
  226. /**
  227. * 校验类型
  228. * @param $attribute
  229. */
  230. public function isStatus($attribute){
  231. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  232. $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
  233. return ;
  234. }
  235. if ($this->scenario == 'adminStatus'){
  236. if ($this->status == $this->_model['STATUS']) {
  237. $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
  238. return ;
  239. }
  240. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  241. $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
  242. return ;
  243. }
  244. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  245. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  246. return ;
  247. }
  248. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  249. $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
  250. return ;
  251. }
  252. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  253. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  254. return ;
  255. }
  256. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  257. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  258. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
  259. return ;
  260. }
  261. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  262. $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
  263. return ;
  264. }
  265. }
  266. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  267. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  268. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
  269. return ;
  270. }
  271. }
  272. }
  273. }
  274. /**
  275. * 校验PayStack支付,更新订单状态.同步到正式订单.
  276. * @throws Exception
  277. */
  278. public function verifyPayStack(): ?ApproachOrder
  279. {
  280. if (!$this->validate()) {
  281. return null;
  282. }
  283. // 调用PayStack支付校验
  284. LoggerTool::info([$this->note['reference'], $this->note]);
  285. $payload = PayStack::transactionVerify($this->note['reference']);
  286. LoggerTool::info($payload);
  287. if ($payload['status'] !== true) {
  288. throw new Exception(Form::formatErrorsForApi($payload['message']));
  289. }
  290. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  291. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'payAmountNotEqualOrderAmount')));
  292. }
  293. // 订单类型:userOrder(会员订单)、userUpgrade(会员升级)、userDec(会员报单)
  294. $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
  295. $db = \Yii::$app->db;
  296. $transaction = $db->beginTransaction();
  297. try {
  298. // 更新准订单状态为已支付
  299. $this->_model->STATUS = $this->status;
  300. $this->_model->NOTE = json_encode($this->note);
  301. $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
  302. $this->_model->EMAIL = $this->note['email'];
  303. if (!$this->_model->save()) {
  304. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  305. }
  306. // 更新订单商品的支付Email
  307. ApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  308. // 同步准订单到正式订单
  309. Order::insertOne($this->_model->toArray());
  310. // 同步准订单商品到正式订单商品
  311. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  312. foreach ($approachOrderGoods as &$approachOrderGood) {
  313. $approachOrderGood['EMAIL'] = $this->email;
  314. }
  315. OrderGoods::batchInsert($approachOrderGoods);
  316. // AMP订单
  317. $order = Order::findOne($this->_model->ID);
  318. if ($order['AUTO_MAINTENANCE'] == 1) {
  319. $this->orderAutoMaintenance($order);
  320. }
  321. // 会员报单、BA升级
  322. if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
  323. // 同步报单
  324. $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  325. if ($approachDecOrder) {
  326. unset($approachDecOrder['STATUS']);
  327. // 同步报单
  328. DecOrder::insertOne($approachDecOrder);
  329. // 修改会员锁定状态
  330. if (in_array($orderType, ['userDec', 'baUpgrade'])) {
  331. if (!User::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
  332. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'changeUserStatusError')));
  333. }
  334. }
  335. // 修改BA会员升级状态
  336. if ($orderType === 'baUpgrade') {
  337. // 查询BA会员名
  338. $userInfo = User::findOneAsArray('ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']]);
  339. if (!BaUser::updateAll(['WHETHER_UPGRADE' => 1, 'BA_UPGRADE_AT' => time()], 'USER_NAME=:USER_NAME', [':USER_NAME' => $userInfo['USER_NAME']])) {
  340. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'brandAmbassadorUpgradeError')));
  341. }
  342. }
  343. // 正式会员-升级单
  344. if ($orderType === 'userUpgrade') {
  345. // 会员升级 报单类型:2会员升级单
  346. if ($approachDecOrder['DETAIL_TYPE'] == 2) {
  347. // 为被升级人进行升级操作
  348. $decLevelLog = new DecLevelLog();
  349. $decLog = [
  350. 'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
  351. 'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
  352. 'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
  353. 'actionId' => $approachDecOrder['USER_ID'],
  354. 'remark' => $approachDecOrder['REMARK'],
  355. 'lvPv' => $this->_model->PV,
  356. ];
  357. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  358. if (empty($modifyDecLv)) {
  359. $transaction->rollBack();
  360. throw new Exception(Yii::t('app', 'failedToUpgrade'));
  361. }
  362. }
  363. }
  364. // 删除中间表
  365. ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  366. }
  367. }
  368. // 删除中间表
  369. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  370. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  371. $transaction->commit();
  372. } catch (Exception $e) {
  373. $transaction->rollBack();
  374. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  375. return null;
  376. }
  377. return $this->_model;
  378. }
  379. /**
  380. * AMP
  381. * @throws Exception
  382. * @throws \yii\db\Exception
  383. */
  384. public function autoMaintenanceSureOrder()
  385. {
  386. if(!$this->validate()){
  387. return null;
  388. }
  389. $ids = $this->goodsId;
  390. $totalAmount = 0;
  391. $totalPv = 0;
  392. $totalRealPv = 0;
  393. $totalAmountStandard = 0;
  394. $this->autoMaintenance = 1;
  395. $goodsType = ShopGoods::getGoodType();
  396. $hasInstalment = 0;
  397. $userId = Info::getUserIdByUserName($this->userName);
  398. $user = User::getEnCodeInfo($userId);
  399. $decUserID = Info::getUserIdByUserName($this->decUserName);
  400. $stockist_user = User::getEnCodeInfo($decUserID);
  401. if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
  402. throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
  403. }
  404. // 报单中心汇率
  405. $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
  406. $decCountry = Countries::getById($decCountryId);
  407. $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
  408. // 会员汇率
  409. $country = Countries::getById($user['COUNTRY_ID']);
  410. $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
  411. // 判断是否是报单中心
  412. $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
  413. if ($loginUser['IS_DEC'] == 1){
  414. if($decUserID != \Yii::$app->user->id){
  415. throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
  416. }
  417. }
  418. foreach ($this->goodsNum as $k => $v) {
  419. if ($v) {
  420. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1 AND AUTO_MAINTENANCE=1',[':ID'=> $ids[$k]]);
  421. if (!$goods) {
  422. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  423. }
  424. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  425. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  426. if (!$goodsNature) {
  427. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  428. }
  429. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  430. if($goods['STORE_NUMS']>0){
  431. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  432. $discount = $goodsType[$goods['TYPE']]['discount'];
  433. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  434. $realPv = $goods['PRICE_PV'] * $discount/100;
  435. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  436. } else {
  437. $discount = $goods['SELL_DISCOUNT'];
  438. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  439. $realPv = $goods['PRICE_PV'] * $discount;
  440. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  441. }
  442. $currentPv = $goods['PRICE_PV'];
  443. $totalPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  444. $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
  445. $totalAmount += $realPrice * intval($v);
  446. $totalAmountStandard += $realPriceStandard * intval($v);
  447. $this->_orderGoods[] = [
  448. 'GOODS_ID' => $goods['ID'],
  449. 'PRICE' => $goodsNature['SELL_PRICE'],
  450. 'PV' => $currentPv,
  451. 'REAL_PRICE' => $realPrice,
  452. 'REAL_PV' => $realPv,
  453. 'REMAIN_PV' => 0,
  454. 'POINT' => $goods['POINT'],
  455. 'BUY_NUMS' => intval($v),
  456. 'SKU_CODE' => $goods['GOODS_NO'],
  457. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  458. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  459. 'PAY_TYPE' => $this->payType,
  460. 'EMAIL' => $this->email,
  461. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  462. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  463. 'EXCHANGE_RATE' => $currencyRate,
  464. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  465. ];
  466. }
  467. if ($goods['INSTALMENT']>0) {
  468. if ($v > 1) {
  469. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  470. }
  471. $userStage = Instalment::getStage($userId);
  472. $userInstalmentInfo = Instalment::getInfo($userId);
  473. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  474. if (intval($goods['INSTALMENT']) > $instalment) {
  475. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  476. }
  477. if ($userStage == $instalment) {
  478. if ($goods['INSTALMENT'] != 1) {
  479. throw new Exception(Yii::t('app', 'canNotBuy'));
  480. }
  481. } else {
  482. if ($userInstalmentInfo) {
  483. if ($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE'] != 'FX') {
  484. throw new Exception(Yii::t('app', 'canNotBuy'));
  485. }
  486. }
  487. if ($userStage + 1 != $goods['INSTALMENT']) {
  488. throw new Exception(Yii::t('app', 'canNotBuy'));
  489. }
  490. if ($userStage + 1 > $instalment){
  491. throw new Exception(Yii::t('app', 'canNotBuy'));
  492. }
  493. }
  494. $hasInstalment = $goods['INSTALMENT'];
  495. }
  496. }
  497. }
  498. $sysConfig = Cache::getSystemConfig();
  499. $ampDivideLine = (int)$sysConfig['ampBVCondition']['VALUE'];
  500. if ($totalPv < $ampDivideLine) {
  501. throw new Exception(Yii::t('app', 'ampOrderSubStandard', ['ampBv' => $ampDivideLine]));
  502. }
  503. // 运费模板
  504. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  505. // 运费
  506. $freight = $freeTemplate['freight'] ?? 0;
  507. // 普通商品免运费阈值
  508. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  509. $this->_decAmount = $totalAmount;
  510. $this->_decPv = $totalPv;
  511. $this->_realPv = $totalRealPv;
  512. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  513. $this->_payAmount = $this->_decAmount + $this->_freight;
  514. $this->_decAmountStandard = $totalAmountStandard;
  515. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  516. $db = \Yii::$app->db;
  517. $transaction = $db->beginTransaction();
  518. try {
  519. //写入订单
  520. if (!$orderResult = $this->addOrder()) {
  521. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  522. }
  523. if ($hasInstalment){
  524. $instalmentModel = Instalment::findOne(['USER_ID' => $userId]);
  525. if(!$instalmentModel) {
  526. $instalmentModel = new Instalment();
  527. }
  528. $instalmentModel->USER_ID = $userId;
  529. $instalmentModel->STAGE = $hasInstalment;
  530. $instalmentModel->UPDATE_TIME = time();
  531. $instalmentModel->save();
  532. }
  533. $transaction->commit();
  534. return $orderResult;
  535. }catch (\Exception $e){
  536. $transaction->rollBack();
  537. $this->addError('add', $e->getMessage());
  538. return null;
  539. }
  540. }
  541. /**
  542. * 复销订单
  543. * @throws Exception
  544. */
  545. public function addOrder()
  546. {
  547. $periodObj = Period::instance();
  548. $nowPeriodNum = $periodObj->getNowPeriodNum();
  549. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  550. //帮复消会员Id(登陆会员)
  551. $loginUserId = \Yii::$app->user->id;
  552. $loginUserName = Info::getUserNameByUserId($loginUserId);
  553. //订单会员Id
  554. $userId = Info::getUserIdByUserName($this->userName);
  555. $countryId = Info::getUserCountryByUserId($userId);
  556. $email = Info::getEmailByUserId($this->userName);
  557. $country = Countries::getById($countryId);
  558. $warehouse = '01';
  559. $_hasPV = $this->_decPv;
  560. $ordNo = $this->_generateSn();
  561. $orderModel = new ApproachReconsumeOrder();
  562. $orderModel->SN = 'OS' . $ordNo;
  563. $orderModel->DEC_SN = 'DS' . $ordNo;
  564. $orderModel->ORDER_TYPE = $this->type;
  565. $orderModel->USER_ID = $userId;
  566. $orderModel->USER_NAME = $this->userName;
  567. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  568. $orderModel->PV = $_hasPV;
  569. $orderModel->PAY_AMOUNT = $this->_payAmount;
  570. $orderModel->PAY_PV = $_hasPV;
  571. $orderModel->PAY_AT = 0;
  572. $orderModel->PAY_TYPE = $this->payType;
  573. $orderModel->PERIOD_NUM = $nowPeriodNum;
  574. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  575. $orderModel->FREIGHT = $this->_freight;
  576. $orderModel->PAY_FREIGHT = $this->_freight;
  577. $orderModel->CONSIGNEE = $this->consignee;
  578. $orderModel->MOBILE = $this->acceptMobile;
  579. $orderModel->PROVINCE = $this->province[0];
  580. $orderModel->LGA_NAME = $this->lgaName;
  581. $orderModel->CITY_NAME = $this->cityName;
  582. $orderModel->ADDRESS = $this->detailaddress;
  583. $orderModel->FRONT_REMARK = $this->remark;
  584. $orderModel->WAREHOUSE = $warehouse;
  585. $orderModel->STATUS = Yii::$app->params['orderStatus']['notPaid']['value'];
  586. $orderModel->CREATED_AT = Date::nowTime();
  587. $orderModel->CREATE_USER = $loginUserName;
  588. $orderModel->EMAIL = $email ?? '';
  589. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  590. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  591. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  592. $orderModel->COUNTRY_ID = $countryId;
  593. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  594. $orderModel->DEC_USER_ID = $this->decUserName;
  595. $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
  596. if(!$orderModel->save()){
  597. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  598. }
  599. // 加入商品到订单商品表
  600. foreach($this->_orderGoods as $key=>$value) {
  601. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  602. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  603. }
  604. ApproachOrderGoods::batchInsert($this->_orderGoods);
  605. return $orderModel;
  606. }
  607. /**
  608. * 生成流水号
  609. * @return string
  610. */
  611. private function _generateSn() {
  612. return Date::today('Ymd') . $this->_random(10, 1);
  613. }
  614. /**
  615. * 生成随机数
  616. * @param $length
  617. * @param int $numeric
  618. * @return string
  619. */
  620. private function _random($length, $numeric = 0) {
  621. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  622. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  623. $hash = '';
  624. $max = strlen($seed) - 1;
  625. for ($i = 0; $i < $length; $i++) {
  626. $hash .= $seed[mt_rand(0, $max)];
  627. }
  628. return $hash;
  629. }
  630. private function orderAutoMaintenance($order)
  631. {
  632. $nowPeriodNum = Period::instance()->getNowPeriodNum();
  633. try {
  634. $sysConfig = Cache::getSystemConfig();
  635. $divideLine = (int)$sysConfig['monthPcsPvFxCondition']['VALUE'];
  636. $orderTotalBv = $order->PV;
  637. if ($orderTotalBv <= $divideLine) {
  638. return;
  639. }
  640. $lastAmpPeriod = AmpPeriod::find()
  641. ->where(['USER_ID' => $order->USER_ID])
  642. ->orderBy(['PERIOD_NUM' => SORT_DESC])
  643. ->one();
  644. $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
  645. if (!$lastAmpPeriod) {
  646. $memberOrderBv = Order::find()
  647. ->select('SUM(PV) AS total_pv')
  648. ->where([
  649. 'USER_ID' => $order->USER_ID,
  650. 'IS_DELETE' => 0,
  651. 'PERIOD_NUM' => $nowPeriodNum
  652. ])
  653. ->scalar();
  654. if ($memberOrderBv >= $divideLine) {
  655. $startPeriodNum = $nowPeriodNum + 1;
  656. }
  657. }
  658. $periodCount = floor($orderTotalBv / $divideLine);
  659. $remainderBv = $orderTotalBv % $divideLine;
  660. $ampPeriods = [];
  661. for ($i = 1; $i <= $periodCount; $i++) {
  662. $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
  663. $ampPeriods[] = [
  664. 'USER_ID' => $order->USER_ID,
  665. 'ORDER_SN' => $order->SN,
  666. 'PERIOD_NUM' => $startPeriodNum + $i - 1,
  667. 'BV' => $currentBv,
  668. ];
  669. }
  670. if (!empty($ampPeriods)) {
  671. AmpPeriod::batchInsert($ampPeriods);
  672. }
  673. } catch (\Exception $e) {
  674. // 记录日志或进行错误处理
  675. \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
  676. }
  677. }
  678. }