ApproachReconsumeOrderForm.php 30 KB

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