Balance.php 25 KB

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