Balance.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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 'bonus':
  248. $lockKey = self::BONUS_BALANCE_LOCK_KEY . $userId;
  249. break;
  250. default:
  251. throw new Exception('流水类型错误');
  252. }
  253. if (RedisLock::instance()->lock($lockKey)) {
  254. // 改变发奖
  255. $paramData = [];
  256. $oneUserBonusModel = UserBonus::findOne(['USER_ID' => $userId]);
  257. // 是否奖金发放操作
  258. $issueBonus = $params['BONUS_ISSUE'] ?? false;
  259. if ($oneUserBonusModel) {
  260. $paramData[$type] = new Expression($type.' + ' . ($issueBonus ? $amount * $exchangeRate : $amount));
  261. $oneUserBonusModel->$type += ($issueBonus ? $amount * $exchangeRate : $amount);
  262. if ($oneUserBonusModel->$type < 0) {
  263. RedisLock::instance()->unlock($lockKey);
  264. throw new Exception('金额不足');
  265. }
  266. if (isset($params['BONUS_TOTAL'])) {
  267. $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + ' . ($issueBonus ? $params['BONUS_TOTAL'] * $exchangeRate : $params['BONUS_TOTAL']));
  268. }
  269. // 奖金发放
  270. UserBonus::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  271. } else {
  272. $paramData = [
  273. 'USER_ID' => $userId,
  274. $type => $issueBonus ? $amount * $exchangeRate : $amount,
  275. 'CREATED_AT' => Date::nowTime()
  276. ];
  277. if (isset($params['MANAGE_TAX'])) {
  278. $paramData['MANAGE_TAX'] = ($issueBonus ? $params['MANAGE_TAX'] * $exchangeRate : $params['MANAGE_TAX']);
  279. }
  280. if (isset($params['BONUS_TOTAL'])) {
  281. $paramData['BONUS_TOTAL'] = ($issueBonus ? $params['BONUS_TOTAL'] * $exchangeRate : $params['BONUS_TOTAL']);
  282. }
  283. // 新增用户奖金记录
  284. UserBonus::insertOne($paramData);
  285. }
  286. unset($oneUserBonusModel,$paramData);
  287. // 获取发放完成的奖金信息
  288. $oneUserBonus = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  289. $userInfo = Info::getLastInfo($userId);
  290. // 记录流水
  291. $flowInsertData = [
  292. 'USER_ID' => $userId,
  293. 'LAST_DEC_LV' => $userInfo['DEC_LV'],
  294. 'LAST_EMP_LV' => $userInfo['LAST_EMP_LV'],
  295. 'LAST_STATUS' => $userInfo['STATUS'],
  296. 'CALC_ID' => $params['CALC_ID'] ?? null,
  297. 'AMOUNT' => ($issueBonus ? $amount * $exchangeRate : $amount),
  298. 'AMOUNT_STANDARD' => (!$issueBonus ? $amount / $exchangeRate : $amount),
  299. 'EXCHANGE_RATE' => $exchangeRate,
  300. 'TOTAL' => $oneUserBonus[$type],
  301. 'IS_INCR' => $amount > 0 ? FlowBonus::INCR_ADD : FlowBonus::INCR_REDUCE,
  302. 'REMARK' => $params['REMARK'] ?? null,
  303. 'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
  304. 'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
  305. 'CALC_MONTH' => $calcYearMonth,
  306. 'P_MONTH' => Date::ociToDate(),
  307. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  308. 'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
  309. 'DEAL_TYPE_ID' => $params['DEAL_TYPE_ID'] ?? '',
  310. 'DEAL_TYPE_IS_PRESET' => $params['DEAL_TYPE_IS_PRESET'] ?? 1,
  311. 'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
  312. 'SORT' => $params['SORT'] ?? 0,
  313. 'ORDER_SN' => $params['ORDER_SN'] ?? '',
  314. ];
  315. // 写入流水
  316. if (strtolower($type) == 'bonus') {
  317. FlowBonus::insertOne($flowInsertData);
  318. }
  319. unset($flowInsertData, $userInfo, $oneUserBonus);
  320. RedisLock::instance()->unlock($lockKey);
  321. } else {
  322. throw new Exception('流水产生错误');
  323. }
  324. return true;
  325. }
  326. /**
  327. * 添加对应期数的复消积分
  328. * @param $userId
  329. * @param $periodNum
  330. * @param $amount
  331. * @throws \yii\db\Exception
  332. * @return boolean
  333. */
  334. public static function addPeriodReconsumePoints($userId, $periodNum, $amount) {
  335. if($amount <= 0) return false;
  336. $exists = UserPeriodPoints::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  337. 'USER_ID' => $userId,
  338. 'PERIOD_NUM' => $periodNum,
  339. ])->asArray()->exists();
  340. if( $exists ) {
  341. UserPeriodPoints::updateAllCounters([
  342. 'RECONSUME_POINTS' => $amount,
  343. 'REMAINDER_POINTS' => $amount,
  344. ], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  345. 'USER_ID' => $userId,
  346. 'PERIOD_NUM' => $periodNum,
  347. ]);
  348. }else {
  349. UserPeriodPoints::insertOne([
  350. 'USER_ID' => $userId,
  351. 'PERIOD_NUM' => $periodNum,
  352. 'RECONSUME_POINTS' => $amount,
  353. 'REMAINDER_POINTS' => $amount,
  354. 'EXPIRED' => 0,
  355. 'CREATED_AT' => Date::nowTime()
  356. ]);
  357. }
  358. return true;
  359. }
  360. /**
  361. * 添加对应期数的兑换积分
  362. * @param $userId
  363. * @param $periodNum
  364. * @param $amount
  365. * @throws \yii\db\Exception
  366. * @return boolean
  367. */
  368. public static function addPeriodExchangePoints($userId, $periodNum, $amount) {
  369. if($amount <= 0) return false;
  370. $exists = UserPeriodExchangePoints::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  371. 'USER_ID' => $userId,
  372. 'PERIOD_NUM' => $periodNum,
  373. ])->asArray()->exists();
  374. if( $exists ) {
  375. UserPeriodExchangePoints::updateAllCounters([
  376. 'EXCHANGE_POINTS' => $amount,
  377. 'REMAINDER_POINTS' => $amount,
  378. ], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  379. 'USER_ID' => $userId,
  380. 'PERIOD_NUM' => $periodNum,
  381. ]);
  382. }else {
  383. UserPeriodExchangePoints::insertOne([
  384. 'USER_ID' => $userId,
  385. 'PERIOD_NUM' => $periodNum,
  386. 'EXCHANGE_POINTS' => $amount,
  387. 'REMAINDER_POINTS' => $amount,
  388. 'EXPIRED' => 0,
  389. 'CREATED_AT' => Date::nowTime()
  390. ]);
  391. }
  392. return true;
  393. }
  394. /**
  395. * 减少
  396. * @param $userId
  397. * @param $amount
  398. * @return bool
  399. */
  400. public static function deductPeriodReconsumePoints($userId, $amount) {
  401. if( $amount <= 0 ) return false;
  402. $avalidList = UserPeriodPoints::find()->where('USER_ID=:USER_ID AND EXPIRED=:EXPIRED AND REMAINDER_POINTS>0', [
  403. 'USER_ID' => $userId,
  404. 'EXPIRED'=>0
  405. ])->orderBy('PERIOD_NUM ASC')->asArray()->all();
  406. if( !$avalidList ) return false;
  407. foreach ($avalidList as $everyData) {
  408. if( $amount <= 0 ) break;
  409. $remainderPoints = floatval($everyData['REMAINDER_POINTS']);
  410. if( $amount >= $remainderPoints ) {
  411. UserPeriodPoints::updateAllCounters([
  412. 'REMAINDER_POINTS' => (-1) * $remainderPoints
  413. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  414. $amount -= $remainderPoints;
  415. }else {
  416. UserPeriodPoints::updateAllCounters([
  417. 'REMAINDER_POINTS' => (-1) * $amount
  418. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  419. $amount = 0;
  420. }
  421. unset($everyData, $remainderPoints);
  422. }
  423. if( $amount > 0 ) return false;
  424. return true;
  425. }
  426. /**
  427. * 减少
  428. * @param $userId
  429. * @param $amount
  430. * @return bool
  431. */
  432. public static function deductPeriodExchangePoints($userId, $amount) {
  433. if( $amount <= 0 ) return false;
  434. $avalidList = UserPeriodExchangePoints::find()->where('USER_ID=:USER_ID AND EXPIRED=:EXPIRED AND REMAINDER_POINTS>0', [
  435. 'USER_ID' => $userId,
  436. 'EXPIRED'=>0
  437. ])->orderBy('PERIOD_NUM ASC')->asArray()->all();
  438. if( !$avalidList ) return false;
  439. foreach ($avalidList as $everyData) {
  440. if( $amount <= 0 ) break;
  441. $remainderPoints = floatval($everyData['REMAINDER_POINTS']);
  442. if( $amount >= $remainderPoints ) {
  443. UserPeriodExchangePoints::updateAllCounters([
  444. 'REMAINDER_POINTS' => (-1) * $remainderPoints
  445. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  446. $amount -= $remainderPoints;
  447. }else {
  448. UserPeriodExchangePoints::updateAllCounters([
  449. 'REMAINDER_POINTS' => (-1) * $amount
  450. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  451. $amount = 0;
  452. }
  453. unset($everyData, $remainderPoints);
  454. }
  455. if( $amount > 0 ) return false;
  456. return true;
  457. }
  458. /**
  459. * 冻结用户余额
  460. * @param $userId
  461. * @param $amount
  462. * @param null $remark
  463. * @param null $time
  464. * @return bool
  465. * @throws Exception
  466. * @throws \yii\db\Exception
  467. */
  468. public static function freezeUserBonus($userId, $amount, $remark = null, $time = null) {
  469. return self::changeFreezeUserBonus($userId, $amount, ['REMARK' => $remark, 'TIME' => $time]);
  470. }
  471. /**
  472. * 解冻用户余额
  473. * @param $userId
  474. * @param $amount
  475. * @param null $remark
  476. * @param null $time
  477. * @return bool
  478. * @throws Exception
  479. * @throws \yii\db\Exception
  480. */
  481. public static function unfreezeUserBonus($userId, $amount, $remark = null, $time = null) {
  482. return self::changeFreezeUserBonus($userId, -$amount, ['REMARK' => $remark, 'TIME' => $time]);
  483. }
  484. /**
  485. * @param $userId
  486. * @param $amount
  487. * @param $params
  488. * [
  489. * 'REMARK' => '备注',
  490. * 'PERIOD_NUM' => 100,
  491. * ]
  492. * @return bool
  493. * @throws Exception
  494. * @throws \yii\db\Exception
  495. */
  496. public static function changeFreezeUserBonus($userId, $amount, $params) {
  497. if ($amount == 0) return true;
  498. $period = Period::instance();
  499. if (!isset($params['PERIOD_NUM'])) {
  500. $periodNum = $period->getNowPeriodNum();
  501. } else {
  502. $periodNum = $params['PERIOD_NUM'];
  503. }
  504. $calcYearMonth = $period->getYearMonth($periodNum);
  505. // 改变冻结
  506. $oneUserBonusModel = UserBonus::findOne(['USER_ID' => $userId]);
  507. if ($oneUserBonusModel) {
  508. $oneUserBonusModel->BONUS_FREEZE = $oneUserBonusModel->BONUS_FREEZE + $amount;
  509. } else {
  510. $oneUserBonusModel = new UserBonus();
  511. $oneUserBonusModel->USER_ID = $userId;
  512. $oneUserBonusModel->BONUS_FREEZE = $amount;
  513. }
  514. if (!$oneUserBonusModel->save()) {
  515. throw new Exception(Form::formatErrorsForApi($oneUserBonusModel->getErrors()));
  516. }
  517. unset($oneUserBonusModel);
  518. // 流水
  519. // 获取发放完成的奖金信息
  520. $oneUserBonus = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
  521. // 记录流水
  522. $flowInsertData = [
  523. 'USER_ID' => $userId,
  524. 'AMOUNT' => abs($amount),
  525. 'TOTAL' => $oneUserBonus['BONUS'],
  526. 'IS_INCR' => $amount > 0 ? FlowBonus::INCR_FREEZE : FlowBonus::INCR_UNFREEZE,
  527. 'REMARK' => $params['REMARK'] ?? null,
  528. 'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
  529. 'CALC_MONTH' => $calcYearMonth,
  530. 'P_MONTH' => Date::ociToDate(),
  531. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  532. ];
  533. FlowBonus::insertOne($flowInsertData);
  534. unset($flowInsertData);
  535. return true;
  536. }
  537. /**
  538. * 清空会员奖金有流水
  539. * @param $userId
  540. * @param array $params
  541. * @throws Exception
  542. * @throws \yii\db\Exception
  543. */
  544. public static function clearAllBonus($userId, $params = []) {
  545. // 先查找会员的全部余额
  546. $userBonus = UserBonus::findOne(['USER_ID' => $userId]);
  547. // 如果没有会员余额数据,新建余额数据
  548. if (!$userBonus) {
  549. UserBonus::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
  550. } else {
  551. $period = Period::instance();
  552. foreach (\Yii::$app->params['bonusWalletType'] as $type) {
  553. $field = strtoupper($type['name']);
  554. if ($userBonus[$field]<=0) continue;
  555. $userInfo = Info::getLastInfo($userId);
  556. $flowInsertData = [
  557. 'USER_ID' => $userId,
  558. 'LAST_DEC_LV' => $userInfo['DEC_LV'],
  559. 'LAST_EMP_LV' => $userInfo['EMP_LV'],
  560. 'LAST_STATUS' => $userInfo['STATUS'],
  561. 'CALC_ID' => $params['CALC_ID'] ?? null,
  562. 'AMOUNT' => -$userBonus[$field],
  563. 'TOTAL' => 0,
  564. 'IS_INCR' => FlowBonus::INCR_REDUCE,
  565. 'REMARK' => $params['REMARK'] ?? null,
  566. 'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
  567. 'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $period->getNowPeriodNum(),
  568. 'CALC_MONTH' => $period->getNowYearMonth(),
  569. 'P_MONTH' => Date::ociToDate(),
  570. 'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
  571. 'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
  572. 'DEAL_TYPE_ID' => $params['DEAL_TYPE_ID'] ?? '',
  573. 'DEAL_TYPE_IS_PRESET' => $params['DEAL_TYPE_IS_PRESET'] ?? 1,
  574. 'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
  575. 'SORT' => $params['SORT'] ?? 0,
  576. ];
  577. // 流水
  578. if (strtolower($field) == 'bonus') FlowBonus::insertOne($flowInsertData);
  579. elseif (strtolower($field) == 'cf') {
  580. unset($flowInsertData['CALC_ID']);
  581. unset($flowInsertData['SORT']);
  582. unset($flowInsertData['TRANSFER_SN']);
  583. FlowCF::insertOne($flowInsertData);
  584. } elseif (strtolower($field) == 'lx') {
  585. unset($flowInsertData['CALC_ID']);
  586. unset($flowInsertData['SORT']);
  587. unset($flowInsertData['TRANSFER_SN']);
  588. FlowLX::insertOne($flowInsertData);
  589. }
  590. }
  591. // 清空
  592. $userBonus->BONUS = 0;
  593. $userBonus->CF = 0;
  594. $userBonus->LX = 0;
  595. if (!$userBonus->save()) {
  596. throw new Exception(Form::formatErrorsForApi($userBonus->getErrors()));
  597. }
  598. }
  599. FlowBonus::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  600. FlowCF::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  601. FlowLX::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  602. }
  603. /**
  604. * 是否存在奖金余额
  605. * @param $userId
  606. * @return bool
  607. */
  608. public static function hasBonus($userId) {
  609. $userBonus = UserBonus::findOne(['USER_ID' => $userId]);
  610. if (!$userBonus) {
  611. return false;
  612. }
  613. foreach (\Yii::$app->params['bonusWalletType'] as $type) {
  614. $field = strtoupper($type['name']);
  615. if (isset($userBonus[$field]) && $userBonus[$field] > 0) {
  616. return true;
  617. }
  618. }
  619. return false;
  620. }
  621. /**
  622. * 获取金额用于日志
  623. * @param $userId
  624. * @return array
  625. */
  626. public static function getLogData($userId){
  627. $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
  628. $cash = !empty($userWallet) ? $userWallet['CASH'] : '';
  629. $userName = Info::getUserNameByUserId($userId);
  630. $data = [];
  631. $data[$userId]['label'] = $userName.'余额';
  632. $data[$userId]['value'] = '奖金'.self::getAvailableBalance($userId).',现金'.$cash;
  633. return $data;
  634. }
  635. }