ApproachOrderForm.php 29 KB

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