ApproachReconsumeOrderForm.php 30 KB

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