ApproachOrderForm.php 27 KB

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