OrderForm.php 32 KB

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