ApproachReconsumeOrderForm.php 30 KB

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