ApproachReconsumeOrderForm.php 30 KB

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