OrderForm.php 32 KB

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