OrderForm.php 44 KB

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