OrderForm.php 33 KB

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