OrderForm.php 42 KB

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