需求:每個加分項有累計上限,申請時預判斷是否超限並提示。雙端校驗策略:
const MAX = 100, PER_TIME = 3;
let current = getCurrentScore(); // 從頁面數據或 AJAX 獲取
if (current >= MAX) {
showToast('已達上限 100 分,無法申請');
disableApplyBtn();
} else if (current > MAX - PER_TIME) {
showConfirm(`本次僅能加 ${MAX - current} 分(將達上限),確定申請?`);
} else {
enableApplyBtn(); // 正常可加 3 分
}
@Transactional
public Result applyBonus(Long studentId, Long itemId) {
BonusItem item = itemRepo.findById(itemId);
int current = scoreRepo.sumByStudentAndItem(studentId, itemId);
if (current >= item.getMaxScore())
return Result.fail("已達上限");
if (current + item.getPerScore() > item.getMaxScore())
return Result.fail("超出上限,可加 " + (item.getMaxScore() - current) + " 分");
scoreRepo.save(new ScoreRecord(studentId, itemId, item.getPerScore()));
return Result.ok();
}