gaoluyang
2026-11-02 9e9f0e2d9f6fcce7dcea88b181b3c7e6069e8a1b
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
package cn.iocoder.yudao.module.hrm.service.supply;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyAlertRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyIssuePageReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyIssueRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyIssueSaveReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyPageReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyPurchasePageReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyPurchaseRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyPurchaseSaveReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplyRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.supply.vo.HrmSupplySaveReqVO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.supply.HrmSupplyDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.supply.HrmSupplyIssueDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.supply.HrmSupplyPurchaseDO;
import cn.iocoder.yudao.module.hrm.dal.mysql.supply.HrmSupplyIssueMapper;
import cn.iocoder.yudao.module.hrm.dal.mysql.supply.HrmSupplyMapper;
import cn.iocoder.yudao.module.hrm.dal.mysql.supply.HrmSupplyPurchaseMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
 
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.*;
 
/**
 * 办公用品管理 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class HrmSupplyServiceImpl implements HrmSupplyService {
 
    /** 领用状态:待审批 */
    private static final Integer ISSUE_STATUS_PENDING = 1;
    /** 领用状态:已通过 */
    private static final Integer ISSUE_STATUS_APPROVED = 2;
    /** 领用状态:已驳回 */
    private static final Integer ISSUE_STATUS_REJECTED = 3;
    /** 领用状态:已发放 */
    private static final Integer ISSUE_STATUS_ISSUED = 4;
 
    /** 预警类型:低于库存下限 */
    private static final Integer WARNING_BELOW_MIN = 1;
    /** 预警类型:高于库存上限 */
    private static final Integer WARNING_ABOVE_MAX = 2;
 
    @Resource
    private HrmSupplyMapper supplyMapper;
    @Resource
    private HrmSupplyPurchaseMapper supplyPurchaseMapper;
    @Resource
    private HrmSupplyIssueMapper supplyIssueMapper;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DeptApi deptApi;
 
    @Override
    public Long createSupply(HrmSupplySaveReqVO createReqVO) {
        validateCodeUnique(null, createReqVO.getCode());
        HrmSupplyDO supply = BeanUtils.toBean(createReqVO, HrmSupplyDO.class);
        if (supply.getStockQuantity() == null) {
            supply.setStockQuantity(0);
        }
        supplyMapper.insert(supply);
        return supply.getId();
    }
 
    @Override
    public void updateSupply(HrmSupplySaveReqVO updateReqVO) {
        validateSupplyExists(updateReqVO.getId());
        validateCodeUnique(updateReqVO.getId(), updateReqVO.getCode());
        HrmSupplyDO updateObj = BeanUtils.toBean(updateReqVO, HrmSupplyDO.class);
        // 当前库存只能通过「采购入库」「领用发放」变更,档案编辑不覆盖库存
        updateObj.setStockQuantity(null);
        supplyMapper.updateById(updateObj);
    }
 
    @Override
    public void deleteSupply(Long id) {
        HrmSupplyDO supply = validateSupplyExists(id);
        Long purchaseCount = supplyPurchaseMapper.selectCountBySupplyId(id);
        if (purchaseCount != null && purchaseCount > 0) {
            throw exception(SUPPLY_DELETE_FAIL_HAS_PURCHASE, supply.getName(), purchaseCount);
        }
        Long issueCount = supplyIssueMapper.selectCountBySupplyId(id);
        if (issueCount != null && issueCount > 0) {
            throw exception(SUPPLY_DELETE_FAIL_HAS_ISSUE, supply.getName(), issueCount);
        }
        supplyMapper.deleteById(id);
    }
 
    @Override
    public HrmSupplyDO getSupply(Long id) {
        return supplyMapper.selectById(id);
    }
 
    @Override
    public PageResult<HrmSupplyRespVO> getSupplyPage(HrmSupplyPageReqVO pageReqVO) {
        PageResult<HrmSupplyDO> pageResult = supplyMapper.selectPage(pageReqVO);
        return BeanUtils.toBean(pageResult, HrmSupplyRespVO.class);
    }
 
    @Override
    public List<HrmSupplyDO> getSupplyList() {
        return supplyMapper.selectEnabledList();
    }
 
    @Override
    public List<HrmSupplyAlertRespVO> getSupplyAlertList() {
        List<HrmSupplyDO> list = supplyMapper.selectEnabledList();
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<HrmSupplyAlertRespVO> alertList = new ArrayList<>();
        for (HrmSupplyDO supply : list) {
            Integer stock = supply.getStockQuantity() != null ? supply.getStockQuantity() : 0;
            Integer warningType = null;
            if (supply.getMinQuantity() != null && stock <= supply.getMinQuantity()) {
                warningType = WARNING_BELOW_MIN;
            } else if (supply.getMaxQuantity() != null && stock >= supply.getMaxQuantity()) {
                warningType = WARNING_ABOVE_MAX;
            }
            if (warningType == null) {
                continue;
            }
            HrmSupplyAlertRespVO alert = BeanUtils.toBean(supply, HrmSupplyAlertRespVO.class);
            alert.setWarningType(warningType);
            alertList.add(alert);
        }
        // 先低于下限、再高于上限,便于优先处理缺货
        alertList.sort((a, b) -> {
            int byType = Integer.compare(a.getWarningType(), b.getWarningType());
            if (byType != 0) {
                return byType;
            }
            return StrUtil.compare(a.getName(), b.getName(), true);
        });
        return alertList;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSupplyPurchase(HrmSupplyPurchaseSaveReqVO createReqVO) {
        HrmSupplyDO supply = validateSupplyExists(createReqVO.getSupplyId());
        Integer quantity = createReqVO.getQuantity();
        if (quantity == null || quantity <= 0) {
            throw exception(SUPPLY_PURCHASE_QUANTITY_INVALID, quantity);
        }
        if (createReqVO.getPrice() != null && createReqVO.getPrice().signum() < 0) {
            throw exception(SUPPLY_PURCHASE_PRICE_INVALID, createReqVO.getPrice());
        }
        // 1. 写入采购记录:金额 = 数量 × 单价
        HrmSupplyPurchaseDO purchase = BeanUtils.toBean(createReqVO, HrmSupplyPurchaseDO.class);
        if (purchase.getPurchaseTime() == null) {
            purchase.setPurchaseTime(LocalDateTime.now());
        }
        if (createReqVO.getPrice() != null) {
            purchase.setTotalPrice(createReqVO.getPrice().multiply(BigDecimal.valueOf(quantity)));
        }
        supplyPurchaseMapper.insert(purchase);
        // 2. 累加当前库存
        int newStock = (supply.getStockQuantity() != null ? supply.getStockQuantity() : 0) + quantity;
        supplyMapper.update(null, new LambdaUpdateWrapper<HrmSupplyDO>()
                .eq(HrmSupplyDO::getId, supply.getId())
                .set(HrmSupplyDO::getStockQuantity, newStock)
                .set(HrmSupplyDO::getUpdateTime, LocalDateTime.now()));
        return purchase.getId();
    }
 
    @Override
    public PageResult<HrmSupplyPurchaseRespVO> getSupplyPurchasePage(HrmSupplyPurchasePageReqVO pageReqVO) {
        PageResult<HrmSupplyPurchaseDO> pageResult = supplyPurchaseMapper.selectPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        List<HrmSupplyPurchaseRespVO> list = BeanUtils.toBean(pageResult.getList(), HrmSupplyPurchaseRespVO.class);
        Map<Long, HrmSupplyDO> supplyMap = getSupplyMap(collectIds(list, HrmSupplyPurchaseRespVO::getSupplyId));
        list.forEach(vo -> {
            HrmSupplyDO supply = supplyMap.get(vo.getSupplyId());
            if (supply != null) {
                vo.setSupplyCode(supply.getCode());
                vo.setSupplyName(supply.getName());
                vo.setUnit(supply.getUnit());
            }
        });
        return new PageResult<>(list, pageResult.getTotal());
    }
 
    @Override
    public Long createSupplyIssue(HrmSupplyIssueSaveReqVO createReqVO) {
        validateSupplyExists(createReqVO.getSupplyId());
        Integer quantity = createReqVO.getQuantity();
        if (quantity == null || quantity <= 0) {
            throw exception(SUPPLY_ISSUE_QUANTITY_INVALID, quantity);
        }
        HrmSupplyIssueDO issue = BeanUtils.toBean(createReqVO, HrmSupplyIssueDO.class);
        issue.setStatus(ISSUE_STATUS_PENDING);
        issue.setApproveUserId(null);
        issue.setApproveTime(null);
        issue.setApproveRemark(null);
        issue.setIssueTime(null);
        supplyIssueMapper.insert(issue);
        return issue.getId();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approveSupplyIssue(Long id, Boolean approve, String remark) {
        HrmSupplyIssueDO issue = validateSupplyIssueExists(id);
        HrmSupplyDO supply = supplyMapper.selectById(issue.getSupplyId());
        if (!ISSUE_STATUS_PENDING.equals(issue.getStatus())) {
            throw exception(SUPPLY_ISSUE_APPROVE_FAIL,
                    supply != null ? supply.getName() : "ID=" + issue.getSupplyId(),
                    issueStatusLabel(issue.getStatus()));
        }
        HrmSupplyIssueDO updateObj = new HrmSupplyIssueDO();
        updateObj.setId(id);
        updateObj.setStatus(Boolean.TRUE.equals(approve) ? ISSUE_STATUS_APPROVED : ISSUE_STATUS_REJECTED);
        updateObj.setApproveUserId(SecurityFrameworkUtils.getLoginUserId());
        updateObj.setApproveTime(LocalDateTime.now());
        updateObj.setApproveRemark(remark);
        supplyIssueMapper.updateById(updateObj);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void issueSupply(Long id) {
        HrmSupplyIssueDO issue = validateSupplyIssueExists(id);
        HrmSupplyDO supply = validateSupplyExists(issue.getSupplyId());
        if (!ISSUE_STATUS_APPROVED.equals(issue.getStatus())) {
            throw exception(SUPPLY_ISSUE_ISSUE_FAIL,
                    supply.getName(), issueStatusLabel(issue.getStatus()));
        }
        // 1. 校验库存
        int stock = supply.getStockQuantity() != null ? supply.getStockQuantity() : 0;
        int quantity = issue.getQuantity() != null ? issue.getQuantity() : 0;
        String unit = StrUtil.blankToDefault(supply.getUnit(), "件");
        if (stock < quantity) {
            throw exception(SUPPLY_ISSUE_STOCK_NOT_ENOUGH,
                    supply.getName(), quantity, unit, stock, unit);
        }
        // 2. 扣减库存
        supplyMapper.update(null, new LambdaUpdateWrapper<HrmSupplyDO>()
                .eq(HrmSupplyDO::getId, supply.getId())
                .set(HrmSupplyDO::getStockQuantity, stock - quantity)
                .set(HrmSupplyDO::getUpdateTime, LocalDateTime.now()));
        // 3. 更新领用申请为已发放
        HrmSupplyIssueDO updateObj = new HrmSupplyIssueDO();
        updateObj.setId(id);
        updateObj.setStatus(ISSUE_STATUS_ISSUED);
        updateObj.setIssueTime(LocalDateTime.now());
        supplyIssueMapper.updateById(updateObj);
    }
 
    @Override
    public PageResult<HrmSupplyIssueRespVO> getSupplyIssuePage(HrmSupplyIssuePageReqVO pageReqVO) {
        PageResult<HrmSupplyIssueDO> pageResult = supplyIssueMapper.selectPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        List<HrmSupplyIssueRespVO> list = BeanUtils.toBean(pageResult.getList(), HrmSupplyIssueRespVO.class);
        Set<Long> userIds = new HashSet<>();
        userIds.addAll(collectIds(list, HrmSupplyIssueRespVO::getUserId));
        userIds.addAll(collectIds(list, HrmSupplyIssueRespVO::getApproveUserId));
        Map<Long, AdminUserRespDTO> userMap = getUserMap(userIds);
        Map<Long, DeptRespDTO> deptMap = getDeptMap(collectIds(list, HrmSupplyIssueRespVO::getDeptId));
        Map<Long, HrmSupplyDO> supplyMap = getSupplyMap(collectIds(list, HrmSupplyIssueRespVO::getSupplyId));
        list.forEach(vo -> {
            HrmSupplyDO supply = supplyMap.get(vo.getSupplyId());
            if (supply != null) {
                vo.setSupplyCode(supply.getCode());
                vo.setSupplyName(supply.getName());
                vo.setUnit(supply.getUnit());
            }
            AdminUserRespDTO user = userMap.get(vo.getUserId());
            if (user != null) {
                vo.setUserName(user.getNickname());
            }
            AdminUserRespDTO approveUser = userMap.get(vo.getApproveUserId());
            if (approveUser != null) {
                vo.setApproveUserName(approveUser.getNickname());
            }
            DeptRespDTO dept = deptMap.get(vo.getDeptId());
            if (dept != null) {
                vo.setDeptName(dept.getName());
            }
        });
        return new PageResult<>(list, pageResult.getTotal());
    }
 
    // ==================== 校验与辅助方法 ====================
 
    private HrmSupplyDO validateSupplyExists(Long id) {
        HrmSupplyDO supply = id != null ? supplyMapper.selectById(id) : null;
        if (supply == null) {
            throw exception(SUPPLY_NOT_EXISTS, id);
        }
        return supply;
    }
 
    private HrmSupplyIssueDO validateSupplyIssueExists(Long id) {
        HrmSupplyIssueDO issue = id != null ? supplyIssueMapper.selectById(id) : null;
        if (issue == null) {
            throw exception(SUPPLY_ISSUE_NOT_EXISTS, id);
        }
        return issue;
    }
 
    private void validateCodeUnique(Long id, String code) {
        HrmSupplyDO supply = supplyMapper.selectByCode(code);
        if (supply != null && !Objects.equals(supply.getId(), id)) {
            throw exception(SUPPLY_CODE_DUPLICATED, code);
        }
    }
 
    private Map<Long, HrmSupplyDO> getSupplyMap(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        List<HrmSupplyDO> list = supplyMapper.selectBatchIds(ids);
        Map<Long, HrmSupplyDO> map = new HashMap<>(list.size());
        list.forEach(item -> map.put(item.getId(), item));
        return map;
    }
 
    private Map<Long, AdminUserRespDTO> getUserMap(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        return adminUserApi.getUserMap(ids);
    }
 
    private Map<Long, DeptRespDTO> getDeptMap(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        return deptApi.getDeptMap(ids);
    }
 
    private static <T> Set<Long> collectIds(Collection<T> list, Function<T, Long> getter) {
        Set<Long> ids = new HashSet<>();
        list.forEach(item -> {
            Long id = getter.apply(item);
            if (id != null) {
                ids.add(id);
            }
        });
        return ids;
    }
 
    private static String issueStatusLabel(Integer status) {
        if (ISSUE_STATUS_PENDING.equals(status)) {
            return "待审批";
        }
        if (ISSUE_STATUS_APPROVED.equals(status)) {
            return "已通过";
        }
        if (ISSUE_STATUS_REJECTED.equals(status)) {
            return "已驳回";
        }
        if (ISSUE_STATUS_ISSUED.equals(status)) {
            return "已发放";
        }
        return "未知状态(ID=" + status + ")";
    }
 
}