ApproachReconsumeOrderForm.php 30 KB

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