Balance.php 25 KB

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