seatonwan9
2025-08-15 c28a6afe1f87acecbe7aad4559a3842b1e3d5acb
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package com.webmanage.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.webmanage.common.BusinessException;
import com.webmanage.common.PageResult;
import com.webmanage.dto.AddPointsFlowDTO;
import com.webmanage.dto.PointsFlowQueryDTO;
import com.webmanage.emun.RuleTypeEnum;
import com.webmanage.entity.PointsFlow;
import com.webmanage.entity.PointsRule;
import com.webmanage.entity.UserPoints;
import com.webmanage.mapper.PointsFlowMapper;
import com.webmanage.mapper.UserPointsMapper;
import com.webmanage.service.PointsFlowService;
import com.webmanage.service.PointsRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 积分流水Service实现类
 */
@Slf4j
@Service
public class PointsFlowServiceImpl extends ServiceImpl<PointsFlowMapper, PointsFlow> implements PointsFlowService {
 
    @Resource
    private UserPointsMapper userPointsMapper;
 
    @Resource
    private PointsRuleService pointsRuleService;
 
    @Override
    public PageResult<PointsFlow> getPersonalPointsFlowPage(PointsFlowQueryDTO queryDTO) {
        if (queryDTO.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
 
        Page<PointsFlow> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", queryDTO.getUserId());
        
        buildQueryWrapper(wrapper, queryDTO);
        
        IPage<PointsFlow> result = page(page, wrapper);
        
        return new PageResult<PointsFlow>(
            result.getRecords(),
            result.getTotal(),
            queryDTO.getPageNum().longValue(),
            queryDTO.getPageSize().longValue(),
            result.getPages()
        );
    }
 
    @Override
    public PageResult<PointsFlow> getUnitPointsFlowPage(PointsFlowQueryDTO queryDTO) {
        if (queryDTO.getUnitId() == null) {
            throw new BusinessException("单位ID不能为空");
        }
 
        Page<PointsFlow> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("unit_id", queryDTO.getUnitId());
        
        buildQueryWrapper(wrapper, queryDTO);
        
        IPage<PointsFlow> result = page(page, wrapper);
        
        return new PageResult<PointsFlow>(
            result.getRecords(),
            result.getTotal(),
            queryDTO.getPageNum().longValue(),
            queryDTO.getPageSize().longValue(),
            result.getPages()
        );
    }
 
    @Override
    public List<PointsFlow> getPointsFlowByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("user_id", userId)
               .orderByDesc("created_at");
        
        return list(wrapper);
    }
 
    @Override
    public List<PointsFlow> getPointsFlowByUnitId(Long unitId) {
        if (unitId == null) {
            throw new BusinessException("单位ID不能为空");
        }
        
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("unit_id", unitId)
               .orderByDesc("created_at");
        
        return list(wrapper);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPointsFlowByRule(AddPointsFlowDTO addPointsFlowDTO) {
        if (addPointsFlowDTO == null) {
            throw new BusinessException("参数不能为空");
        }
 
        Long userId = addPointsFlowDTO.getUserId();
        Long unitId = addPointsFlowDTO.getUnitId();
        Integer ruleType = addPointsFlowDTO.getRuleType();
        String category = addPointsFlowDTO.getCategory();
        String ruleNameCode = addPointsFlowDTO.getRuleNameCode();
        Integer count = addPointsFlowDTO.getCount() != null ? addPointsFlowDTO.getCount() : 1;
 
        // 根据ruleType、ruleNameCode、category查询生效时间最新的积分规则
        PointsRule pointsRule = getLatestEffectiveRule(ruleType, ruleNameCode, category);
        if (pointsRule == null) {
            throw new BusinessException("积分规则不存在或未启用: ruleType=" + ruleType + ", ruleNameCode=" + ruleNameCode + ", category=" + category);
        }
 
        // 验证规则类型是否匹配
        if (!ruleType.equals(pointsRule.getRuleType())) {
            throw new BusinessException("规则类型不匹配,期望: " + pointsRule.getRuleType() + ",实际: " + ruleType);
        }
 
        // 计算积分值
        Integer basePoints = pointsRule.getPointsValue() != null ? pointsRule.getPointsValue() : 0;
        Integer totalPoints = basePoints * count;
 
        // 如果是消费类型,积分为负数
        if (ruleType == RuleTypeEnum.CONSUME.getCode()) { // 1表示消费类型
            totalPoints = -totalPoints;
        }
 
        // 检查每日积分上限
        if (pointsRule.getIsLimit() != null && pointsRule.getIsLimit() == 0) { // 0表示有每日上限
            checkDailyLimitByRule(userId, unitId, pointsRule, totalPoints);
        }
 
        // 如果是扣积分操作,先检查余额是否足够
        if (totalPoints < 0) {
            checkBalanceSufficient(userId, unitId, Math.abs(totalPoints));
        }
 
        // 创建积分流水记录
        PointsFlow pointsFlow = new PointsFlow();
        pointsFlow.setUserId(userId);
        pointsFlow.setUnitId(unitId);
        pointsFlow.setDataType(ruleType);
        pointsFlow.setDataCategory(addPointsFlowDTO.getCategory());
        pointsFlow.setPoints(totalPoints);
        pointsFlow.setName(addPointsFlowDTO.getDescription() != null ? addPointsFlowDTO.getDescription() : pointsRule.getRuleDescription());
        pointsFlow.setFlowTime(LocalDateTime.now());
        pointsFlow.setRlueId(pointsRule.getId());
 
        boolean saved = save(pointsFlow);
        if (!saved) {
            throw new BusinessException("保存积分流水失败");
        }
 
        // 更新用户积分账户
        updateUserPointsByRule(userId, unitId, totalPoints);
 
        return true;
    }
 
    @Override
    public UserPoints getUserPointsTotal(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为null");
        }
        
        QueryWrapper<UserPoints> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("user_id", userId);
        
        UserPoints userPoints = userPointsMapper.selectOne(wrapper);
        return userPoints ;
    }
 
    @Override
    public UserPoints getUnitPointsTotal(Long unitId) {
        if (unitId == null) {
            throw new BusinessException("用户ID不能为null");
        }
        
        QueryWrapper<UserPoints> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("unit_id", unitId);
        
        UserPoints userPoints = userPointsMapper.selectOne(wrapper);
        return userPoints;
    }
 
    @Override
    public List<String> getPointsFlowCategories() {
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT data_category")
               .isNotNull("data_category")
               .ne("data_category", "")
               .ne("data_category", "null")
               .eq("deleted", 0)
               .orderByAsc("data_category");
        
        List<PointsFlow> flows = list(wrapper);
        return flows.stream()
                .map(PointsFlow::getDataCategory)
                .filter(category -> category != null && !category.trim().isEmpty())
                .distinct()
                .sorted()
                .collect(Collectors.toList());
    }
 
    /**
     * 构建查询条件
     */
    private void buildQueryWrapper(QueryWrapper<PointsFlow> wrapper, PointsFlowQueryDTO queryDTO) {
        if(StringUtils.hasText(queryDTO.getDataCategory())){
            wrapper.eq("data_category", queryDTO.getDataCategory());
        }
        if (queryDTO.getDataType()!=null) {
            wrapper.eq("data_type", queryDTO.getDataType());
        }
        if (StringUtils.hasText(queryDTO.getPointsSource())) {
            wrapper.eq("points_source", queryDTO.getPointsSource());
        }
        if (StringUtils.hasText(queryDTO.getOrderId())) {
            wrapper.eq("order_id", queryDTO.getOrderId());
        }
        if (queryDTO.getFlowEndTime() != null) {
            wrapper.ge("flow_time", queryDTO.getFlowStartTime());
        }
        if (queryDTO.getFlowEndTime() != null) {
            wrapper.le("flow_time", queryDTO.getFlowEndTime());
        }
        
        wrapper.orderByDesc("flow_time");
    }
 
    /**
     * 根据ruleType、ruleNameCode、category查询生效时间最新的积分规则
     */
    private PointsRule getLatestEffectiveRule(Integer ruleType, String ruleNameCode, String category) {
        QueryWrapper<PointsRule> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("is_enabled", 0) // 0表示启用
               .eq("rule_type", ruleType)
               .eq("rule_name_code", ruleNameCode)
               .eq("category", category)
               .orderByDesc("created_at") // 按创建时间倒序,获取最新的规则
               .last("LIMIT 1");
        
        return pointsRuleService.getOne(wrapper);
    }
 
    /**
     * 检查每日积分上限(基于规则)
     */
    private void checkDailyLimitByRule(Long userId, Long unitId, PointsRule pointsRule, Integer currentPoints) {
        // 获取今日开始和结束时间
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(23, 59, 59);
 
        // 查询今日该规则的积分流水
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("user_id", userId)
               .eq("unit_id", unitId)
//               .eq("data_category", pointsRule.getRuleName())
                .eq("rule_id",pointsRule.getId())
               .ge("flow_time", startOfDay)
               .le("flow_time", endOfDay);
 
        List<PointsFlow> todayFlows = list(wrapper);
        
        // 计算今日累计积分
        int todayTotal = todayFlows.stream()
                .mapToInt(flow -> flow.getPoints() != null ? flow.getPoints() : 0)
                .sum();
 
        // 获取规则的每日积分上限
        Integer dailyLimit = pointsRule.getDailyLimit();
        if (dailyLimit != null && dailyLimit > 0) {
            // 如果今日累计积分超过每日上限,则抛出异常
            if (Math.abs(todayTotal) >= dailyLimit) {
                throw new BusinessException("今日该规则积分已达上限: " + dailyLimit);
            }
            
            // 如果加上当前积分会超过每日上限,则抛出异常
            if (Math.abs(todayTotal + currentPoints) > dailyLimit) {
                throw new BusinessException("本次积分操作将超过每日上限: " + dailyLimit + ",当前已累计: " + Math.abs(todayTotal));
            }
        }
    }
 
    /**
     * 检查积分余额是否足够
     */
    private void checkBalanceSufficient(Long userId, Long unitId, Integer requiredPoints) {
        // 检查个人积分余额
        QueryWrapper<UserPoints> userWrapper = new QueryWrapper<>();
        userWrapper.eq("deleted", 0)
                  .eq("user_id", userId);
        
        UserPoints userPoints = userPointsMapper.selectOne(userWrapper);
        if (userPoints == null || userPoints.getBalance() < requiredPoints) {
            throw new BusinessException("个人积分余额不足,当前余额: " + (userPoints != null ? userPoints.getBalance() : 0) + ",需要扣除: " + requiredPoints);
        }
 
        // 检查单位积分余额
        QueryWrapper<UserPoints> unitWrapper = new QueryWrapper<>();
        unitWrapper.eq("deleted", 0)
                  .eq("unit_id", unitId);
        
        UserPoints unitPoints = userPointsMapper.selectOne(unitWrapper);
        if (unitPoints == null || unitPoints.getBalance() < requiredPoints) {
            throw new BusinessException("单位积分余额不足,当前余额: " + (unitPoints != null ? unitPoints.getBalance() : 0) + ",需要扣除: " + requiredPoints);
        }
    }
 
    /**
     * 检查每日积分上限(旧方法,保留兼容性)
     */
    private void checkDailyLimit(Long userId, Long unitId, String ruleName, Integer currentPoints, Integer priority) {
        // 获取今日开始和结束时间
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(23, 59, 59);
 
        // 查询今日该规则的积分流水
        QueryWrapper<PointsFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0)
               .eq("user_id", userId)
               .eq("unit_id", unitId)
               .eq("data_category", ruleName)
               .ge("flow_time", startOfDay)
               .le("flow_time", endOfDay);
 
        List<PointsFlow> todayFlows = list(wrapper);
        
        // 计算今日累计积分
        int todayTotal = todayFlows.stream()
                .mapToInt(flow -> flow.getPoints() != null ? flow.getPoints() : 0)
                .sum();
 
        // 如果今日累计积分超过优先级限制,则抛出异常
        if (Math.abs(todayTotal) >= priority) {
            throw new BusinessException("今日该规则积分已达上限: " + priority);
        }
    }
 
    /**
     * 更新用户积分
     */
    private void updateUserPoints(Long userId, Long unitId, Integer pointsValue) {
        // 更新个人积分
        QueryWrapper<UserPoints> userWrapper = new QueryWrapper<>();
        userWrapper.eq("deleted", 0)
                  .eq("user_id", userId);
        
        UserPoints userPoints = userPointsMapper.selectOne(userWrapper);
        if (userPoints == null) {
            userPoints = new UserPoints();
            userPoints.setUserId(userId);
            userPoints.setUnitId(unitId);
            userPoints.setBalance(pointsValue);
            userPointsMapper.insert(userPoints);
        } else {
            userPoints.setBalance(userPoints.getBalance() + pointsValue);
            userPoints.setUpdateTime(LocalDateTime.now());
            userPointsMapper.updateById(userPoints);
        }
 
        // 更新单位积分
        QueryWrapper<UserPoints> unitWrapper = new QueryWrapper<>();
        unitWrapper.eq("deleted", 0)
                  .eq("unit_id", unitId);
        
        UserPoints unitPoints = userPointsMapper.selectOne(unitWrapper);
        if (unitPoints == null) {
            unitPoints = new UserPoints();
            unitPoints.setUserId(userId);
            unitPoints.setUnitId(unitId);
            unitPoints.setBalance(pointsValue);
            userPointsMapper.insert(unitPoints);
        } else {
            unitPoints.setBalance(unitPoints.getBalance() + pointsValue);
            unitPoints.setUpdateTime(LocalDateTime.now());
            userPointsMapper.updateById(unitPoints);
        }
    }
 
    /**
     * 根据规则更新用户积分账户
     */
    private void updateUserPointsByRule(Long userId, Long unitId, Integer pointsValue) {
        // 更新个人积分账户
        QueryWrapper<UserPoints> userWrapper = new QueryWrapper<>();
        userWrapper.eq("deleted", 0)
                  .eq("user_id", userId);
        
        UserPoints userPoints = userPointsMapper.selectOne(userWrapper);
        if (userPoints == null) {
            // 如果是新用户且是扣积分操作,余额不足
            if (pointsValue < 0) {
                throw new BusinessException("积分余额不足,无法扣除积分");
            }
            
            userPoints = new UserPoints();
            userPoints.setUserId(userId);
            userPoints.setUnitId(unitId);
            userPoints.setBalance(pointsValue);
            userPoints.setTotalEarned(pointsValue > 0 ? pointsValue : 0);
            userPoints.setTotalConsumed(pointsValue < 0 ? Math.abs(pointsValue) : 0);
            userPointsMapper.insert(userPoints);
        } else {
            // 检查扣积分时余额是否足够
            if (pointsValue < 0 && userPoints.getBalance() + pointsValue < 0) {
                throw new BusinessException("积分余额不足,当前余额: " + userPoints.getBalance() + ",需要扣除: " + Math.abs(pointsValue));
            }
            
            userPoints.setBalance(userPoints.getBalance() + pointsValue);
            
            // 更新累计获取积分
            if (pointsValue > 0) {
                userPoints.setTotalEarned(userPoints.getTotalEarned() != null ? 
                    userPoints.getTotalEarned() + pointsValue : pointsValue);
            }
            
            // 更新累计消耗积分
            if (pointsValue < 0) {
                userPoints.setTotalConsumed(userPoints.getTotalConsumed() != null ? 
                    userPoints.getTotalConsumed() + Math.abs(pointsValue) : Math.abs(pointsValue));
            }
            
            userPoints.setUpdateTime(LocalDateTime.now());
            userPointsMapper.updateById(userPoints);
        }
 
        // 更新单位积分账户
        QueryWrapper<UserPoints> unitWrapper = new QueryWrapper<>();
        unitWrapper.eq("deleted", 0)
                  .eq("unit_id", unitId);
        
        UserPoints unitPoints = userPointsMapper.selectOne(unitWrapper);
        if (unitPoints == null) {
            // 如果是新单位且是扣积分操作,余额不足
            if (pointsValue < 0) {
                throw new BusinessException("单位积分余额不足,无法扣除积分");
            }
            
            unitPoints = new UserPoints();
            unitPoints.setUserId(userId);
            unitPoints.setUnitId(unitId);
            unitPoints.setBalance(pointsValue);
            unitPoints.setTotalEarned(pointsValue > 0 ? pointsValue : 0);
            unitPoints.setTotalConsumed(pointsValue < 0 ? Math.abs(pointsValue) : 0);
            userPointsMapper.insert(unitPoints);
        } else {
            // 检查扣积分时余额是否足够
            if (pointsValue < 0 && unitPoints.getBalance() + pointsValue < 0) {
                throw new BusinessException("单位积分余额不足,当前余额: " + unitPoints.getBalance() + ",需要扣除: " + Math.abs(pointsValue));
            }
            
            unitPoints.setBalance(unitPoints.getBalance() + pointsValue);
            
            // 更新累计获取积分
            if (pointsValue > 0) {
                unitPoints.setTotalEarned(unitPoints.getTotalEarned() != null ? 
                    unitPoints.getTotalEarned() + pointsValue : pointsValue);
            }
            
            // 更新累计消耗积分
            if (pointsValue < 0) {
                unitPoints.setTotalConsumed(unitPoints.getTotalConsumed() != null ? 
                    unitPoints.getTotalConsumed() + Math.abs(pointsValue) : Math.abs(pointsValue));
            }
            
            unitPoints.setUpdateTime(LocalDateTime.now());
            userPointsMapper.updateById(unitPoints);
        }
    }
}