ApproachReconsumeOrderForm.php 30 KB

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