package com.yeshi.makemoney.app.service.impl.money;
|
|
import com.ks.lib.common.exception.ParamsException;
|
import com.yeshi.makemoney.app.dao.money.UserMoneyBalanceMapper;
|
import com.yeshi.makemoney.app.entity.money.UserMoneyBalance;
|
import com.yeshi.makemoney.app.entity.money.UserMoneyRecord;
|
import com.yeshi.makemoney.app.exception.money.ExtractException;
|
import com.yeshi.makemoney.app.exception.money.UserMoneyBalanceException;
|
import com.yeshi.makemoney.app.service.inter.money.UserMoneyRecordService;
|
import com.yeshi.makemoney.app.service.inter.money.UserMoneyService;
|
import org.springframework.stereotype.Service;
|
import org.springframework.transaction.annotation.Transactional;
|
|
import javax.annotation.Resource;
|
import java.math.BigDecimal;
|
import java.util.Date;
|
|
@Service
|
public class UserMoneyServiceImpl implements UserMoneyService {
|
|
@Resource
|
private UserMoneyBalanceMapper userMoneyBalanceMapper;
|
|
@Resource
|
private UserMoneyRecordService userMoneyRecordService;
|
|
|
@Override
|
public void init(Long uid) {
|
UserMoneyBalance balance = userMoneyBalanceMapper.selectByPrimaryKeyForUpdate(uid);
|
if (balance != null) {
|
return;
|
}
|
balance = new UserMoneyBalance();
|
balance.setCreateTime(new Date());
|
balance.setMoney(new BigDecimal(0));
|
balance.setId(uid);
|
userMoneyBalanceMapper.insertSelective(balance);
|
}
|
|
@Override
|
public BigDecimal getBalance(Long uid) {
|
UserMoneyBalance balance = userMoneyBalanceMapper.selectByPrimaryKey(uid);
|
if (balance == null) {
|
return new BigDecimal(0);
|
}
|
return balance.getMoney();
|
}
|
|
|
@Transactional(rollbackFor = Exception.class)
|
@Override
|
public void subUserMoney(UserMoneyRecord record) throws ParamsException, UserMoneyBalanceException {
|
userMoneyRecordService.add(record);
|
UserMoneyBalance balance = userMoneyBalanceMapper.selectByPrimaryKeyForUpdate(record.getUser().getId());
|
if (balance == null || balance.getMoney() == null || balance.getMoney().compareTo(record.getMoney().abs()) < 0) {
|
throw new UserMoneyBalanceException(UserMoneyBalanceException.CODE_BALANCE_NOT_ENOUGH, "账户余额不足");
|
}
|
//添加到提现记录,并扣除账户余额
|
userMoneyBalanceMapper.subMoney(record.getUser().getId(), record.getMoney().abs());
|
}
|
|
@Transactional(rollbackFor = Exception.class)
|
@Override
|
public void addUserMoney(UserMoneyRecord record) throws ParamsException {
|
userMoneyRecordService.add(record);
|
//用户余额上锁
|
UserMoneyBalance balance = userMoneyBalanceMapper.selectByPrimaryKeyForUpdate(record.getUser().getId());
|
if (balance == null) {
|
init(record.getUser().getId());
|
balance = userMoneyBalanceMapper.selectByPrimaryKeyForUpdate(record.getUser().getId());
|
}
|
userMoneyBalanceMapper.addMoney(record.getUser().getId(), record.getMoney().abs());
|
}
|
}
|