ApproachReconsumeOrderForm.php 30 KB

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