ApproachReconsumeOrderForm.php 30 KB

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