ApproachReconsumeOrderForm.php 25 KB

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