ApproachReconsumeOrderForm.php 30 KB

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