12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- <?php
- namespace app\common\service;
- use app\common\model\Accounts;
- use app\common\traits\ServiceTrait;
- use think\Log;
- use think\Db;
- class AccountService
- {
- use ServiceTrait;
- /** @var Accounts */
- public static $Model = Accounts::class;
- /**
- * 更新账户余额 正值为加,负值为减
- * @param $user_id
- * @param $amount
- * @param int|float $freeze
- * @param int $integral
- * @param int $credit_score
- * @param int $log_id
- * @return mixed
- * @throws \Exception
- */
- public static function updateData($user_id, $amount, $freeze = 0, int $credit_score = 0, int $integral = 0, int $log_id = 0)
- {
- $fields = [
- 'amount' => $amount,
- 'freeze' => $freeze,
- 'integral' => $integral,
- 'credit_score' => $credit_score,
- ];
- $where = ['user_id' => $user_id];
- $old_account = self::getOne($where);
- if (!$old_account) {
- exception('该账户未找到');
- }
- // 检查每个字段更新后是否为负值
- foreach ($fields as $field => $change) {
- if ($change < 0) {
- $current = $old_account->$field;
- $required = -$change;
- if ($current < $required) {
- $accountTypeName = AccountLogService::ACCOUNT_TYPE_MAP[$field] ?? '余额';
- Log::info(__CLASS__ . "账户{$accountTypeName}不足,更新失败: 当前={$current}, 扣除={$required}");
- exception("账户{$accountTypeName}不足");
- }
- }
- }
- // 构建要更新的字段
- $updateData = [];
- foreach ($fields as $field => $change) {
- if ($change != 0) {
- $updateData[$field] = Db::raw("{$field} + {$change}");
- }
- }
- $res = self::where($where)->update($updateData);
- if (!$res) {
- Log::info(__CLASS__ . ' 更新用户余额失败:' . json_encode($updateData, JSON_UNESCAPED_UNICODE));
- exception('更新用户余额失败');
- }
- //记录数据变动日志
- $now_account = self::getOne($where);
- DataLogService::addLog('accounts', 'account_logs', $log_id, $old_account->toArray(), $now_account->toArray());
- return $res;
- }
- /**
- * @param $demandId
- * @param $userId
- * @return void
- * @throws \Exception
- */
- public static function freezeAmountRefund($demandId, $userId)
- {
- $list = AccountLogService::where(['refer_id' => $demandId, 'user_id' => $userId, 'account_type' => AccountLogService::ACCOUNT_TYPE_FREEZE, 'type' => AccountLogService::TYPE_FREEZE, 'status' => CommonService::STATUS_OFF])->select();
- foreach ($list as $item) {
- $amount = $item->amount;
- $log_res = AccountLogService::addLog(AccountLogService::ACCOUNT_TYPE_FREEZE, $userId, $amount, '需求完成失败-冻结金额退回', AccountLogService::TYPE_FREEZE, 0, AccountLogService::INC_EXP_EXPEND, $demandId);
- //减去冻结
- AccountService::updateData($userId, 0, -$amount, 0, 0, $log_res->id);
- $item->status = CommonService::STATUS_ON;
- $saveRes = $item->save();
- if (!$saveRes) {
- exception('更新冻结余额日志失败');
- }
- }
- }
- }
|