OrderForm.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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\PayStack;
  8. use common\helpers\user\Balance;
  9. use common\helpers\user\Cash;
  10. use common\helpers\user\Info;
  11. use common\libs\logging\operate\AdminOperate;
  12. use common\models\DealType;
  13. use common\models\Order;
  14. use common\models\OrderGoods;
  15. use common\models\Period;
  16. use common\models\ReceiveAddress;
  17. use common\models\Region;
  18. use common\models\ShopGoods;
  19. use common\models\User;
  20. use common\models\UserNetwork;
  21. use yii\base\Exception;
  22. /**
  23. * Login form
  24. */
  25. class OrderForm extends Model
  26. {
  27. public $sn;
  28. public $expressCompany;
  29. public $orderTrackNo;
  30. public $status;
  31. public $remark;
  32. public $type;
  33. public $addressId;
  34. public $payType;
  35. public $goodsId;
  36. public $goodsNum;
  37. public $payPassword;
  38. public $email;
  39. public $userName;
  40. public $consignee;
  41. public $acceptMobile;
  42. public $province;
  43. public $city;
  44. public $county;
  45. public $detailaddress;
  46. private $_address;
  47. private $_decAmount;
  48. private $_decPv;
  49. private $_freight;
  50. private $_payAmount;
  51. private $_orderGoods;
  52. private $_standardAmount;
  53. private $_decAmountStandard;
  54. private $_exchangeRate;
  55. /**
  56. * @var Order
  57. */
  58. private $_model;
  59. public function init() {
  60. parent::init();
  61. $this->adminOperateLogger = new AdminOperate([
  62. 'fetchClass' => Order::class,
  63. ]);
  64. }
  65. /**
  66. * @inheritdoc
  67. */
  68. public function rules()
  69. {
  70. return [
  71. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress','email'], 'trim'],
  72. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/], 'required'],
  73. [['status'], 'isStatus'],
  74. [['addressId'], 'isAddress'],
  75. [['payType'], 'isPayType'],
  76. [['payPassword'], 'validatePassword'],
  77. ];
  78. }
  79. public function attributeLabels()
  80. {
  81. return [
  82. 'sn' => '订单号',
  83. 'expressCompany' => '快递公司',
  84. 'orderTrackNo' => '快递单号',
  85. 'status' => '状态',
  86. 'remark' => '备注',
  87. 'type' => '订单类型',
  88. 'addressId' => '收货地址',
  89. 'payType' => '支付方式',
  90. 'goodsId' => '商品ID',
  91. 'goodsNum' => '商品数量',
  92. 'userName' => '复消会员编号',
  93. 'consignee' => '收货人',
  94. 'acceptMobile' => '收货电话',
  95. 'province' => '省',
  96. 'city' => '市',
  97. 'county' => '区',
  98. 'detailaddress' => '收货详细地址',
  99. 'email' => 'Email',
  100. ];
  101. }
  102. /**
  103. * 指定校验场景
  104. * @return array
  105. */
  106. public function scenarios()
  107. {
  108. $parentScenarios = parent::scenarios();
  109. $customScenarios = [
  110. // 管理员发货
  111. 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  112. // 会员确认收货
  113. 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  114. // 管理员修改订单状态
  115. 'adminStatus' => ['sn', 'status'],
  116. // 管理员修改备注
  117. 'adminRemark' => ['sn', 'remark'],
  118. // 会员下单
  119. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword', /*'email'*/],
  120. // 帮会员复消下单
  121. 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'],
  122. // 管理员修改订单状态
  123. 'verifyPayStack' => ['sn', 'remark'],
  124. // 管理员退款
  125. 'adminRefund' => ['sn'],
  126. ];
  127. return array_merge($parentScenarios, $customScenarios);
  128. }
  129. /**
  130. * 校验之前
  131. * @return bool
  132. */
  133. public function beforeValidate()
  134. {
  135. $parentValidate = parent::beforeValidate();
  136. if ($this->sn) {
  137. $this->_model = Order::findOne(['SN'=>$this->sn]);
  138. if (!$this->_model){
  139. $this->addError('sn', '订单不存在');
  140. return false;
  141. }
  142. }
  143. if ($this->scenario == 'adminDelivery'){
  144. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
  145. $this->addError('sn', '订单已取消不能发货');
  146. return false;
  147. }
  148. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  149. $this->addError('sn', '订单已删除不能发货');
  150. return false;
  151. }
  152. }
  153. if ($this->scenario == 'verifyPayStack'){
  154. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  155. $this->addError('sn', '订单状态非未支付');
  156. return false;
  157. }
  158. }
  159. if ($this->scenario == 'adminRefund'){
  160. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['paid']['value']) {
  161. $this->addError('sn', '订单状态支付状态不支持退款');
  162. return false;
  163. }
  164. if ($this->_model['DELIVERY_STATUS'] != \Yii::$app->params['deliveryStatus']['notDelivery']['value']) {
  165. $this->addError('sn', '订单物流状态不支持退款');
  166. return false;
  167. }
  168. if ($this->_model['PAY_TYPE'] != 'pay_stack') {
  169. $this->addError('sn', '订单支付方式不支持退款');
  170. return false;
  171. }
  172. if (!$this->_model['REMARK']) {
  173. $this->addError('sn', '订单支付信息不存在');
  174. return false;
  175. }
  176. }
  177. return $parentValidate;
  178. }
  179. /**
  180. * 校验支付密码
  181. * @param $attribute
  182. * @param $params
  183. */
  184. public function validatePassword($attribute, $params) {
  185. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  186. $this->addError($attribute, 'The payment password is incorrect');//支付密码不正确
  187. }
  188. }
  189. /**
  190. * 判断收货地址是否存在
  191. * @param $attribute
  192. */
  193. public function isAddress($attribute){
  194. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  195. $this->addError($attribute, '收货地址不存在');
  196. } else {
  197. $this->_address = $receiveAddress;
  198. }
  199. }
  200. /**
  201. * 判断支付方式
  202. * @param $attribute
  203. */
  204. public function isPayType($attribute){
  205. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  206. $this->addError($attribute, '支付方式错误1');
  207. return;
  208. }
  209. // 一个订单只能包含一类商品
  210. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  211. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  212. if (count($goodsCategoryType) != 1) {
  213. $this->addError($attribute, '订单不能包含多种商品分类');
  214. return;
  215. }
  216. // 购买方式
  217. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  218. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  219. $this->addError($attribute, '支付方式错误2');
  220. return;
  221. }
  222. // 所选支付方式必须是商品分类支持的类型
  223. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  224. // 商品类型
  225. $currCategoryType = $goodsCategoryType[0];
  226. if (!array_key_exists($currCategoryType, $categoryType)) {
  227. $this->addError($attribute, '商品分类错误');
  228. return;
  229. }
  230. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  231. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  232. $this->addError($attribute, '支付方式错误3');
  233. return;
  234. }
  235. }
  236. /**
  237. * 校验类型
  238. * @param $attribute
  239. */
  240. public function isStatus($attribute){
  241. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  242. $this->addError($attribute, '类型错误');
  243. return ;
  244. }
  245. if ($this->scenario == 'adminStatus'){
  246. if ($this->status == $this->_model['STATUS']) {
  247. $this->addError($attribute, '订单状态没有改变');
  248. return ;
  249. }
  250. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  251. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  252. return ;
  253. }
  254. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  255. $this->addError($attribute, '订单已失效不能处理');
  256. return ;
  257. }
  258. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  259. $this->addError($attribute, '订单不能单独处理为物流状态');
  260. return ;
  261. }
  262. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  263. $this->addError($attribute, '订单已失效不能处理');
  264. return ;
  265. }
  266. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  267. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  268. $this->addError($attribute, '订单已完成不能取消');
  269. return ;
  270. }
  271. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  272. $this->addError($attribute, '订单已删除不能取消');
  273. return ;
  274. }
  275. }
  276. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  277. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  278. $this->addError($attribute, '订单已完成不能删除');
  279. return ;
  280. }
  281. }
  282. }
  283. }
  284. /**
  285. * 管理员发货
  286. * @return Order|null
  287. * @throws \yii\db\Exception
  288. */
  289. public function adminDelivery(){
  290. if(!$this->validate()){
  291. return null;
  292. }
  293. $db = \Yii::$app->db;
  294. $transaction = $db->beginTransaction();
  295. try {
  296. $period = Period::instance();
  297. $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value'];
  298. $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum();
  299. $this->_model->DELIVERY_AT = Date::nowTime();
  300. $this->_model->EXPRESS_COMPANY = $this->expressCompany;
  301. $this->_model->ORDER_TRACK_NO = $this->orderTrackNo;
  302. $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value'];
  303. if(!$this->_model->save()){
  304. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  305. }
  306. $transaction->commit();
  307. } catch (Exception $e) {
  308. $transaction->rollBack();
  309. $this->addError('edit', $e->getMessage());
  310. return null;
  311. }
  312. return $this->_model;
  313. }
  314. /**
  315. * 校验PayStack支付,更新订单状态.
  316. * @return Order|null
  317. * @throws Exception
  318. */
  319. public function verifyPayStack(): ?Order
  320. {
  321. if(!$this->validate()){
  322. return null;
  323. }
  324. // 调用PayStack支付校验
  325. $payload = PayStack::transactionVerify($this->remark['reference']);
  326. if ($payload['status'] !== true) {
  327. throw new Exception(Form::formatErrorsForApi($payload['message']));
  328. }
  329. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  330. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  331. }
  332. $db = \Yii::$app->db;
  333. $transaction = $db->beginTransaction();
  334. try {
  335. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  336. $this->_model->REMARK = json_encode($this->remark);
  337. $this->_model->PAY_AT = Date::nowTime();
  338. if (!$this->_model->save()) {
  339. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  340. }
  341. $transaction->commit();
  342. } catch (Exception $e) {
  343. $transaction->rollBack();
  344. $this->addError('edit', $e->getMessage());
  345. return null;
  346. }
  347. return $this->_model;
  348. }
  349. /**
  350. * 订单退款
  351. * @return Order|null
  352. * @throws Exception
  353. */
  354. public function adminRefund()
  355. {
  356. if(!$this->validate()){
  357. return null;
  358. }
  359. // 支付信息存在于remark中
  360. $remark = $this->_model->REMARK ? json_decode($this->_model->REMARK, true) : [];
  361. $reference = $remark['reference'] ?? '';
  362. if (!$reference) {
  363. throw new Exception(Form::formatErrorsForApi('支付信息不存在'));
  364. }
  365. // 退款金额. 订单支付金额 * 100
  366. $amount = $this->_model->PAY_AMOUNT * 100;
  367. // 调用PayStack支付校验
  368. $payload = PayStack::transactionRefund($reference, $amount);
  369. if ($payload['status'] !== true) {
  370. throw new Exception(Form::formatErrorsForApi($payload['message']));
  371. }
  372. $db = \Yii::$app->db;
  373. $transaction = $db->beginTransaction();
  374. try {
  375. $this->_model->STATUS = \Yii::$app->params['orderStatus']['refund']['value'];
  376. $this->_model->REMARK = json_encode([
  377. 'payment' => $remark,
  378. 'refund' => $payload['data']
  379. ]
  380. );
  381. if (!$this->_model->save()) {
  382. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  383. }
  384. $transaction->commit();
  385. } catch (Exception $e) {
  386. $transaction->rollBack();
  387. $this->addError('edit', $e->getMessage());
  388. return null;
  389. }
  390. return $this->_model;
  391. }
  392. /**
  393. * 复销
  394. * @throws Exception
  395. * @throws \yii\db\Exception
  396. */
  397. public function add(){
  398. if(!$this->validate()){
  399. return null;
  400. }
  401. $ids = $this->goodsId;
  402. $totalAmount = 0;
  403. $totalPv = 0;
  404. $totalAmountStandard = 0;
  405. $goodsType = ShopGoods::GOODS_TYPE;
  406. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  407. foreach ($this->goodsNum as $k => $v) {
  408. if ($v) {
  409. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  410. if($goods['STORE_NUMS']>0){
  411. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  412. $discount = $goodsType[$goods['TYPE']]['discount'];
  413. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  414. $realPv = $goods['PRICE_PV'] * $discount/100;
  415. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  416. } else {
  417. $discount = $goods['SELL_DISCOUNT'];
  418. $realPrice = $goods['SELL_PRICE'] * $discount;
  419. $realPv = $goods['PRICE_PV'] * $discount;
  420. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  421. }
  422. $totalAmount += $realPrice * intval($v);
  423. $totalPv += $realPv * intval($v);
  424. $totalAmountStandard += $realPriceStandard * intval($v);
  425. // if($this->payType=='cash') {
  426. // $discount = $goodsType[$goods['TYPE']]['discount'];
  427. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  428. // $realPv = $goods['PRICE_PV'] * $discount/100;
  429. // $totalAmount += $realPrice * intval($v);
  430. // $totalPv += $realPv * intval($v);
  431. // }else{
  432. // $realPrice = $goods['SELL_PRICE'];
  433. // $realPv = $goods['PRICE_PV'];
  434. // $totalAmount += $realPrice * intval($v);
  435. // $totalPv += $realPv * intval($v);
  436. // }
  437. $this->_orderGoods[] = [
  438. 'GOODS_ID' => $goods['ID'],
  439. 'PRICE' => $goods['SELL_PRICE'],
  440. 'PV' => $goods['PRICE_PV'],
  441. 'REAL_PRICE' => $realPrice,
  442. 'REAL_PV' => $realPv,
  443. 'POINT' => $goods['POINT'],
  444. 'BUY_NUMS' => intval($v),
  445. 'SKU_CODE' => $goods['GOODS_NO'],
  446. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  447. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  448. 'PAY_TYPE' => $this->payType,
  449. 'EMAIL' => $this->email,
  450. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  451. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  452. 'EXCHANGE_RATE' => $exchangeRate,
  453. ];
  454. }
  455. }
  456. }
  457. $this->_decAmount = $totalAmount;
  458. $this->_decPv = $totalPv;
  459. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  460. if($this->_address['PROVINCE']==1){
  461. $this->_freight = 0;
  462. }
  463. $this->_payAmount = $this->_decAmount + $this->_freight;
  464. $this->_decAmountStandard = $totalAmountStandard;
  465. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  466. $db = \Yii::$app->db;
  467. $transaction = $db->beginTransaction();
  468. try {
  469. //判断用户余额是否充足
  470. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  471. if ($result['code'] !== 200) {
  472. throw new Exception($result['message']);
  473. }
  474. /**
  475. * 2022-04-28
  476. * York
  477. * 支付后减少库存
  478. */
  479. foreach ($this->goodsNum as $k => $v){
  480. if ($v){
  481. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  482. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  483. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  484. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  485. $data->STORE_NUMS = $goods_store_nums;
  486. $data->update();
  487. //下单后库存小于等于0 商品下架
  488. if($goods_store_nums <= 0){
  489. $data->STATUS = 0;
  490. $data->UPDATED_AT = Date::nowTime();
  491. $data->update();
  492. }
  493. }else{
  494. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  495. }
  496. }
  497. }
  498. // exit();
  499. //写入订单
  500. if (!$orderResult = $this->addOrder()) {
  501. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  502. }
  503. $transaction->commit();
  504. return $orderResult;
  505. }catch (\Exception $e){
  506. $transaction->rollBack();
  507. $this->addError('add', $e->getMessage());
  508. return null;
  509. }
  510. }
  511. /**
  512. * 判断对应账户余额是否充足.
  513. * @param $payType string 支付方式.
  514. * @param $payAmount numeric 支付金额
  515. * @return array|int[]
  516. */
  517. public function getBalanceAdequate(string $payType, $payAmount): array
  518. {
  519. $loginUserId = \Yii::$app->user->id;
  520. if ($payType == 'cash') {
  521. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  522. return ['code' => 500, 'message' => '余额不足,无法购买商品'];
  523. }
  524. } else if ($payType =='exchange') {
  525. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  526. return ['code' => 500, 'message' => '兑换积分不足,无法购买商品'];
  527. }
  528. } else if (in_array($payType, ['travel_points', 'car_points', 'house_points'])) {
  529. if ($payAmount > Balance::getAccountBalance($loginUserId, $payType)) {
  530. return ['code' => 500, 'message' => (Balance::BALANCE_TYPE[$payType]['title'] ?? '积分') . '不足,无法购买商品'];
  531. }
  532. } else{
  533. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  534. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  535. // }
  536. }
  537. return ['code' => 200];
  538. }
  539. /**
  540. * 复销订单
  541. * @throws Exception
  542. */
  543. public function addOrder(){
  544. $periodObj = Period::instance();
  545. $nowPeriodNum = $periodObj->getNowPeriodNum();
  546. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  547. $userId = \Yii::$app->user->id;
  548. $userName = Info::getUserNameByUserId($userId);
  549. $userRealName = Info::getUserRealNameByUserId($userId);
  550. $userMobile = Info::getUserMobileByUserId($userId);
  551. $userEmail = Info::getUserEmailByUserId($userId);
  552. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  553. // 加入订单信息
  554. if ($this->_address['PROVINCE'] != 1) {
  555. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  556. if (!$warehouse) {
  557. throw new Exception('地区2暂时不支持配送,具体联系客服');
  558. }
  559. }else{
  560. $warehouse = '01';
  561. }
  562. $_hasPV = in_array($this->payType, ['exchange', 'travel_points', 'car_points', 'house_points']) ? 0 : $this->_decPv;
  563. $ordNo = $this->_generateSn();
  564. $orderModel = new Order();
  565. $orderModel->SN = 'OS'.$ordNo;
  566. $orderModel->DEC_SN = 'DS'.$ordNo;
  567. $orderModel->ORDER_TYPE = $this->type;
  568. $orderModel->USER_ID = $userId;
  569. $orderModel->USER_NAME = $userName;
  570. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  571. $orderModel->PV = $_hasPV;
  572. $orderModel->PAY_AMOUNT = $this->_payAmount;
  573. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  574. $orderModel->PAY_AT = ($this->payType == 'pay_stack' ? 0 :Date::nowTime());
  575. $orderModel->PAY_TYPE = $this->payType;
  576. $orderModel->PERIOD_NUM = $nowPeriodNum;
  577. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  578. $orderModel->FREIGHT = $this->_freight;
  579. $orderModel->PAY_FREIGHT = $this->_freight;
  580. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  581. $orderModel->MOBILE = $this->_address['MOBILE'];
  582. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  583. // $orderModel->CITY = $this->_address['CITY'];
  584. // $orderModel->COUNTY = $this->_address['COUNTY'];
  585. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  586. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  587. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  588. $orderModel->FRONT_REMARK = $this->remark;
  589. $orderModel->WAREHOUSE = $warehouse;
  590. $orderModel->STATUS = ($this->payType == 'pay_stack' ? \Yii::$app->params['orderStatus']['notPaid']['value'] : \Yii::$app->params['orderStatus']['paid']['value']);
  591. $orderModel->CREATED_AT = Date::nowTime();
  592. $orderModel->CREATE_USER = $userName;
  593. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.com';
  594. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  595. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  596. $orderModel->EXCHANGE_RATE = $exchangeRate;
  597. if($this->_address['PROVINCE']==1){
  598. $orderModel->EXPRESS_TYPE = 1;
  599. $orderModel->CONSIGNEE = $userRealName;
  600. $orderModel->MOBILE = $userMobile;
  601. $orderModel->PROVINCE = 1;
  602. $orderModel->CITY = 1;
  603. $orderModel->COUNTY = 1;
  604. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  605. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  606. $orderModel->ADDRESS = 'Self Pick-up';
  607. }
  608. if(!$orderModel->save()){
  609. $this->addErrors($orderModel->getErrors());
  610. return false;
  611. }
  612. // 加入商品到订单商品表
  613. foreach($this->_orderGoods as $key=>$value){
  614. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  615. if (in_array($orderModel->PAY_TYPE, ['exchange', 'travel_points', 'car_points', 'house_points'])) {
  616. $this->_orderGoods[$key]['REAL_PV'] = 0;
  617. }
  618. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  619. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  620. }
  621. OrderGoods::batchInsert($this->_orderGoods);
  622. //扣除会员余额/积分
  623. if($this->payType=='cash') {
  624. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  625. } else if ($this->payType=='exchange') {
  626. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
  627. } else if ($this->payType == 'travel_points') {
  628. Balance::changeUserBonus(\Yii::$app->user->id, 'travel_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TRAVEL_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']);
  629. } else if ($this->payType == 'car_points') {
  630. Balance::changeUserBonus(\Yii::$app->user->id, 'car_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::CAR_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']);
  631. } else if ($this->payType == 'house_points') {
  632. Balance::changeUserBonus(\Yii::$app->user->id, 'house_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::HOUSE_POINTS_EXCHANGE,'REMARK' => '会员豪宅积分兑换']);
  633. } else if ($this->payType == 'reconsume_points') {
  634. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
  635. }
  636. return $orderModel;
  637. }
  638. /**
  639. * 帮会员复销
  640. * @return bool|null
  641. * @throws Exception
  642. * @throws \yii\db\Exception
  643. */
  644. public function reconsumeAdd(){
  645. if(!$this->validate()){
  646. return null;
  647. }
  648. $ids = $this->goodsId;
  649. $totalAmount = 0;
  650. $totalPv = 0;
  651. $goodsType = ShopGoods::GOODS_TYPE;
  652. foreach ($this->goodsNum as $k => $v) {
  653. if ($v) {
  654. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  655. if($goods['STORE_NUMS']>0){
  656. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  657. $discount = $goodsType[$goods['TYPE']]['discount'];
  658. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  659. $realPv = $goods['PRICE_PV'] * $discount/100;
  660. } else {
  661. $discount = $goods['SELL_DISCOUNT'];
  662. $realPrice = $goods['SELL_PRICE'] * $discount;
  663. $realPv = $goods['PRICE_PV'] * $discount;
  664. }
  665. $totalAmount += $realPrice * intval($v);
  666. $totalPv += $realPv * intval($v);
  667. $this->_orderGoods[] = [
  668. 'GOODS_ID' => $goods['ID'],
  669. 'PRICE' => $goods['SELL_PRICE'],
  670. 'PV' => $goods['PRICE_PV'],
  671. 'REAL_PRICE' => $realPrice,
  672. 'REAL_PV' => $realPv,
  673. 'POINT' => $goods['POINT'],
  674. 'BUY_NUMS' => intval($v),
  675. 'SKU_CODE' => $goods['GOODS_NO'],
  676. 'GOODS_TITLE' => $goods['GOODS_NAME']
  677. ];
  678. }
  679. }
  680. }
  681. $this->_decAmount = $totalAmount;
  682. $this->_decPv = $totalPv;
  683. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  684. if($this->_address['PROVINCE']==1){
  685. $this->_freight = 0;
  686. }
  687. $this->_payAmount = $this->_decAmount + $this->_freight;
  688. $db = \Yii::$app->db;
  689. $transaction = $db->beginTransaction();
  690. try {
  691. $loginUserId = \Yii::$app->user->id;
  692. //是否开启伞下会员限制
  693. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  694. if($isResaleUmbrella){
  695. $userId = Info::getUserIdByUserName($this->userName);
  696. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  697. if(!$userNetwork){
  698. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  699. }
  700. }
  701. //判断用户余额是否充足
  702. if($this->payType=='cash') {
  703. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  704. throw new Exception('余额不足,无法购买商品');
  705. }
  706. }else{
  707. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  708. throw new Exception('复消积分不足,无法购买商品');
  709. }
  710. }
  711. /**
  712. * 2022-04-28
  713. * York
  714. * 支付后减少库存
  715. */
  716. foreach ($this->goodsNum as $k => $v){
  717. if ($v){
  718. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  719. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  720. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  721. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  722. $data->STORE_NUMS = $goods_store_nums;
  723. $data->update();
  724. //下单后库存小于等于0 商品下架
  725. if($goods_store_nums <= 0){
  726. $data->STATUS = 0;
  727. $data->UPDATED_AT = Date::nowTime();
  728. $data->update();
  729. }
  730. }else{
  731. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  732. }
  733. }
  734. }
  735. // exit();
  736. //写入订单
  737. if (!$orderResult = $this->addUserOrder()) {
  738. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  739. }
  740. $transaction->commit();
  741. }catch (\Exception $e){
  742. $transaction->rollBack();
  743. $this->addError('add', $e->getMessage());
  744. return null;
  745. }
  746. return true;
  747. }
  748. /**
  749. * 帮会员复消的订单
  750. */
  751. public function addUserOrder(){
  752. $periodObj = Period::instance();
  753. $nowPeriodNum = $periodObj->getNowPeriodNum();
  754. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  755. //帮复消会员Id(登陆会员)
  756. $loginUserId = \Yii::$app->user->id;
  757. $loginUserName = Info::getUserNameByUserId($loginUserId);
  758. //订单会员Id
  759. $userId = Info::getUserIdByUserName($this->userName);
  760. $email = Info::getEmailByUserId($this->userName);
  761. // 加入订单信息
  762. if($this->province!=1){
  763. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  764. if(!$warehouse){
  765. throw new Exception('地区1暂时不支持配送,具体联系客服');
  766. }
  767. }else{
  768. $warehouse = '01';
  769. }
  770. $ordNo = $this->_generateSn();
  771. $orderModel = new Order();
  772. $orderModel->SN = 'OS'.$ordNo;
  773. $orderModel->DEC_SN = 'DS'.$ordNo;
  774. $orderModel->ORDER_TYPE = $this->type;
  775. $orderModel->USER_ID = $userId;
  776. $orderModel->USER_NAME = $this->userName;
  777. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  778. $orderModel->PV = $this->_decPv;
  779. $orderModel->PAY_AMOUNT = $this->_payAmount;
  780. $orderModel->PAY_PV = $this->_decPv;
  781. $orderModel->PAY_AT = Date::nowTime();
  782. $orderModel->PAY_TYPE = $this->payType;
  783. $orderModel->PERIOD_NUM = $nowPeriodNum;
  784. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  785. $orderModel->FREIGHT = $this->_freight;
  786. $orderModel->PAY_FREIGHT = $this->_freight;
  787. $orderModel->CONSIGNEE = $this->consignee;
  788. $orderModel->MOBILE = $this->acceptMobile;
  789. $orderModel->PROVINCE = $this->province;
  790. // $orderModel->CITY = $this->city;
  791. // $orderModel->COUNTY = $this->county;
  792. $orderModel->ADDRESS = $this->detailaddress;
  793. $orderModel->FRONT_REMARK = $this->remark;
  794. $orderModel->WAREHOUSE = $warehouse;
  795. $orderModel->STATUS = 1;
  796. $orderModel->CREATED_AT = Date::nowTime();
  797. $orderModel->CREATE_USER = $loginUserName;
  798. $orderModel->EMAIL = $email?$email:'tt@qq.com';
  799. if(!$orderModel->save()){
  800. $this->addErrors($orderModel->getErrors());
  801. return false;
  802. }
  803. // 加入商品到订单商品表
  804. foreach($this->_orderGoods as $key=>$value){
  805. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  806. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  807. }
  808. OrderGoods::batchInsert($this->_orderGoods);
  809. //扣除会员余额/积分
  810. if($this->payType=='cash') {
  811. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  812. }else{
  813. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  814. }
  815. return $orderModel;
  816. }
  817. /**
  818. * 生成流水号
  819. * @return string
  820. */
  821. private function _generateSn() {
  822. return Date::today('Ymd') . $this->_random(10, 1);
  823. }
  824. /**
  825. * 生成随机数
  826. * @param $length
  827. * @param int $numeric
  828. * @return string
  829. */
  830. private function _random($length, $numeric = 0) {
  831. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  832. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  833. $hash = '';
  834. $max = strlen($seed) - 1;
  835. for ($i = 0; $i < $length; $i++) {
  836. $hash .= $seed[mt_rand(0, $max)];
  837. }
  838. return $hash;
  839. }
  840. }