OrderForm.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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\Countries;
  15. use common\models\CurrencyConversions;
  16. use common\models\DealType;
  17. use common\models\FreeTemplate;
  18. use common\models\Instalment;
  19. use common\models\Order;
  20. use common\models\OrderGoods;
  21. use common\models\Period;
  22. use common\models\ReceiveAddress;
  23. use common\models\Region;
  24. use common\models\ShopGoods;
  25. use common\models\ShopGoodsNature;
  26. use common\models\User;
  27. use common\models\UserNetwork;
  28. use common\models\RemainPv;
  29. use common\models\FlowRemainPv;
  30. use Yii;
  31. use yii\base\Exception;
  32. /**
  33. * Login form
  34. */
  35. class OrderForm extends Model
  36. {
  37. public $sn;
  38. public $expressCompany;
  39. public $orderTrackNo;
  40. public $status;
  41. public $remark;
  42. public $type;
  43. public $addressId;
  44. public $payType;
  45. public $goodsId;
  46. public $goodsNum;
  47. public $payPassword;
  48. public $email;
  49. public $exchangeRate;
  50. public $period;
  51. public $userName;
  52. public $decUserName;
  53. public $consignee;
  54. public $acceptMobile;
  55. public $province;
  56. public $city;
  57. public $lgaName;
  58. public $cityName;
  59. public $county;
  60. public $detailaddress;
  61. private $_address;
  62. private $_decAmount;
  63. private $_decPv;
  64. private $_freight;
  65. private $_payAmount;
  66. private $_orderGoods;
  67. private $_standardAmount;
  68. private $_decAmountStandard;
  69. private $_remainPv;
  70. private $_realPv;
  71. /**
  72. * @var Order
  73. */
  74. private $_model;
  75. public function init() {
  76. parent::init();
  77. $this->adminOperateLogger = new AdminOperate([
  78. 'fetchClass' => Order::class,
  79. ]);
  80. }
  81. /**
  82. * @inheritdoc
  83. */
  84. public function rules()
  85. {
  86. return [
  87. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province'/*,'city','county'*/,'cityName','lgaName','detailaddress','email'], 'trim'],
  88. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/], 'required'],
  89. [['status'], 'isStatus'],
  90. [['addressId'], 'isAddress'],
  91. [['payType'], 'isPayType'],
  92. [['payPassword'], 'validatePassword'],
  93. ];
  94. }
  95. public function attributeLabels()
  96. {
  97. return [
  98. 'sn' => Yii::t('app', 'orderSn'),
  99. 'expressCompany' => Yii::t('app', 'expressCompany'),
  100. 'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
  101. 'status' => Yii::t('app', 'state'),
  102. 'remark' => Yii::t('app', 'remark'),
  103. 'type' => Yii::t('app', 'orderType'),
  104. 'addressId' => Yii::t('app', 'shippingAddress'),
  105. 'payType' => Yii::t('app', 'payType'),
  106. 'goodsId' => Yii::t('app', 'productID'),
  107. 'goodsNum' => Yii::t('app', 'quantity'),
  108. 'userName' => Yii::t('app', 'repeatSalesMemberNo'),
  109. 'consignee' => Yii::t('app', 'consignee'),
  110. 'acceptMobile' => Yii::t('app', 'acceptMobile'),
  111. 'province' => Yii::t('app', 'province'),
  112. 'city' => Yii::t('app', 'city'),
  113. 'county' => Yii::t('app', 'county'),
  114. 'lgaName' =>Yii::t('app', 'lgaName'),
  115. 'cityName' => Yii::t('app', 'cityName'),
  116. 'detailaddress' => Yii::t('app', 'detailAddress'),
  117. 'email' => Yii::t('app', 'email'),
  118. ];
  119. }
  120. /**
  121. * 指定校验场景
  122. * @return array
  123. */
  124. public function scenarios()
  125. {
  126. $parentScenarios = parent::scenarios();
  127. $customScenarios = [
  128. // 管理员发货
  129. 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  130. // 会员确认收货
  131. 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  132. // 管理员修改订单状态
  133. 'adminStatus' => ['sn', 'status'],
  134. // 管理员修改备注
  135. 'adminRemark' => ['sn', 'remark'],
  136. // 会员下单
  137. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword', 'period'],
  138. // 帮会员复消下单
  139. 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress'],
  140. // 管理员退款
  141. 'adminRefund' => ['sn'],
  142. ];
  143. return array_merge($parentScenarios, $customScenarios);
  144. }
  145. /**
  146. * 校验之前
  147. * @return bool
  148. */
  149. public function beforeValidate()
  150. {
  151. $parentValidate = parent::beforeValidate();
  152. if ($this->sn) {
  153. $this->_model = Order::findOne(['SN'=>$this->sn]);
  154. if (!$this->_model){
  155. $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
  156. return false;
  157. }
  158. }
  159. if ($this->scenario == 'adminDelivery'){
  160. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
  161. $this->addError('sn', Yii::t('app', 'orderHasBeenCancelCanNotDeliver'));
  162. return false;
  163. }
  164. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  165. $this->addError('sn', Yii::t('app', 'orderHasBeenDeleteCanNotDeliver'));
  166. return false;
  167. }
  168. }
  169. if ($this->scenario == 'adminRefund'){
  170. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['paid']['value']) {
  171. $this->addError('sn', Yii::t('app', 'orderPayStatusDoesNotSupportRefund'));
  172. return false;
  173. }
  174. if ($this->_model['DELIVERY_STATUS'] != \Yii::$app->params['deliveryStatus']['notDelivery']['value']) {
  175. $this->addError('sn', Yii::t('app', 'orderLogisticsStatusDoesNotSupportRefund'));
  176. return false;
  177. }
  178. if ($this->_model['PAY_TYPE'] != 'pay_stack') {
  179. $this->addError('sn', Yii::t('app', 'orderPayTypeDoesNotSupportRefund'));
  180. return false;
  181. }
  182. if (!$this->_model['REMARK']) {
  183. $this->addError('sn', Yii::t('app', 'paymentInfoDoesNotExists'));
  184. return false;
  185. }
  186. }
  187. return $parentValidate;
  188. }
  189. /**
  190. * 校验支付密码
  191. * @param $attribute
  192. * @param $params
  193. */
  194. public function validatePassword($attribute, $params) {
  195. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  196. $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
  197. }
  198. }
  199. /**
  200. * 判断收货地址是否存在
  201. * @param $attribute
  202. */
  203. public function isAddress($attribute){
  204. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  205. $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
  206. } else {
  207. $this->_address = $receiveAddress;
  208. }
  209. }
  210. /**
  211. * 判断支付方式
  212. * @param $attribute
  213. * @throws Exception
  214. */
  215. public function isPayType($attribute){
  216. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  217. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  218. return;
  219. }
  220. // 一个订单只能包含一类商品
  221. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  222. if (!$goods) {
  223. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  224. return;
  225. }
  226. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  227. if (count($goodsCategoryType) > 1) {
  228. $this->addError($attribute, Yii::t('app', 'orderCanNotHasMoreClassification'));
  229. return;
  230. }
  231. // 购买方式
  232. $sellTypeLabelMap = array_column(ShopGoods::getSaleType(), NULL, 'label');
  233. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  234. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  235. return;
  236. }
  237. // 所选支付方式必须是商品分类支持的类型
  238. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  239. // 商品类型
  240. $currCategoryType = $goodsCategoryType[0];
  241. if (!array_key_exists($currCategoryType, $categoryType)) {
  242. $this->addError($attribute, Yii::t('app', 'shopGoodClassificationError'));
  243. return;
  244. }
  245. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  246. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  247. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  248. return;
  249. }
  250. }
  251. /**
  252. * 校验类型
  253. * @param $attribute
  254. */
  255. public function isStatus($attribute){
  256. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  257. $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
  258. return ;
  259. }
  260. if ($this->scenario == 'adminStatus'){
  261. if ($this->status == $this->_model['STATUS']) {
  262. $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
  263. return ;
  264. }
  265. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  266. $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
  267. return ;
  268. }
  269. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  270. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  271. return ;
  272. }
  273. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  274. $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
  275. return ;
  276. }
  277. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  278. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  279. return ;
  280. }
  281. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  282. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  283. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
  284. return ;
  285. }
  286. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  287. $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
  288. return ;
  289. }
  290. }
  291. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  292. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  293. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
  294. return ;
  295. }
  296. }
  297. }
  298. }
  299. /**
  300. * 管理员发货
  301. * @return Order|null
  302. * @throws \yii\db\Exception
  303. */
  304. public function adminDelivery(){
  305. if(!$this->validate()){
  306. return null;
  307. }
  308. $db = \Yii::$app->db;
  309. $transaction = $db->beginTransaction();
  310. try {
  311. $period = Period::instance();
  312. $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value'];
  313. $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum();
  314. $this->_model->DELIVERY_AT = Date::nowTime();
  315. $this->_model->EXPRESS_COMPANY = $this->expressCompany;
  316. $this->_model->ORDER_TRACK_NO = $this->orderTrackNo;
  317. $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value'];
  318. if(!$this->_model->save()){
  319. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  320. }
  321. $transaction->commit();
  322. } catch (Exception $e) {
  323. $transaction->rollBack();
  324. $this->addError('edit', $e->getMessage());
  325. return null;
  326. }
  327. return $this->_model;
  328. }
  329. /**
  330. * 校验支付
  331. * @return Order|null
  332. * @throws Exception
  333. */
  334. public function verifyPayStack(): ?Order
  335. {
  336. if(!$this->validate()){
  337. return null;
  338. }
  339. // 调用PayStack支付校验
  340. $payload = PayStack::transactionVerify($this->remark['reference']);
  341. if ($payload['status'] !== true) {
  342. throw new Exception(Form::formatErrorsForApi($payload['message']));
  343. }
  344. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  345. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'payAmountNotEqualOrderAmount')));
  346. }
  347. $db = \Yii::$app->db;
  348. $transaction = $db->beginTransaction();
  349. try {
  350. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  351. $this->_model->REMARK = json_encode($this->remark);
  352. $this->_model->PAY_AT = Date::nowTime();
  353. if (!$this->_model->save()) {
  354. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  355. }
  356. $transaction->commit();
  357. } catch (Exception $e) {
  358. $transaction->rollBack();
  359. $this->addError('edit', $e->getMessage());
  360. return null;
  361. }
  362. return $this->_model;
  363. }
  364. /**
  365. * 订单退款
  366. * @return Order|null
  367. * @throws Exception
  368. */
  369. public function adminRefund()
  370. {
  371. if(!$this->validate()){
  372. return null;
  373. }
  374. // 支付信息存在于remark中
  375. $remark = $this->_model->REMARK ? json_decode($this->_model->REMARK, true) : [];
  376. $reference = $remark['reference'] ?? '';
  377. if (!$reference) {
  378. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'paymentInfoDoesNotExists')));
  379. }
  380. // 退款金额. 订单支付金额 * 100
  381. $amount = $this->_model->PAY_AMOUNT * 100;
  382. // 调用PayStack支付校验
  383. $payload = PayStack::transactionRefund($reference, $amount);
  384. if ($payload['status'] !== true) {
  385. throw new Exception(Form::formatErrorsForApi($payload['message']));
  386. }
  387. $db = \Yii::$app->db;
  388. $transaction = $db->beginTransaction();
  389. try {
  390. $this->_model->STATUS = \Yii::$app->params['orderStatus']['refund']['value'];
  391. $this->_model->REMARK = json_encode([
  392. 'payment' => $remark,
  393. 'refund' => $payload['data']
  394. ]
  395. );
  396. if (!$this->_model->save()) {
  397. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  398. }
  399. $transaction->commit();
  400. } catch (Exception $e) {
  401. $transaction->rollBack();
  402. $this->addError('edit', $e->getMessage());
  403. return null;
  404. }
  405. return $this->_model;
  406. }
  407. /**
  408. * BV分期
  409. *
  410. *
  411. */
  412. private function _pvSplit($oPv){
  413. $sysConfig = Cache::getSystemConfig();
  414. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  415. if($oPv>$mesureUpCondition){
  416. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  417. $remainPv = $oPv - $currentPv;
  418. }else{
  419. $currentPv = $oPv;
  420. $remainPv = 0;
  421. }
  422. return [
  423. 'current' => $currentPv,
  424. 'remain' => $remainPv
  425. ];
  426. }
  427. /**
  428. * 复销
  429. * @throws Exception
  430. * @throws \yii\db\Exception
  431. */
  432. public function add(){
  433. if(!$this->validate()){
  434. return null;
  435. }
  436. $ids = $this->goodsId;
  437. $totalAmount = 0;
  438. $totalPv = 0;
  439. $totalRealPv = 0;
  440. $totalAmountStandard = 0;
  441. $goodsType = ShopGoods::getGoodType();
  442. $this->_remainPv = 0;
  443. $hasInstalment = 0;
  444. $loginUserId = \Yii::$app->user->id;
  445. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  446. foreach ($this->goodsNum as $k => $v) {
  447. if ($v) {
  448. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  449. if (!$goods) {
  450. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  451. }
  452. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  453. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  454. if (!$goodsNature) {
  455. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  456. }
  457. // 汇率
  458. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  459. if($goods['STORE_NUMS']>0){
  460. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  461. $discount = $goodsType[$goods['TYPE']]['discount'];
  462. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  463. $realPv = $goods['PRICE_PV'] * $discount/100;
  464. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  465. } else {
  466. $discount = $goods['SELL_DISCOUNT'];
  467. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  468. $realPv = $goods['PRICE_PV'] * $discount;
  469. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  470. }
  471. if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
  472. $pvSplit = $this->_pvSplit($realPv);
  473. $currentPv = $pvSplit['current'];
  474. $remainPv = $pvSplit['remain'];
  475. $totalPv += $currentPv * intval($v);
  476. $totalRealPv += $realPv * intval($v);
  477. $this->_remainPv += $remainPv * intval($v);
  478. }else{
  479. $currentPv = $goods['PRICE_PV'];
  480. $totalPv += $realPv * intval($v);
  481. $totalRealPv += $realPv * intval($v);
  482. $remainPv = 0;
  483. $this->_remainPv += 0;
  484. }
  485. $totalAmount += $realPrice * intval($v);
  486. $totalAmountStandard += $realPriceStandard * intval($v);
  487. // if($this->payType=='cash') {
  488. // $discount = $goodsType[$goods['TYPE']]['discount'];
  489. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  490. // $realPv = $goods['PRICE_PV'] * $discount/100;
  491. // $totalAmount += $realPrice * intval($v);
  492. // $totalPv += $realPv * intval($v);
  493. // }else{
  494. // $realPrice = $goods['SELL_PRICE'];
  495. // $realPv = $goods['PRICE_PV'];
  496. // $totalAmount += $realPrice * intval($v);
  497. // $totalPv += $realPv * intval($v);
  498. // }
  499. $this->_orderGoods[] = [
  500. 'GOODS_ID' => $goods['ID'],
  501. 'PRICE' => $goodsNature['SELL_PRICE'],
  502. 'PV' => $currentPv, // $goods['PRICE_PV'],
  503. 'REAL_PRICE' => $realPrice,
  504. 'REAL_PV' => $realPv,
  505. 'REMAIN_PV' => $remainPv,
  506. 'POINT' => $goods['POINT'],
  507. 'BUY_NUMS' => intval($v),
  508. 'SKU_CODE' => $goods['GOODS_NO'],
  509. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  510. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  511. 'PAY_TYPE' => $this->payType,
  512. 'EMAIL' => $this->email,
  513. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  514. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  515. 'EXCHANGE_RATE' => $this->exchangeRate,
  516. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  517. ];
  518. }
  519. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  520. if($v>1){ // 不可以购买多个
  521. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  522. }
  523. $userStage = Instalment::getStage($loginUserId);
  524. $userInstalmentInfo = Instalment::getInfo($loginUserId);
  525. // 分期的总期数
  526. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  527. // 分期商品的期数不能大于总分期数限制
  528. if (intval($goods['INSTALMENT']) > $instalment) {
  529. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  530. }
  531. if ($userStage != $instalment){
  532. if ($userInstalmentInfo){
  533. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  534. throw new Exception(Yii::t('app', 'canNotBuy'));
  535. }
  536. }
  537. if ($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  538. throw new Exception(Yii::t('app', 'canNotBuy'));
  539. }
  540. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  541. throw new Exception(Yii::t('app', 'canNotBuy'));
  542. }
  543. } else {
  544. if ($goods['INSTALMENT'] != 1) {
  545. throw new Exception(Yii::t('app', 'canNotBuy'));
  546. }
  547. }
  548. $hasInstalment = $goods['INSTALMENT'];
  549. }
  550. }
  551. }
  552. // 运费模板
  553. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  554. // 运费
  555. $freight = $freeTemplate['freight'] ?? 0;
  556. // 普通商品免运费阈值
  557. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  558. $this->_decAmount = $totalAmount;
  559. $this->_decPv = $totalPv;
  560. $this->_realPv = $totalRealPv;
  561. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  562. if($this->_address['PROVINCE']==1){
  563. $this->_freight = 0;
  564. }
  565. $this->_payAmount = $this->_decAmount + $this->_freight;
  566. $this->_decAmountStandard = $totalAmountStandard;
  567. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  568. $db = \Yii::$app->db;
  569. $transaction = $db->beginTransaction();
  570. try {
  571. //判断用户余额是否充足
  572. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  573. if ($result['code'] !== 200) {
  574. throw new Exception($result['message']);
  575. }
  576. /**
  577. * 2022-04-28
  578. * York
  579. * 支付后减少库存
  580. */
  581. foreach ($this->goodsNum as $k => $v){
  582. if ($v){
  583. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  584. if (!$goods) {
  585. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  586. }
  587. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  588. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  589. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  590. $data->STORE_NUMS = $goods_store_nums;
  591. $data->update();
  592. //下单后库存小于等于0 商品下架
  593. if($goods_store_nums <= 0){
  594. $data->STATUS = 0;
  595. $data->UPDATED_AT = Date::nowTime();
  596. $data->update();
  597. }
  598. }else{
  599. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  600. }
  601. }
  602. }
  603. //写入订单
  604. if (!$orderResult = $this->addOrder()) {
  605. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  606. }
  607. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  608. $instalmentModel = Instalment::findOne(['USER_ID'=>$loginUserId]);
  609. if(!$instalmentModel) {
  610. $instalmentModel = new Instalment();
  611. }
  612. $instalmentModel->USER_ID = $loginUserId;
  613. $instalmentModel->STAGE = $hasInstalment;
  614. $instalmentModel->ORDER_TYPE = 'FX';
  615. $instalmentModel->UPDATE_TIME = time();
  616. $instalmentModel->save();
  617. }
  618. $transaction->commit();
  619. return $orderResult;
  620. }catch (\Exception $e){
  621. $transaction->rollBack();
  622. $this->addError('add', $e->getMessage());
  623. return null;
  624. }
  625. }
  626. /**
  627. * 判断对应账户余额是否充足.
  628. * @param $payType string 支付方式.
  629. * @param $payAmount numeric 支付金额
  630. * @return array|int[]
  631. */
  632. public function getBalanceAdequate(string $payType, $payAmount): array
  633. {
  634. $loginUserId = \Yii::$app->user->id;
  635. if ($payType == 'cash') {
  636. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  637. return ['code' => 500, 'message' => Yii::t('app', 'cashDoesNotAdequate')];
  638. }
  639. } else if ($payType =='exchange') {
  640. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  641. return ['code' => 500, 'message' => Yii::t('app', 'exchangePointDoesNotAdequate')];
  642. }
  643. } else if ($payType == 'tourism_points') {
  644. if ($payAmount > Balance::getBalanceTourism($loginUserId)) {
  645. return ['code' => 500, 'message' => Yii::t('app', 'travelPointDoesNotAdequate')];
  646. }
  647. } else if ($payType == 'garage_points') {
  648. if ($payAmount > Balance::getBalanceGarage($loginUserId)) {
  649. return ['code' => 500, 'message' => Yii::t('app', 'carFundPointDoesNotAdequate')];
  650. }
  651. // } else{
  652. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  653. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  654. // }
  655. }
  656. return ['code' => 200];
  657. }
  658. /**
  659. * 复销订单
  660. * @throws Exception
  661. */
  662. public function addOrder(){
  663. $periodObj = Period::instance();
  664. $nowPeriodNum = $this->period ?: $periodObj->getNowPeriodNum();
  665. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  666. $userId = \Yii::$app->user->id;
  667. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  668. $userName = Info::getUserNameByUserId($userId);
  669. $userRealName = Info::getUserRealNameByUserId($userId);
  670. $userMobile = Info::getUserMobileByUserId($userId);
  671. $userEmail = Info::getUserEmailByUserId($userId);
  672. $country = Countries::getById($user['COUNTRY_ID']);
  673. // 加入订单信息
  674. if ($this->_address['PROVINCE'] != 1) {
  675. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  676. if (!$warehouse) {
  677. throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  678. }
  679. }else{
  680. $warehouse = '01';
  681. }
  682. $_hasPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_decPv;
  683. $_hasRealPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_realPv;
  684. $ordNo = $this->_generateSn();
  685. $orderModel = new Order();
  686. $orderModel->SN = 'OS'.$ordNo;
  687. $orderModel->DEC_SN = 'DS'.$ordNo;
  688. $orderModel->ORDER_TYPE = $this->type;
  689. $orderModel->USER_ID = $userId;
  690. $orderModel->USER_NAME = $userName;
  691. $orderModel->DEC_USER_ID = $this->decUserName;;
  692. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  693. $orderModel->PV = $_hasPV;
  694. $orderModel->PAY_AMOUNT = $this->_payAmount;
  695. $orderModel->PAY_PV = $_hasRealPV; // 兑换积分不能算业绩
  696. $orderModel->REMAIN_PV = $this->_remainPv;
  697. $orderModel->PAY_AT = Date::nowTime();
  698. $orderModel->PAY_TYPE = $this->payType;
  699. $orderModel->PERIOD_NUM = $nowPeriodNum;
  700. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  701. $orderModel->FREIGHT = $this->_freight;
  702. $orderModel->PAY_FREIGHT = $this->_freight;
  703. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  704. $orderModel->MOBILE = $this->_address['MOBILE'];
  705. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  706. // $orderModel->CITY = $this->_address['CITY'];
  707. // $orderModel->COUNTY = $this->_address['COUNTY'];
  708. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  709. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  710. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  711. $orderModel->FRONT_REMARK = $this->remark;
  712. $orderModel->WAREHOUSE = $warehouse;
  713. $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  714. $orderModel->CREATED_AT = Date::nowTime();
  715. $orderModel->CREATE_USER = $userName;
  716. $orderModel->EMAIL = $userEmail ?? '';
  717. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  718. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  719. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  720. $orderModel->COUNTRY_ID = $user['COUNTRY_ID'];
  721. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  722. if($this->_address['PROVINCE']==1){
  723. $orderModel->EXPRESS_TYPE = 1;
  724. $orderModel->CONSIGNEE = $userRealName;
  725. $orderModel->MOBILE = $userMobile;
  726. $orderModel->PROVINCE = 1;
  727. $orderModel->CITY = 1;
  728. $orderModel->COUNTY = 1;
  729. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  730. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  731. $orderModel->ADDRESS = 'Self Pick-up';
  732. }
  733. if(!$orderModel->save()){
  734. $this->addErrors($orderModel->getErrors());
  735. return false;
  736. }
  737. // 加入商品到订单商品表
  738. foreach($this->_orderGoods as $key=>$value){
  739. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  740. if (in_array($orderModel->PAY_TYPE, ['exchange', 'tourism_points', 'garage_points'])) {
  741. $this->_orderGoods[$key]['REAL_PV'] = 0;
  742. }
  743. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  744. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  745. }
  746. OrderGoods::batchInsert($this->_orderGoods);
  747. //扣除会员余额/积分
  748. if($this->payType=='cash') {
  749. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment', 'ORDER_SN' => $orderModel->SN]); // 会员复销余额支付
  750. } else if ($this->payType=='exchange') {
  751. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换', 'ORDER_SN' => $orderModel->SN]);
  752. } else if ($this->payType == 'tourism_points') {
  753. Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换', 'ORDER_SN' => $orderModel->SN]);
  754. } else if ($this->payType == 'garage_points') {
  755. Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换', 'ORDER_SN' => $orderModel->SN]);
  756. } else if ($this->payType == 'villa_points') {
  757. Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换', 'ORDER_SN' => $orderModel->SN]);
  758. } else if ($this->payType == 'reconsume_points') {
  759. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换', 'ORDER_SN' => $orderModel->SN]);
  760. }
  761. return $orderModel;
  762. }
  763. /**
  764. * 帮会员复销
  765. * @return bool|null
  766. * @throws Exception
  767. * @throws \yii\db\Exception
  768. */
  769. public function reconsumeAdd(){
  770. if(!$this->validate()){
  771. return null;
  772. }
  773. $ids = $this->goodsId;
  774. $totalAmount = 0;
  775. $totalPv = 0;
  776. $totalRealPv = 0;
  777. $totalAmountStandard = 0;
  778. $goodsType = ShopGoods::getGoodType();
  779. $hasInstalment = 0;
  780. $userId = Info::getUserIdByUserName($this->userName);
  781. $user = User::getEnCodeInfo($userId);
  782. // 报单中心汇率
  783. $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
  784. $decCountry = Countries::getById($decCountryId);
  785. $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
  786. // 会员汇率
  787. $country = Countries::getById($user['COUNTRY_ID']);
  788. $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
  789. foreach ($this->goodsNum as $k => $v) {
  790. if ($v) {
  791. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  792. if (!$goods) {
  793. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  794. }
  795. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  796. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  797. if (!$goodsNature) {
  798. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  799. }
  800. if($goods['STORE_NUMS']>0){
  801. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  802. $discount = $goodsType[$goods['TYPE']]['discount'];
  803. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  804. $realPv = $goods['PRICE_PV'] * $discount/100;
  805. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  806. } else {
  807. $discount = $goods['SELL_DISCOUNT'];
  808. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  809. $realPv = $goods['PRICE_PV'] * $discount;
  810. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  811. }
  812. if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
  813. $pvSplit = $this->_pvSplit($realPv);
  814. $currentPv = $pvSplit['current'];
  815. $remainPv = $pvSplit['remain'];
  816. $totalPv += $currentPv * intval($v);
  817. $totalRealPv += $realPv * intval($v);
  818. $this->_remainPv += $remainPv * intval($v);
  819. }else{
  820. $currentPv = $goods['PRICE_PV'];
  821. $totalPv += $realPv * intval($v);
  822. $totalRealPv += $realPv * intval($v);
  823. $remainPv = 0;
  824. $this->_remainPv += 0;
  825. }
  826. $totalAmount += $realPrice * intval($v);
  827. $totalAmountStandard += $realPriceStandard * intval($v);
  828. $this->_orderGoods[] = [
  829. 'GOODS_ID' => $goods['ID'],
  830. 'PRICE' => $goodsNature['SELL_PRICE'],
  831. 'PV' => $currentPv, // $goods['PRICE_PV'],
  832. 'REAL_PRICE' => $realPrice,
  833. 'REAL_PV' => $realPv,
  834. 'REMAIN_PV' => $remainPv,
  835. 'POINT' => $goods['POINT'],
  836. 'BUY_NUMS' => intval($v),
  837. 'SKU_CODE' => $goods['GOODS_NO'],
  838. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  839. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  840. 'PAY_TYPE' => $this->payType,
  841. 'EMAIL' => $this->email,
  842. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  843. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  844. 'EXCHANGE_RATE' => $currencyRate,
  845. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  846. ];
  847. }
  848. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  849. if($v>1){ // 不可以购买多个
  850. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  851. }
  852. $userStage = Instalment::getStage($userId);
  853. $userInstalmentInfo = Instalment::getInfo($userId);
  854. // 分期的总期数
  855. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  856. // 分期商品的期数不能大于总分期数限制
  857. if (intval($goods['INSTALMENT']) > $instalment) {
  858. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  859. }
  860. if ($userStage == $instalment){
  861. if ($goods['INSTALMENT'] != 1) {
  862. throw new Exception(Yii::t('app', 'canNotBuy'));
  863. }
  864. }else{
  865. if($userInstalmentInfo){
  866. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  867. throw new Exception(Yii::t('app', 'canNotBuy'));
  868. }
  869. }
  870. if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  871. throw new Exception(Yii::t('app', 'canNotBuy'));
  872. }
  873. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  874. throw new Exception(Yii::t('app', 'canNotBuy'));
  875. }
  876. }
  877. $hasInstalment = $goods['INSTALMENT'];
  878. }
  879. }
  880. }
  881. // 运费模板
  882. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  883. // 运费
  884. $freight = $freeTemplate['freight'] ?? 0;
  885. // 普通商品免运费阈值
  886. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  887. $this->_decAmount = $totalAmount;
  888. $this->_decPv = $totalPv;
  889. $this->_realPv = $totalRealPv;
  890. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  891. $this->_payAmount = $this->_decAmount + $this->_freight;
  892. $this->_decAmountStandard = $totalAmountStandard;
  893. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  894. $db = \Yii::$app->db;
  895. $transaction = $db->beginTransaction();
  896. try {
  897. $loginUserId = \Yii::$app->user->id;
  898. //是否开启伞下会员限制
  899. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  900. if($isResaleUmbrella){
  901. $userId = Info::getUserIdByUserName($this->userName);
  902. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  903. if(!$userNetwork){
  904. throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
  905. }
  906. }
  907. //看现金余额是否充足
  908. $decCash = Cash::getAvailableBalance($loginUserId);
  909. // 转换后的余额
  910. $localCash = Tool::convertAmount($decCash, $decUserCurrencyRate, $currencyRate);
  911. if ($localCash < $this->_decAmount){
  912. throw new Exception(Yii::t('app', 'applicantCashShort'), 400);
  913. }
  914. foreach ($this->goodsNum as $k => $v){
  915. if ($v){
  916. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  917. if (!$goods) {
  918. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  919. }
  920. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  921. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  922. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  923. $data->STORE_NUMS = $goods_store_nums;
  924. $data->update();
  925. //下单后库存小于等于0 商品下架
  926. if($goods_store_nums <= 0){
  927. $data->STATUS = 0;
  928. $data->UPDATED_AT = Date::nowTime();
  929. $data->update();
  930. }
  931. }else{
  932. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  933. }
  934. }
  935. }
  936. //写入订单
  937. if (!$orderResult = $this->addUserOrder()) {
  938. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  939. }
  940. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  941. $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
  942. if(!$instalmentModel) {
  943. $instalmentModel = new Instalment();
  944. }
  945. $instalmentModel->USER_ID = $userId;
  946. $instalmentModel->STAGE = $hasInstalment;
  947. $instalmentModel->ORDER_TYPE = 'FX';
  948. $instalmentModel->UPDATE_TIME = time();
  949. $instalmentModel->save();
  950. }
  951. $transaction->commit();
  952. }catch (\Exception $e){
  953. $transaction->rollBack();
  954. $this->addError('add', $e->getMessage());
  955. return null;
  956. }
  957. return true;
  958. }
  959. /**
  960. * 帮会员复消的订单
  961. */
  962. public function addUserOrder(){
  963. $periodObj = Period::instance();
  964. $nowPeriodNum = $periodObj->getNowPeriodNum();
  965. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  966. //帮复消会员Id(登陆会员)
  967. $loginUserId = \Yii::$app->user->id;
  968. $loginUserName = Info::getUserNameByUserId($loginUserId);
  969. //订单会员Id
  970. $userId = Info::getUserIdByUserName($this->userName);
  971. $countryId = Info::getUserCountryByUserId($userId);
  972. $email = Info::getEmailByUserId($this->userName);
  973. $country = Countries::getById($countryId);
  974. // 加入订单信息
  975. // if($this->province!=1){
  976. // $warehouse = Region::getWarehouseByCode($this->province);//仓库
  977. // if(!$warehouse){
  978. // throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  979. // }
  980. // }else{
  981. $warehouse = '01';
  982. // }
  983. $ordNo = $this->_generateSn();
  984. $orderModel = new Order();
  985. $orderModel->SN = 'OS'.$ordNo;
  986. $orderModel->DEC_SN = 'DS'.$ordNo;
  987. $orderModel->ORDER_TYPE = $this->type;
  988. $orderModel->ORDER_CATEGORY = 'STUDIO';
  989. $orderModel->USER_ID = $userId;
  990. $orderModel->USER_NAME = $this->userName;
  991. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  992. $orderModel->PV = $this->_decPv;
  993. $orderModel->PAY_AMOUNT = $this->_payAmount;
  994. $orderModel->PAY_PV = $this->_decPv;
  995. $orderModel->PAY_AT = Date::nowTime();
  996. $orderModel->PAY_TYPE = $this->payType;
  997. $orderModel->PERIOD_NUM = $nowPeriodNum;
  998. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  999. $orderModel->FREIGHT = $this->_freight;
  1000. $orderModel->PAY_FREIGHT = $this->_freight;
  1001. $orderModel->CONSIGNEE = $this->consignee;
  1002. $orderModel->MOBILE = $this->acceptMobile;
  1003. $orderModel->PROVINCE = $this->province[0];
  1004. $orderModel->LGA_NAME = $this->lgaName;
  1005. $orderModel->CITY_NAME = $this->cityName;
  1006. $orderModel->ADDRESS = $this->detailaddress;
  1007. $orderModel->FRONT_REMARK = $this->remark;
  1008. $orderModel->WAREHOUSE = $warehouse;
  1009. $orderModel->STATUS = 1;
  1010. $orderModel->CREATED_AT = Date::nowTime();
  1011. $orderModel->CREATE_USER = $loginUserName;
  1012. $orderModel->EMAIL = $email ?? '';
  1013. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  1014. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  1015. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  1016. $orderModel->COUNTRY_ID = $countryId;
  1017. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  1018. if(!$orderModel->save()){
  1019. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  1020. }
  1021. // 加入商品到订单商品表
  1022. foreach($this->_orderGoods as $key=>$value){
  1023. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  1024. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  1025. }
  1026. OrderGoods::batchInsert($this->_orderGoods);
  1027. //扣除会员余额/积分
  1028. if($this->payType=='cash') {
  1029. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => Yii::t('app', 'membersResellingBalancePayment')]);
  1030. }else{
  1031. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => Yii::t('app', 'membersExchangePointPayment')]);
  1032. }
  1033. return $orderModel;
  1034. }
  1035. /**
  1036. * 生成流水号
  1037. * @return string
  1038. */
  1039. private function _generateSn() {
  1040. return Date::today('Ymd') . $this->_random(10, 1);
  1041. }
  1042. /**
  1043. * 生成随机数
  1044. * @param $length
  1045. * @param int $numeric
  1046. * @return string
  1047. */
  1048. private function _random($length, $numeric = 0) {
  1049. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  1050. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  1051. $hash = '';
  1052. $max = strlen($seed) - 1;
  1053. for ($i = 0; $i < $length; $i++) {
  1054. $hash .= $seed[mt_rand(0, $max)];
  1055. }
  1056. return $hash;
  1057. }
  1058. public function addFakeOrder($userId, $periodNum){
  1059. $userName = Info::getUserNameByUserId($userId);
  1060. $sysConfig = Cache::getSystemConfig();
  1061. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  1062. $ordNo = $this->_generateSn();
  1063. $orderModel = new Order();
  1064. $orderModel->SN = 'OS'.$ordNo;
  1065. $orderModel->DEC_SN = 'DS'.$ordNo;
  1066. $orderModel->USER_ID = $userId;
  1067. $orderModel->USER_NAME = $userName;
  1068. $orderModel->PERIOD_NUM = $periodNum;
  1069. $orderModel->CREATE_USER = 'AUTO';
  1070. $orderModel->ORDER_TYPE = 'FX';
  1071. $orderModel->STATUS = 1;
  1072. $orderModel->PV = $mesureUpCondition;
  1073. $orderModel->PAY_PV = $mesureUpCondition;
  1074. $orderModel->P_CALC_MONTH = '1970-01-01';
  1075. $orderModel->CREATED_AT = Date::nowTime();
  1076. $orderModel->EXPRESS_TYPE = 1;
  1077. $orderModel->IS_AUTO = 1;
  1078. if(!$orderModel->save()){
  1079. $this->addErrors($orderModel->getErrors());
  1080. return false;
  1081. }
  1082. return $orderModel;
  1083. }
  1084. }