ApproachReconsumeOrderForm.php 30 KB

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