Balance.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/10/30
  6. * Time: 下午3:19
  7. */
  8. namespace common\helpers\user;
  9. use common\components\ActiveRecord;
  10. use common\helpers\Cache;
  11. use common\helpers\Date;
  12. use common\helpers\Form;
  13. use common\libs\lock\RedisLock;
  14. use common\models\Countries;
  15. use common\models\CurrencyConversions;
  16. use common\models\FlowBonus;
  17. use common\models\FlowCF;
  18. use common\models\FlowGaragePoints;
  19. use common\models\FlowLX;
  20. use common\models\FlowReconsumePoints;
  21. use common\models\FlowTourismPoints;
  22. use common\models\FlowVillaPoints;
  23. use common\models\InvoiceFlow;
  24. use common\models\Period;
  25. use common\models\DeclarationLevel;
  26. use common\models\DecRole;
  27. use common\models\FlowExchangePoints;
  28. use common\models\User;
  29. use common\models\UserPeriodPoints;
  30. use common\models\UserWallet;
  31. use common\models\UserBonus;
  32. use common\models\UserInfo;
  33. use common\models\UserPeriodExchangePoints;
  34. use yii\base\Exception;
  35. use yii\db\Expression;
  36. class Balance {
  37. const INCR_REDUCE = 0; // 减少
  38. const INCR_ADD = 1; // 增加
  39. const BONUS_BALANCE_LOCK_KEY = 'userBonus:';
  40. const INVOICE_BALANCE_LOCK_KEY = 'Invoice';
  41. const USER_PERFORMANCE_BONUS_BALANCE_LOCK_KEY = 'userPerformanceBonus:';
  42. const BALANCE_TYPE = [
  43. 'userBonus' => [
  44. 'id' => 'userBonus',
  45. 'title' => '奖金',
  46. 'attr' => 'userBonus',
  47. 'pv' => false,
  48. ],
  49. 'userPerformanceBonus' => [
  50. 'id' => 'userPerformanceBonus',
  51. 'title' => '绩效奖金',
  52. 'attr' => 'userPerformanceBonus',
  53. 'pv' => false,
  54. ],
  55. ];
  56. /**
  57. * 发票流水
  58. * @param $userId
  59. * @param $amount
  60. * @param $params
  61. * @return bool
  62. * @throws Exception
  63. * @throws \yii\db\Exception
  64. */
  65. public static function changeInvoice($userId, $amount, $params) {
  66. if ($amount == 0) return true;
  67. $period = Period::instance();
  68. if (!isset($params['PERIOD_NUM'])) {
  69. $periodNum = $period->getNowPeriodNum();
  70. } else {
  71. $periodNum = $params['PERIOD_NUM'];
  72. }
  73. $calcYearMonth = $period->getYearMonth($periodNum);
  74. // redis加锁(防止并发余额数值不准确出错)
  75. $lockKey = self::INVOICE_BALANCE_LOCK_KEY . $userId;
  76. if (RedisLock::instance()->lock($lockKey)) {
  77. $userInfo = UserInfo::findOne(['USER_ID' => $userId]);
  78. $totals = $userInfo->INVOICE_BALANCE + $amount;
  79. $userInfo->INVOICE_BALANCE = $totals;
  80. if (!$userInfo->save()) {
  81. throw new \Exception(Form::formatErrorsForApi($userInfo->getErrors()));
  82. }
  83. //记录流水
  84. $baseInfo = Info::baseInfoZh($userId);
  85. $flowInsertData = [
  86. 'USER_ID' => $userId,
  87. 'REAL_NAME' => $baseInfo['REAL_NAME'],
  88. 'DEC_LV' => $baseInfo['DEC_LV'],
  89. 'EMP_LV' => $baseInfo['EMP_LV'],
  90. 'MOBILE' => $baseInfo['MOBILE'],
  91. 'REG_TYPE' => $userInfo['REG_TYPE'],
  92. 'REG_NAME' => $userInfo['REG_NAME'],
  93. 'CREDIT_CODE' => $userInfo['CREDIT_CODE'],
  94. 'SALE_NAME' => $params['SALE_NAME'] ?? null,
  95. 'TAXPAYER_NUMBER' => $params['TAXPAYER_NUMBER'] ?? null,
  96. 'INVOICE_SN' => $params['INVOICE_SN'] ?? null,
  97. 'INVOICE_ACCOUNT' => $params['INVOICE_ACCOUNT'] ?? null,
  98. 'TAX_ACCOUNT' => $params['TAX_ACCOUNT'] ?? null,
  99. 'OUTED_AT' => $params['OUTED_AT'] ?? 0,
  100. 'AMOUNT' => abs($amount),
  101. 'TOTAL' => $totals,
  102. 'WITHDRAW_SN' => $params['WITHDRAW_SN'] ?? null,
  103. 'IS_INCR' => $amount > 0 ? self::INCR_ADD : self::INCR_REDUCE,
  104. 'PERIOD_NUM' => $periodNum,
  105. 'CALC_MONTH' => $calcYearMonth,
  106. 'REMARK' => $params['REMARK'] ?? null,
  107. 'CREATE_ADMIN' => $params['CREATE_ADMIN'],
  108. 'CREATE_REMARK' => $params['CREATE_REMARK'] ?? null,
  109. 'CREATE_TIME' => $params['CREATE_TIME'],
  110. 'AUDIT_ADMIN' => $params['AUDIT_ADMIN'],
  111. 'AUDIT_REMARK' => $params['AUDIT_REMARK'] ?? null,
  112. 'AUDIT_TIME' => $params['AUDIT_TIME'],
  113. 'P_MONTH' => Date::ociToDate(),
  114. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  115. ];
  116. InvoiceFlow::insertOne($flowInsertData);
  117. unset($flowInsertData);
  118. RedisLock::instance()->unlock($lockKey);
  119. } else {
  120. throw new Exception('流水产生错误');
  121. }
  122. return true;
  123. }
  124. /**
  125. * 获取当前可用余额
  126. * @param $userId
  127. * @return int|mixed
  128. */
  129. public static function getAvailableBalance($userId) {
  130. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  131. if ($oneData) {
  132. return $oneData['BONUS'] - $oneData['BONUS_FREEZE'];
  133. } else {
  134. return 0;
  135. }
  136. }
  137. /**
  138. * 获取当前车房养老奖余额
  139. * @param $userId
  140. * @return int|mixed
  141. */
  142. public static function getBalanceCF($userId) {
  143. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  144. if ($oneData) {
  145. return $oneData['CF'];
  146. } else {
  147. return 0;
  148. }
  149. }
  150. /**
  151. * 获取当前复消积分余额
  152. * @param $userId
  153. * @return int|mixed
  154. */
  155. public static function getBalanceReconsumePoints($userId) {
  156. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  157. if ($oneData) {
  158. return $oneData['RECONSUME_POINTS'];
  159. } else {
  160. return 0;
  161. }
  162. }
  163. /**
  164. * 获取当前兑换积分余额
  165. * @param $userId
  166. * @return int|mixed
  167. */
  168. public static function getBalanceExchangePoints($userId) {
  169. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  170. if ($oneData) {
  171. return $oneData['EXCHANGE_POINTS'];
  172. } else {
  173. return 0;
  174. }
  175. }
  176. /**
  177. * 获取当前车房养老奖余额
  178. * @param $userId
  179. * @return int|mixed
  180. */
  181. public static function getBalanceLX($userId) {
  182. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  183. if ($oneData) {
  184. return $oneData['LX'];
  185. } else {
  186. return 0;
  187. }
  188. }
  189. /**
  190. * 获取当前旅游积分余额
  191. * @param $userId
  192. * @return int|mixed
  193. */
  194. public static function getBalanceTourism($userId) {
  195. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  196. return $oneData['TOURISM_POINTS'] ?? 0;
  197. }
  198. /**
  199. * 获取当前车房余额
  200. * @param $userId
  201. * @return int|mixed
  202. */
  203. public static function getBalanceGarage($userId) {
  204. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  205. return $oneData['GARAGE_POINTS'] ?? 0;
  206. }
  207. /**
  208. * 查询会员账户余额.
  209. * @param $userId
  210. * @param $payType
  211. * @return int|mixed
  212. */
  213. public static function getAccountBalance($userId, $payType) {
  214. $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  215. return !$oneData ? 0 : $oneData[Balance::BALANCE_TYPE[$payType]['attr']] ?? 0;
  216. }
  217. /**
  218. * 改变会员的余额
  219. * @param $userId
  220. * @param $type
  221. * @param $amount
  222. * @param array $params
  223. * @param bool $allowMinus
  224. * @return bool
  225. * @throws Exception
  226. * @throws \yii\db\Exception
  227. */
  228. public static function changeUserBonus($userId, $type, $amount, $params = [], $allowMinus = false) {
  229. if (array_key_exists($type, UserBonus::TYPE)) {
  230. $type = strtoupper($type);
  231. }
  232. if ($amount == 0) return true;
  233. $period = Period::instance();
  234. if (!isset($params['PERIOD_NUM'])) {
  235. $periodNum = $period->getNowPeriodNum();
  236. } else {
  237. $periodNum = $params['PERIOD_NUM'];
  238. }
  239. $calcYearMonth = $period->getYearMonth($periodNum);
  240. // 汇率
  241. // $countryId = User::getEnCodeInfo($userId)['COUNTRY_ID'];
  242. // $decCountry = Countries::getById($countryId);
  243. // $exchangeRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
  244. $exchangeRate = 1; // TODO:奖金发放美元
  245. // redis加锁(防止并发余额数值不准确出错)
  246. switch ($type) {
  247. case 'userBonus':
  248. $lockKey = self::BONUS_BALANCE_LOCK_KEY . $userId;
  249. break;
  250. case 'userPerformanceBonus':
  251. $lockKey = self::USER_PERFORMANCE_BONUS_BALANCE_LOCK_KEY . $userId;
  252. break;
  253. default:
  254. throw new Exception('流水类型错误');
  255. }
  256. if (RedisLock::instance()->lock($lockKey)) {
  257. // 改变发奖
  258. $paramData = [];
  259. $oneUserBonusModel = UserBonus::findOne(['USER_ID' => $userId]);
  260. // 是否奖金发放操作
  261. $issueBonus = $params['BONUS_ISSUE'] ?? false;
  262. if ($oneUserBonusModel) {
  263. $paramData[$type] = new Expression($type.' + ' . ($issueBonus ? $amount * $exchangeRate : $amount));
  264. $oneUserBonusModel->$type += ($issueBonus ? $amount * $exchangeRate : $amount);
  265. if ($oneUserBonusModel->$type < 0) {
  266. RedisLock::instance()->unlock($lockKey);
  267. throw new Exception('金额不足');
  268. }
  269. if (isset($params['BONUS_TOTAL'])) {
  270. $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + ' . ($issueBonus ? $params['BONUS_TOTAL'] * $exchangeRate : $params['BONUS_TOTAL']));
  271. }
  272. // 奖金发放
  273. UserBonus::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  274. } else {
  275. $paramData = [
  276. 'USER_ID' => $userId,
  277. $type => $issueBonus ? $amount * $exchangeRate : $amount,
  278. 'CREATED_AT' => Date::nowTime()
  279. ];
  280. if (isset($params['MANAGE_TAX'])) {
  281. $paramData['MANAGE_TAX'] = ($issueBonus ? $params['MANAGE_TAX'] * $exchangeRate : $params['MANAGE_TAX']);
  282. }
  283. if (isset($params['BONUS_TOTAL'])) {
  284. $paramData['BONUS_TOTAL'] = ($issueBonus ? $params['BONUS_TOTAL'] * $exchangeRate : $params['BONUS_TOTAL']);
  285. }
  286. // 新增用户奖金记录
  287. UserBonus::insertOne($paramData);
  288. }
  289. unset($oneUserBonusModel,$paramData);
  290. // 获取发放完成的奖金信息
  291. $oneUserBonus = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  292. $userInfo = Info::getLastInfo($userId);
  293. // 记录流水
  294. $flowInsertData = [
  295. 'USER_ID' => $userId,
  296. 'LAST_DEC_LV' => $userInfo['DEC_LV'],
  297. 'LAST_EMP_LV' => $userInfo['LAST_EMP_LV'],
  298. 'LAST_STATUS' => $userInfo['STATUS'],
  299. 'CALC_ID' => $params['CALC_ID'] ?? null,
  300. 'AMOUNT' => ($issueBonus ? $amount * $exchangeRate : $amount),
  301. 'AMOUNT_STANDARD' => (!$issueBonus ? $amount / $exchangeRate : $amount),
  302. 'EXCHANGE_RATE' => $exchangeRate,
  303. 'TOTAL' => $oneUserBonus[$type],
  304. 'IS_INCR' => $amount > 0 ? FlowBonus::INCR_ADD : FlowBonus::INCR_REDUCE,
  305. 'REMARK' => $params['REMARK'] ?? null,
  306. 'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
  307. 'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
  308. 'CALC_MONTH' => $calcYearMonth,
  309. 'P_MONTH' => Date::ociToDate(),
  310. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  311. 'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
  312. 'DEAL_TYPE_ID' => $params['DEAL_TYPE_ID'] ?? '',
  313. 'DEAL_TYPE_IS_PRESET' => $params['DEAL_TYPE_IS_PRESET'] ?? 1,
  314. 'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
  315. 'SORT' => $params['SORT'] ?? 0,
  316. 'ORDER_SN' => $params['ORDER_SN'] ?? '',
  317. ];
  318. if (strtolower($type) == 'reconsume_points' || strtolower($type) == 'cf' || strtolower($type) == 'lx'
  319. || strtolower($type) == 'exchange_points'
  320. ) {
  321. unset($flowInsertData['CALC_ID']);
  322. unset($flowInsertData['TRANSFER_SN']);
  323. unset($flowInsertData['SORT']);
  324. }
  325. if (strtolower($type) == 'bonus') {
  326. FlowBonus::insertOne($flowInsertData);
  327. } elseif (strtolower($type) == 'exchange_points') {
  328. //记录和扣除期数的积分
  329. if( $amount > 0 ) {
  330. self::addPeriodExchangePoints($userId, $periodNum, (!$issueBonus ? $amount / $exchangeRate : $amount));
  331. }else {
  332. self::deductPeriodExchangePoints($userId, abs($amount));
  333. }
  334. FlowExchangePoints::insertOne($flowInsertData);
  335. }
  336. unset($flowInsertData, $userInfo, $oneUserBonus);
  337. RedisLock::instance()->unlock($lockKey);
  338. } else {
  339. throw new Exception('流水产生错误');
  340. }
  341. return true;
  342. }
  343. /**
  344. * 添加对应期数的复消积分
  345. * @param $userId
  346. * @param $periodNum
  347. * @param $amount
  348. * @throws \yii\db\Exception
  349. * @return boolean
  350. */
  351. public static function addPeriodReconsumePoints($userId, $periodNum, $amount) {
  352. if($amount <= 0) return false;
  353. $exists = UserPeriodPoints::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  354. 'USER_ID' => $userId,
  355. 'PERIOD_NUM' => $periodNum,
  356. ])->asArray()->exists();
  357. if( $exists ) {
  358. UserPeriodPoints::updateAllCounters([
  359. 'RECONSUME_POINTS' => $amount,
  360. 'REMAINDER_POINTS' => $amount,
  361. ], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  362. 'USER_ID' => $userId,
  363. 'PERIOD_NUM' => $periodNum,
  364. ]);
  365. }else {
  366. UserPeriodPoints::insertOne([
  367. 'USER_ID' => $userId,
  368. 'PERIOD_NUM' => $periodNum,
  369. 'RECONSUME_POINTS' => $amount,
  370. 'REMAINDER_POINTS' => $amount,
  371. 'EXPIRED' => 0,
  372. 'CREATED_AT' => Date::nowTime()
  373. ]);
  374. }
  375. return true;
  376. }
  377. /**
  378. * 添加对应期数的兑换积分
  379. * @param $userId
  380. * @param $periodNum
  381. * @param $amount
  382. * @throws \yii\db\Exception
  383. * @return boolean
  384. */
  385. public static function addPeriodExchangePoints($userId, $periodNum, $amount) {
  386. if($amount <= 0) return false;
  387. $exists = UserPeriodExchangePoints::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  388. 'USER_ID' => $userId,
  389. 'PERIOD_NUM' => $periodNum,
  390. ])->asArray()->exists();
  391. if( $exists ) {
  392. UserPeriodExchangePoints::updateAllCounters([
  393. 'EXCHANGE_POINTS' => $amount,
  394. 'REMAINDER_POINTS' => $amount,
  395. ], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  396. 'USER_ID' => $userId,
  397. 'PERIOD_NUM' => $periodNum,
  398. ]);
  399. }else {
  400. UserPeriodExchangePoints::insertOne([
  401. 'USER_ID' => $userId,
  402. 'PERIOD_NUM' => $periodNum,
  403. 'EXCHANGE_POINTS' => $amount,
  404. 'REMAINDER_POINTS' => $amount,
  405. 'EXPIRED' => 0,
  406. 'CREATED_AT' => Date::nowTime()
  407. ]);
  408. }
  409. return true;
  410. }
  411. /**
  412. * 减少
  413. * @param $userId
  414. * @param $amount
  415. * @return bool
  416. */
  417. public static function deductPeriodReconsumePoints($userId, $amount) {
  418. if( $amount <= 0 ) return false;
  419. $avalidList = UserPeriodPoints::find()->where('USER_ID=:USER_ID AND EXPIRED=:EXPIRED AND REMAINDER_POINTS>0', [
  420. 'USER_ID' => $userId,
  421. 'EXPIRED'=>0
  422. ])->orderBy('PERIOD_NUM ASC')->asArray()->all();
  423. if( !$avalidList ) return false;
  424. foreach ($avalidList as $everyData) {
  425. if( $amount <= 0 ) break;
  426. $remainderPoints = floatval($everyData['REMAINDER_POINTS']);
  427. if( $amount >= $remainderPoints ) {
  428. UserPeriodPoints::updateAllCounters([
  429. 'REMAINDER_POINTS' => (-1) * $remainderPoints
  430. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  431. $amount -= $remainderPoints;
  432. }else {
  433. UserPeriodPoints::updateAllCounters([
  434. 'REMAINDER_POINTS' => (-1) * $amount
  435. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  436. $amount = 0;
  437. }
  438. unset($everyData, $remainderPoints);
  439. }
  440. if( $amount > 0 ) return false;
  441. return true;
  442. }
  443. /**
  444. * 减少
  445. * @param $userId
  446. * @param $amount
  447. * @return bool
  448. */
  449. public static function deductPeriodExchangePoints($userId, $amount) {
  450. if( $amount <= 0 ) return false;
  451. $avalidList = UserPeriodExchangePoints::find()->where('USER_ID=:USER_ID AND EXPIRED=:EXPIRED AND REMAINDER_POINTS>0', [
  452. 'USER_ID' => $userId,
  453. 'EXPIRED'=>0
  454. ])->orderBy('PERIOD_NUM ASC')->asArray()->all();
  455. if( !$avalidList ) return false;
  456. foreach ($avalidList as $everyData) {
  457. if( $amount <= 0 ) break;
  458. $remainderPoints = floatval($everyData['REMAINDER_POINTS']);
  459. if( $amount >= $remainderPoints ) {
  460. UserPeriodExchangePoints::updateAllCounters([
  461. 'REMAINDER_POINTS' => (-1) * $remainderPoints
  462. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  463. $amount -= $remainderPoints;
  464. }else {
  465. UserPeriodExchangePoints::updateAllCounters([
  466. 'REMAINDER_POINTS' => (-1) * $amount
  467. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  468. $amount = 0;
  469. }
  470. unset($everyData, $remainderPoints);
  471. }
  472. if( $amount > 0 ) return false;
  473. return true;
  474. }
  475. /**
  476. * 冻结用户余额
  477. * @param $userId
  478. * @param $amount
  479. * @param null $remark
  480. * @param null $time
  481. * @return bool
  482. * @throws Exception
  483. * @throws \yii\db\Exception
  484. */
  485. public static function freezeUserBonus($userId, $amount, $remark = null, $time = null) {
  486. return self::changeFreezeUserBonus($userId, $amount, ['REMARK' => $remark, 'TIME' => $time]);
  487. }
  488. /**
  489. * 解冻用户余额
  490. * @param $userId
  491. * @param $amount
  492. * @param null $remark
  493. * @param null $time
  494. * @return bool
  495. * @throws Exception
  496. * @throws \yii\db\Exception
  497. */
  498. public static function unfreezeUserBonus($userId, $amount, $remark = null, $time = null) {
  499. return self::changeFreezeUserBonus($userId, -$amount, ['REMARK' => $remark, 'TIME' => $time]);
  500. }
  501. /**
  502. * @param $userId
  503. * @param $amount
  504. * @param $params
  505. * [
  506. * 'REMARK' => '备注',
  507. * 'PERIOD_NUM' => 100,
  508. * ]
  509. * @return bool
  510. * @throws Exception
  511. * @throws \yii\db\Exception
  512. */
  513. public static function changeFreezeUserBonus($userId, $amount, $params) {
  514. if ($amount == 0) return true;
  515. $period = Period::instance();
  516. if (!isset($params['PERIOD_NUM'])) {
  517. $periodNum = $period->getNowPeriodNum();
  518. } else {
  519. $periodNum = $params['PERIOD_NUM'];
  520. }
  521. $calcYearMonth = $period->getYearMonth($periodNum);
  522. // 改变冻结
  523. $oneUserBonusModel = UserBonus::findOne(['USER_ID' => $userId]);
  524. if ($oneUserBonusModel) {
  525. $oneUserBonusModel->BONUS_FREEZE = $oneUserBonusModel->BONUS_FREEZE + $amount;
  526. } else {
  527. $oneUserBonusModel = new UserBonus();
  528. $oneUserBonusModel->USER_ID = $userId;
  529. $oneUserBonusModel->BONUS_FREEZE = $amount;
  530. }
  531. if (!$oneUserBonusModel->save()) {
  532. throw new Exception(Form::formatErrorsForApi($oneUserBonusModel->getErrors()));
  533. }
  534. unset($oneUserBonusModel);
  535. // 流水
  536. // 获取发放完成的奖金信息
  537. $oneUserBonus = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  538. // 记录流水
  539. $flowInsertData = [
  540. 'USER_ID' => $userId,
  541. 'AMOUNT' => abs($amount),
  542. 'TOTAL' => $oneUserBonus['BONUS'],
  543. 'IS_INCR' => $amount > 0 ? FlowBonus::INCR_FREEZE : FlowBonus::INCR_UNFREEZE,
  544. 'REMARK' => $params['REMARK'] ?? null,
  545. 'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
  546. 'CALC_MONTH' => $calcYearMonth,
  547. 'P_MONTH' => Date::ociToDate(),
  548. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  549. ];
  550. FlowBonus::insertOne($flowInsertData);
  551. unset($flowInsertData);
  552. return true;
  553. }
  554. /**
  555. * 清空会员奖金有流水
  556. * @param $userId
  557. * @param array $params
  558. * @throws Exception
  559. * @throws \yii\db\Exception
  560. */
  561. public static function clearAllBonus($userId, $params = []) {
  562. // 先查找会员的全部余额
  563. $userBonus = UserBonus::findOne(['USER_ID' => $userId]);
  564. // 如果没有会员余额数据,新建余额数据
  565. if (!$userBonus) {
  566. UserBonus::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
  567. } else {
  568. $period = Period::instance();
  569. foreach (\Yii::$app->params['bonusWalletType'] as $type) {
  570. $field = strtoupper($type['name']);
  571. if ($userBonus[$field]<=0) continue;
  572. $userInfo = Info::getLastInfo($userId);
  573. $flowInsertData = [
  574. 'USER_ID' => $userId,
  575. 'LAST_DEC_LV' => $userInfo['DEC_LV'],
  576. 'LAST_EMP_LV' => $userInfo['EMP_LV'],
  577. 'LAST_STATUS' => $userInfo['STATUS'],
  578. 'CALC_ID' => $params['CALC_ID'] ?? null,
  579. 'AMOUNT' => -$userBonus[$field],
  580. 'TOTAL' => 0,
  581. 'IS_INCR' => FlowBonus::INCR_REDUCE,
  582. 'REMARK' => $params['REMARK'] ?? null,
  583. 'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
  584. 'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $period->getNowPeriodNum(),
  585. 'CALC_MONTH' => $period->getNowYearMonth(),
  586. 'P_MONTH' => Date::ociToDate(),
  587. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  588. 'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
  589. 'DEAL_TYPE_ID' => $params['DEAL_TYPE_ID'] ?? '',
  590. 'DEAL_TYPE_IS_PRESET' => $params['DEAL_TYPE_IS_PRESET'] ?? 1,
  591. 'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
  592. 'SORT' => $params['SORT'] ?? 0,
  593. ];
  594. // 流水
  595. if (strtolower($field) == 'bonus') FlowBonus::insertOne($flowInsertData);
  596. elseif (strtolower($field) == 'cf') {
  597. unset($flowInsertData['CALC_ID']);
  598. unset($flowInsertData['SORT']);
  599. unset($flowInsertData['TRANSFER_SN']);
  600. FlowCF::insertOne($flowInsertData);
  601. } elseif (strtolower($field) == 'lx') {
  602. unset($flowInsertData['CALC_ID']);
  603. unset($flowInsertData['SORT']);
  604. unset($flowInsertData['TRANSFER_SN']);
  605. FlowLX::insertOne($flowInsertData);
  606. }
  607. }
  608. // 清空
  609. $userBonus->BONUS = 0;
  610. $userBonus->CF = 0;
  611. $userBonus->LX = 0;
  612. if (!$userBonus->save()) {
  613. throw new Exception(Form::formatErrorsForApi($userBonus->getErrors()));
  614. }
  615. }
  616. FlowBonus::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  617. FlowCF::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  618. FlowLX::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  619. }
  620. /**
  621. * 是否存在奖金余额
  622. * @param $userId
  623. * @return bool
  624. */
  625. public static function hasBonus($userId) {
  626. $userBonus = UserBonus::findOne(['USER_ID' => $userId]);
  627. if (!$userBonus) {
  628. return false;
  629. }
  630. foreach (\Yii::$app->params['bonusWalletType'] as $type) {
  631. $field = strtoupper($type['name']);
  632. if (isset($userBonus[$field]) && $userBonus[$field] > 0) {
  633. return true;
  634. }
  635. }
  636. return false;
  637. }
  638. /**
  639. * 获取金额用于日志
  640. * @param $userId
  641. * @return array
  642. */
  643. public static function getLogData($userId){
  644. $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
  645. $cash = !empty($userWallet) ? $userWallet['CASH'] : '';
  646. $userName = Info::getUserNameByUserId($userId);
  647. $data = [];
  648. $data[$userId]['label'] = $userName.'余额';
  649. $data[$userId]['value'] = '奖金'.self::getAvailableBalance($userId).',现金'.$cash;
  650. return $data;
  651. }
  652. }