OrderForm.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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' => 'product ID',//商品ID
  91. 'goodsNum' => 'Product quantity',//商品数量
  92. 'userName' => 'Repeat sales Member No. does not exist',//复消会员编号
  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, 'The payment password is incorrect');//支付密码不正确
  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 adminRefund()
  312. {
  313. if(!$this->validate()){
  314. return null;
  315. }
  316. // 支付信息存在于remark中
  317. $remark = $this->_model->REMARK ? json_decode($this->_model->REMARK, true) : [];
  318. $reference = $remark['reference'] ?? '';
  319. if (!$reference) {
  320. throw new Exception(Form::formatErrorsForApi('支付信息不存在'));
  321. }
  322. // 退款金额. 订单支付金额 * 100
  323. $amount = $this->_model->PAY_AMOUNT * 100;
  324. // 调用PayStack支付校验
  325. $payload = PayStack::transactionRefund($reference, $amount);
  326. if ($payload['status'] !== true) {
  327. throw new Exception(Form::formatErrorsForApi($payload['message']));
  328. }
  329. $db = \Yii::$app->db;
  330. $transaction = $db->beginTransaction();
  331. try {
  332. $this->_model->STATUS = \Yii::$app->params['orderStatus']['refund']['value'];
  333. $this->_model->REMARK = json_encode([
  334. 'payment' => $remark,
  335. 'refund' => $payload['data']
  336. ]
  337. );
  338. if (!$this->_model->save()) {
  339. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  340. }
  341. $transaction->commit();
  342. } catch (Exception $e) {
  343. $transaction->rollBack();
  344. $this->addError('edit', $e->getMessage());
  345. return null;
  346. }
  347. return $this->_model;
  348. }
  349. /**
  350. * 复销
  351. * @throws Exception
  352. * @throws \yii\db\Exception
  353. */
  354. public function add(){
  355. if(!$this->validate()){
  356. return null;
  357. }
  358. $ids = $this->goodsId;
  359. $totalAmount = 0;
  360. $totalPv = 0;
  361. $totalAmountStandard = 0;
  362. $goodsType = ShopGoods::GOODS_TYPE;
  363. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  364. foreach ($this->goodsNum as $k => $v) {
  365. if ($v) {
  366. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  367. if($goods['STORE_NUMS']>0){
  368. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  369. $discount = $goodsType[$goods['TYPE']]['discount'];
  370. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  371. $realPv = $goods['PRICE_PV'] * $discount/100;
  372. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  373. } else {
  374. $discount = $goods['SELL_DISCOUNT'];
  375. $realPrice = $goods['SELL_PRICE'] * $discount;
  376. $realPv = $goods['PRICE_PV'] * $discount;
  377. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  378. }
  379. $totalAmount += $realPrice * intval($v);
  380. $totalPv += $realPv * intval($v);
  381. $this->_orderGoods[] = [
  382. 'GOODS_ID' => $goods['ID'],
  383. 'PRICE' => $goods['SELL_PRICE'],
  384. 'PV' => $goods['PRICE_PV'],
  385. 'REAL_PRICE' => $realPrice,
  386. 'REAL_PV' => $realPv,
  387. 'POINT' => $goods['POINT'],
  388. 'BUY_NUMS' => intval($v),
  389. 'SKU_CODE' => $goods['GOODS_NO'],
  390. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  391. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  392. 'PAY_TYPE' => $this->payType,
  393. 'EMAIL' => $this->email,
  394. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  395. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  396. 'EXCHANGE_RATE' => $exchangeRate,
  397. ];
  398. }
  399. }
  400. }
  401. $this->_decAmount = $totalAmount;
  402. $this->_decPv = $totalPv;
  403. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  404. if($this->_address['PROVINCE']==1){
  405. $this->_freight = 0;
  406. }
  407. $this->_payAmount = $this->_decAmount + $this->_freight;
  408. $this->_decAmountStandard = $totalAmountStandard;
  409. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  410. $db = \Yii::$app->db;
  411. $transaction = $db->beginTransaction();
  412. try {
  413. //判断用户余额是否充足
  414. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  415. if ($result['code'] !== 200) {
  416. throw new Exception($result['message']);
  417. }
  418. /**
  419. * 2022-04-28
  420. * York
  421. * 支付后减少库存
  422. */
  423. foreach ($this->goodsNum as $k => $v){
  424. if ($v){
  425. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  426. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  427. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  428. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  429. $data->STORE_NUMS = $goods_store_nums;
  430. $data->update();
  431. //下单后库存小于等于0 商品下架
  432. if($goods_store_nums <= 0){
  433. $data->STATUS = 0;
  434. $data->UPDATED_AT = Date::nowTime();
  435. $data->update();
  436. }
  437. }else{
  438. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  439. }
  440. }
  441. }
  442. // exit();
  443. //写入订单
  444. if (!$orderResult = $this->addOrder()) {
  445. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  446. }
  447. $transaction->commit();
  448. return $orderResult;
  449. }catch (\Exception $e){
  450. $transaction->rollBack();
  451. $this->addError('add', $e->getMessage());
  452. return null;
  453. }
  454. }
  455. /**
  456. * 判断对应账户余额是否充足.
  457. * @param $payType string 支付方式.
  458. * @param $payAmount numeric 支付金额
  459. * @return array|int[]
  460. */
  461. public function getBalanceAdequate(string $payType, $payAmount): array
  462. {
  463. $loginUserId = \Yii::$app->user->id;
  464. if ($payType == 'cash') {
  465. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  466. return ['code' => 500, 'message' => '余额不足,无法购买商品'];
  467. }
  468. } else if ($payType =='exchange') {
  469. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  470. return ['code' => 500, 'message' => '兑换积分不足,无法购买商品'];
  471. }
  472. } else if (in_array($payType, ['travel_points', 'car_points', 'house_points'])) {
  473. if ($payAmount > Balance::getAccountBalance($loginUserId, $payType)) {
  474. return ['code' => 500, 'message' => (Balance::BALANCE_TYPE[$payType]['title'] ?? '积分') . '不足,无法购买商品'];
  475. }
  476. } else{
  477. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  478. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  479. // }
  480. }
  481. return ['code' => 200];
  482. }
  483. /**
  484. * 复销订单
  485. * @throws Exception
  486. */
  487. public function addOrder(){
  488. $periodObj = Period::instance();
  489. $nowPeriodNum = $periodObj->getNowPeriodNum();
  490. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  491. $userId = \Yii::$app->user->id;
  492. $userName = Info::getUserNameByUserId($userId);
  493. $userRealName = Info::getUserRealNameByUserId($userId);
  494. $userMobile = Info::getUserMobileByUserId($userId);
  495. $userEmail = Info::getUserEmailByUserId($userId);
  496. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  497. // 加入订单信息
  498. if ($this->_address['PROVINCE'] != 1) {
  499. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  500. if (!$warehouse) {
  501. throw new Exception('地区2暂时不支持配送,具体联系客服');
  502. }
  503. }else{
  504. $warehouse = '01';
  505. }
  506. $_hasPV = in_array($this->payType, ['exchange', 'travel_points', 'car_points', 'house_points']) ? 0 : $this->_decPv;
  507. $ordNo = $this->_generateSn();
  508. $orderModel = new Order();
  509. $orderModel->SN = 'OS'.$ordNo;
  510. $orderModel->DEC_SN = 'DS'.$ordNo;
  511. $orderModel->ORDER_TYPE = $this->type;
  512. $orderModel->USER_ID = $userId;
  513. $orderModel->USER_NAME = $userName;
  514. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  515. $orderModel->PV = $_hasPV;
  516. $orderModel->PAY_AMOUNT = $this->_payAmount;
  517. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  518. $orderModel->PAY_AT = Date::nowTime();
  519. $orderModel->PAY_TYPE = $this->payType;
  520. $orderModel->PERIOD_NUM = $nowPeriodNum;
  521. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  522. $orderModel->FREIGHT = $this->_freight;
  523. $orderModel->PAY_FREIGHT = $this->_freight;
  524. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  525. $orderModel->MOBILE = $this->_address['MOBILE'];
  526. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  527. // $orderModel->CITY = $this->_address['CITY'];
  528. // $orderModel->COUNTY = $this->_address['COUNTY'];
  529. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  530. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  531. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  532. $orderModel->FRONT_REMARK = $this->remark;
  533. $orderModel->WAREHOUSE = $warehouse;
  534. $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  535. $orderModel->CREATED_AT = Date::nowTime();
  536. $orderModel->CREATE_USER = $userName;
  537. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.com';
  538. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  539. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  540. $orderModel->EXCHANGE_RATE = $exchangeRate;
  541. if($this->_address['PROVINCE']==1){
  542. $orderModel->EXPRESS_TYPE = 1;
  543. $orderModel->CONSIGNEE = $userRealName;
  544. $orderModel->MOBILE = $userMobile;
  545. $orderModel->PROVINCE = 1;
  546. $orderModel->CITY = 1;
  547. $orderModel->COUNTY = 1;
  548. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  549. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  550. $orderModel->ADDRESS = 'Self Pick-up';
  551. }
  552. if(!$orderModel->save()){
  553. $this->addErrors($orderModel->getErrors());
  554. return false;
  555. }
  556. // 加入商品到订单商品表
  557. foreach($this->_orderGoods as $key=>$value){
  558. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  559. if (in_array($orderModel->PAY_TYPE, ['exchange', 'travel_points', 'car_points', 'house_points'])) {
  560. $this->_orderGoods[$key]['REAL_PV'] = 0;
  561. }
  562. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  563. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  564. }
  565. OrderGoods::batchInsert($this->_orderGoods);
  566. //扣除会员余额/积分
  567. if($this->payType=='cash') {
  568. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  569. } else if ($this->payType=='exchange') {
  570. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
  571. } else if ($this->payType == 'travel_points') {
  572. Balance::changeUserBonus(\Yii::$app->user->id, 'travel_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TRAVEL_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']);
  573. } else if ($this->payType == 'car_points') {
  574. Balance::changeUserBonus(\Yii::$app->user->id, 'car_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::CAR_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']);
  575. } else if ($this->payType == 'house_points') {
  576. Balance::changeUserBonus(\Yii::$app->user->id, 'house_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::HOUSE_POINTS_EXCHANGE,'REMARK' => '会员豪宅积分兑换']);
  577. } else if ($this->payType == 'reconsume_points') {
  578. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
  579. }
  580. return $orderModel;
  581. }
  582. /**
  583. * 帮会员复销
  584. * @return bool|null
  585. * @throws Exception
  586. * @throws \yii\db\Exception
  587. */
  588. public function reconsumeAdd(){
  589. if(!$this->validate()){
  590. return null;
  591. }
  592. $ids = $this->goodsId;
  593. $totalAmount = 0;
  594. $totalPv = 0;
  595. $goodsType = ShopGoods::GOODS_TYPE;
  596. foreach ($this->goodsNum as $k => $v) {
  597. if ($v) {
  598. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  599. if($goods['STORE_NUMS']>0){
  600. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  601. $discount = $goodsType[$goods['TYPE']]['discount'];
  602. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  603. $realPv = $goods['PRICE_PV'] * $discount/100;
  604. } else {
  605. $discount = $goods['SELL_DISCOUNT'];
  606. $realPrice = $goods['SELL_PRICE'] * $discount;
  607. $realPv = $goods['PRICE_PV'] * $discount;
  608. }
  609. $totalAmount += $realPrice * intval($v);
  610. $totalPv += $realPv * intval($v);
  611. $this->_orderGoods[] = [
  612. 'GOODS_ID' => $goods['ID'],
  613. 'PRICE' => $goods['SELL_PRICE'],
  614. 'PV' => $goods['PRICE_PV'],
  615. 'REAL_PRICE' => $realPrice,
  616. 'REAL_PV' => $realPv,
  617. 'POINT' => $goods['POINT'],
  618. 'BUY_NUMS' => intval($v),
  619. 'SKU_CODE' => $goods['GOODS_NO'],
  620. 'GOODS_TITLE' => $goods['GOODS_NAME']
  621. ];
  622. }
  623. }
  624. }
  625. $this->_decAmount = $totalAmount;
  626. $this->_decPv = $totalPv;
  627. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  628. if($this->_address['PROVINCE']==1){
  629. $this->_freight = 0;
  630. }
  631. $this->_payAmount = $this->_decAmount + $this->_freight;
  632. $db = \Yii::$app->db;
  633. $transaction = $db->beginTransaction();
  634. try {
  635. $loginUserId = \Yii::$app->user->id;
  636. //是否开启伞下会员限制
  637. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  638. if($isResaleUmbrella){
  639. $userId = Info::getUserIdByUserName($this->userName);
  640. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  641. if(!$userNetwork){
  642. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  643. }
  644. }
  645. //判断用户余额是否充足
  646. if($this->payType=='cash') {
  647. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  648. throw new Exception('余额不足,无法购买商品');
  649. }
  650. }else{
  651. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  652. throw new Exception('复消积分不足,无法购买商品');
  653. }
  654. }
  655. /**
  656. * 2022-04-28
  657. * York
  658. * 支付后减少库存
  659. */
  660. foreach ($this->goodsNum as $k => $v){
  661. if ($v){
  662. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  663. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  664. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  665. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  666. $data->STORE_NUMS = $goods_store_nums;
  667. $data->update();
  668. //下单后库存小于等于0 商品下架
  669. if($goods_store_nums <= 0){
  670. $data->STATUS = 0;
  671. $data->UPDATED_AT = Date::nowTime();
  672. $data->update();
  673. }
  674. }else{
  675. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  676. }
  677. }
  678. }
  679. // exit();
  680. //写入订单
  681. if (!$orderResult = $this->addUserOrder()) {
  682. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  683. }
  684. $transaction->commit();
  685. }catch (\Exception $e){
  686. $transaction->rollBack();
  687. $this->addError('add', $e->getMessage());
  688. return null;
  689. }
  690. return true;
  691. }
  692. /**
  693. * 帮会员复消的订单
  694. */
  695. public function addUserOrder(){
  696. $periodObj = Period::instance();
  697. $nowPeriodNum = $periodObj->getNowPeriodNum();
  698. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  699. //帮复消会员Id(登陆会员)
  700. $loginUserId = \Yii::$app->user->id;
  701. $loginUserName = Info::getUserNameByUserId($loginUserId);
  702. //订单会员Id
  703. $userId = Info::getUserIdByUserName($this->userName);
  704. $email = Info::getEmailByUserId($this->userName);
  705. // 加入订单信息
  706. if($this->province!=1){
  707. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  708. if(!$warehouse){
  709. throw new Exception('地区1暂时不支持配送,具体联系客服');
  710. }
  711. }else{
  712. $warehouse = '01';
  713. }
  714. $ordNo = $this->_generateSn();
  715. $orderModel = new Order();
  716. $orderModel->SN = 'OS'.$ordNo;
  717. $orderModel->DEC_SN = 'DS'.$ordNo;
  718. $orderModel->ORDER_TYPE = $this->type;
  719. $orderModel->USER_ID = $userId;
  720. $orderModel->USER_NAME = $this->userName;
  721. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  722. $orderModel->PV = $this->_decPv;
  723. $orderModel->PAY_AMOUNT = $this->_payAmount;
  724. $orderModel->PAY_PV = $this->_decPv;
  725. $orderModel->PAY_AT = Date::nowTime();
  726. $orderModel->PAY_TYPE = $this->payType;
  727. $orderModel->PERIOD_NUM = $nowPeriodNum;
  728. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  729. $orderModel->FREIGHT = $this->_freight;
  730. $orderModel->PAY_FREIGHT = $this->_freight;
  731. $orderModel->CONSIGNEE = $this->consignee;
  732. $orderModel->MOBILE = $this->acceptMobile;
  733. $orderModel->PROVINCE = $this->province;
  734. // $orderModel->CITY = $this->city;
  735. // $orderModel->COUNTY = $this->county;
  736. $orderModel->ADDRESS = $this->detailaddress;
  737. $orderModel->FRONT_REMARK = $this->remark;
  738. $orderModel->WAREHOUSE = $warehouse;
  739. $orderModel->STATUS = 1;
  740. $orderModel->CREATED_AT = Date::nowTime();
  741. $orderModel->CREATE_USER = $loginUserName;
  742. $orderModel->EMAIL = $email?$email:'tt@qq.com';
  743. if(!$orderModel->save()){
  744. $this->addErrors($orderModel->getErrors());
  745. return false;
  746. }
  747. // 加入商品到订单商品表
  748. foreach($this->_orderGoods as $key=>$value){
  749. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  750. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  751. }
  752. OrderGoods::batchInsert($this->_orderGoods);
  753. //扣除会员余额/积分
  754. if($this->payType=='cash') {
  755. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  756. }else{
  757. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  758. }
  759. return $orderModel;
  760. }
  761. /**
  762. * 生成流水号
  763. * @return string
  764. */
  765. private function _generateSn() {
  766. return Date::today('Ymd') . $this->_random(10, 1);
  767. }
  768. /**
  769. * 生成随机数
  770. * @param $length
  771. * @param int $numeric
  772. * @return string
  773. */
  774. private function _random($length, $numeric = 0) {
  775. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  776. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  777. $hash = '';
  778. $max = strlen($seed) - 1;
  779. for ($i = 0; $i < $length; $i++) {
  780. $hash .= $seed[mt_rand(0, $max)];
  781. }
  782. return $hash;
  783. }
  784. }