OrderForm.php 41 KB

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