liujie
2026-08-21 a7c8a8f6055e1a03414f2227d12ff2e87ec52d41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.tourguide.modules.finance.service;
 
import com.tourguide.common.exception.BusinessException;
import com.tourguide.modules.user.mapper.GuideUserMapper;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
 
/** 统一读取和原子变更导游可提现余额。 */
@Service
public class GuideWithdrawableBalanceService {
    private final GuideUserMapper guideUserMapper;
 
    public GuideWithdrawableBalanceService(GuideUserMapper guideUserMapper) {
        this.guideUserMapper = guideUserMapper;
    }
 
    public BigDecimal getAvailableAmount(Long guideId) {
        return money(guideUserMapper.selectBalance(guideId));
    }
 
    public boolean debit(Long guideId, BigDecimal amount) {
        BigDecimal value = money(amount);
        return value.signum() > 0 && guideUserMapper.decreaseBalance(guideId, value) == 1;
    }
 
    public void credit(Long guideId, BigDecimal amount) {
        BigDecimal value = money(amount);
        if (value.signum() == 0) return;
        if (value.signum() < 0 || guideUserMapper.increaseBalance(guideId, value) != 1) {
            throw new BusinessException(500, "导游余额更新失败");
        }
    }
 
    private BigDecimal money(BigDecimal value) {
        return (value == null ? BigDecimal.ZERO : value).setScale(2, RoundingMode.HALF_UP);
    }
}