huminmin
13 小时以前 189fe18f9aaabc39cc4bb4cc00f531bc43fe152e
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
package com.ruoyi.sales.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.ruoyi.approve.bean.dto.ApprovalInstanceDto;
import com.ruoyi.approve.mapper.ApprovalTemplateMapper;
import com.ruoyi.approve.pojo.ApprovalTemplate;
import com.ruoyi.approve.pojo.ApproveProcess;
import com.ruoyi.approve.service.ApprovalInstanceService;
import com.ruoyi.approve.service.impl.ApproveProcessServiceImpl;
import com.ruoyi.basic.enums.ApplicationTypeEnum;
import com.ruoyi.basic.enums.RecordTypeEnum;
import com.ruoyi.basic.utils.FileUtil;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.enums.StockOutQualifiedRecordTypeEnum;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.procurementrecord.bean.vo.ShippingProductVo;
import com.ruoyi.procurementrecord.utils.StockUtils;
import com.ruoyi.sales.dto.ShippingApproveDto;
import com.ruoyi.sales.dto.ShippingInfoDto;
import com.ruoyi.sales.dto.ShippingProductDetailDto;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.mapper.ShippingInfoMapper;
import com.ruoyi.sales.mapper.ShippingProductDetailMapper;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.sales.pojo.ShippingInfo;
import com.ruoyi.sales.pojo.ShippingProductDetail;
import com.ruoyi.sales.service.ShippingInfoService;
import com.ruoyi.stock.dto.StockInventoryDto;
import com.ruoyi.stock.dto.StockUninventoryDto;
import com.ruoyi.stock.service.StockInventoryService;
import com.ruoyi.stock.service.StockUninventoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.time.LocalDateTime;
import java.util.List;
 
/**
 * @author :yys
 * @date : 2025/10/22 9:33
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ShippingInfoServiceImpl extends ServiceImpl<ShippingInfoMapper, ShippingInfo> implements ShippingInfoService {
 
 
    private final ShippingInfoMapper shippingInfoMapper;
 
 
    private final SalesLedgerProductMapper salesLedgerProductMapper;
 
    private final StockUtils stockUtils;
 
    private final CommonFileServiceImpl commonFileService;
 
    private final ApproveProcessServiceImpl approveProcessService;
    private final FileUtil fileUtil;
    private final ShippingProductDetailMapper shippingProductDetailMapper;
    private final ApprovalTemplateMapper approvalTemplateMapper;
    private final ApprovalInstanceService approvalInstanceService;
    private final StockInventoryService stockInventoryService;
    private final StockUninventoryService stockUninventoryService;
 
    @Override
    public IPage<ShippingInfoDto> listPage(Page page, ShippingInfo req) {
        IPage<ShippingInfoDto> listPage = shippingInfoMapper.listPage(page, req);
        listPage.getRecords().forEach(item -> {
            item.setStorageBlobVOs(fileUtil.getStorageBlobVOsByApplicationAndRecordTypeAndRecordId(ApplicationTypeEnum.IMAGE, RecordTypeEnum.SHIPPING_INFO, item.getId()));
        });
        return listPage;
    }
 
    @Override
    public boolean deductStock(ShippingInfoDto req) {
        ShippingInfo byId = this.getById(req.getId());
        if (byId == null) {
            throw new RuntimeException("发货信息不存在");
        }
        //扣减库存
        if (!"已发货".equals(byId.getStatus())) {
            List<ShippingProductDetail> shippingProductDetails = shippingProductDetailMapper.selectList(new LambdaQueryWrapper<ShippingProductDetail>().eq(ShippingProductDetail::getShippingInfoId, req.getId()));
            if (CollectionUtils.isEmpty(shippingProductDetails)) {
                throw new RuntimeException("发货信息不存在");
            }
            for (ShippingProductDetail shippingProductDetail : shippingProductDetails) {
                addShippingStockOutRecord(shippingProductDetail, req.getId());
            }
        }
        byId.setExpressNumber(req.getExpressNumber());
        byId.setExpressCompany(req.getExpressCompany());
        byId.setStatus("已发货");
        byId.setShippingCarNumber(req.getShippingCarNumber());
        byId.setShippingDate(req.getShippingDate());
        boolean update = this.updateById(byId);
        // 保存文件
        fileUtil.saveStorageAttachment(ApplicationTypeEnum.IMAGE, RecordTypeEnum.SHIPPING_INFO, req.getId(), req.getStorageBlobDTOs());
        return update;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(List<Long> ids) {
        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
                .in(ShippingInfo::getId, ids));
        if (CollectionUtils.isEmpty(shippingInfos)) return false;
        // 只有待审核状态才能删除
        boolean allPending = shippingInfos.stream().allMatch(s -> "待审核".equals(s.getStatus()));
        if (!allPending) throw new RuntimeException("只有待审核状态才能删除");
        // 删除附件
        commonFileService.deleteByBusinessIds(ids, FileNameType.SHIP.getValue());
        // 删除发货审批
        if (CollectionUtils.isNotEmpty(shippingInfos)) {
            for (ShippingInfo shippingInfo : shippingInfos) {
                List<ApproveProcess> one = approveProcessService.list(new LambdaQueryWrapper<ApproveProcess>()
                        .like(ApproveProcess::getApproveReason, shippingInfo.getShippingNo()));
                if (one != null) {
                    List<Long> list = one.stream().map(ApproveProcess::getId).toList();
                    approveProcessService.delByIds(list);
                }
                // 扣已发货库存
                stockUtils.deleteStockOutRecord(shippingInfo.getId(), StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode());
            }
        }
        //删除发货明细
        shippingProductDetailMapper.delete(new LambdaQueryWrapper<ShippingProductDetail>().in(ShippingProductDetail::getShippingInfoId, ids));
 
        return this.removeByIds(ids);
    }
 
    @Override
    public List<ShippingProductVo> getReturnManagementDtoById(Long shippingId) {
        return shippingInfoMapper.getReturnManagementDtoById(shippingId);
 
    }
 
    @Override
    public List<ShippingInfo> getShippingInfoByCustomerName(String customerName) {
        return shippingInfoMapper.getShippingInfoByCustomerName(customerName);
    }
 
    @Override
    public boolean add(ShippingInfoDto req) {
        String ledgerStockType = resolveLedgerStockType(req.getSalesLedgerProductId());
        this.save(req);
        req.getBatchNoDetailList().forEach(item -> {
            item.setShippingInfoId(req.getId());
            item.setStockType(ledgerStockType);
        });
        shippingProductDetailMapper.insert(req.getBatchNoDetailList());
        // 保存文件
        fileUtil.saveStorageAttachment(ApplicationTypeEnum.IMAGE, RecordTypeEnum.SHIPPING_INFO, req.getId(), req.getStorageBlobDTOs());
        return true;
    }
 
    @Override
    public List<ShippingProductDetailDto> getDetail(Long id) {
        return shippingProductDetailMapper.getDetail(id);
    }
 
    @Override
    public ShippingApproveDto getDateilByShippingNo(String shippingNo) {
        ShippingApproveDto shippingApproveDto = new ShippingApproveDto();
        ShippingInfo shippingInfo = new ShippingInfo();
        shippingInfo.setShippingNo(shippingNo);
        shippingApproveDto.setShippingInfo(shippingInfoMapper.listPage(new Page(1, -1), shippingInfo).getRecords().get(0));
        List<ShippingProductDetailDto> dateilByShippingNo = shippingProductDetailMapper.getDateilByShippingNo(shippingNo);
        shippingApproveDto.setShippingProductDetailDtoList(dateilByShippingNo);
        return shippingApproveDto;
    }
 
    @Override
    public boolean addReq(ShippingInfoDto req) {
 
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String sh = OrderUtils.countTodayByCreateTime(shippingInfoMapper, "SH","shipping_no",req.getCreateTime());
        // 先保存发货单,再发起审批;无审核人自动通过时需要按发货编号回写发货状态。
        req.setShippingNo(sh);
        req.setStatus("待审核");
        boolean save = this.add(req);
        // 发货审批
        ApprovalInstanceDto approvalInstance = new ApprovalInstanceDto();
        approvalInstance.setTemplateId(approvalTemplateMapper.selectOne(new LambdaQueryWrapper<ApprovalTemplate>().eq(ApprovalTemplate::getBusinessType,7L).orderByDesc(ApprovalTemplate::getId).last("LIMIT 1")).getId());
        approvalInstance.setTemplateName(approvalTemplateMapper.selectOne(new LambdaQueryWrapper<ApprovalTemplate>().eq(ApprovalTemplate::getBusinessType,7L).orderByDesc(ApprovalTemplate::getId).last("LIMIT 1")).getTemplateName());
        approvalInstance.setBusinessId(req.getId());
        approvalInstance.setBusinessType(7L);
        approvalInstance.setCurrentLevel(1);
        approvalInstance.setTitle(sh);
        approvalInstance.setApplicantId(loginUser.getUserId());
        approvalInstance.setApplicantName(loginUser.getNickName());
        approvalInstance.setApplyTime(LocalDateTime.now());
        approvalInstanceService.add(approvalInstance);
        return true;
    }
 
    private void addShippingStockOutRecord(ShippingProductDetail shippingProductDetail, Long shippingInfoId) {
        ShippingInfo shippingInfo = this.getById(shippingInfoId);
        String stockType = resolveLedgerStockType(shippingInfo != null ? shippingInfo.getSalesLedgerProductId() : null);
        if (stockType == null) {
            stockType = normalizeStockType(shippingProductDetail.getStockType());
        }
        String detailStockType = normalizeStockType(shippingProductDetail.getStockType());
        if (detailStockType != null && stockType != null && !stockType.equals(detailStockType)) {
            throw new RuntimeException("发货明细库存类型与销售台账产品库存类型不一致");
        }
        if ("waste".equals(stockType)) {
            StockUninventoryDto stockUninventoryDto = new StockUninventoryDto();
            stockUninventoryDto.setRecordId(shippingInfoId);
            stockUninventoryDto.setRecordType(StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode());
            stockUninventoryDto.setQualitity(shippingProductDetail.getQuantity());
            stockUninventoryDto.setProductModelId(shippingProductDetail.getProductModelId());
            stockUninventoryDto.setBatchNo(normalizeBatchNo(shippingProductDetail.getBatchNo()));
            stockUninventoryDto.setType("waste");
            stockUninventoryService.addStockOutRecordOnly(stockUninventoryDto);
            return;
        }
        if (!"qualified".equals(stockType)) {
            throw new RuntimeException("发货明细库存类型无效,只支持 qualified 或 waste");
        }
        StockInventoryDto stockInventoryDto = new StockInventoryDto();
        stockInventoryDto.setRecordId(shippingInfoId);
        stockInventoryDto.setRecordType(StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode());
        stockInventoryDto.setQualitity(shippingProductDetail.getQuantity());
        stockInventoryDto.setProductModelId(shippingProductDetail.getProductModelId());
        stockInventoryDto.setBatchNo(normalizeBatchNo(shippingProductDetail.getBatchNo()));
        stockInventoryService.addStockOutRecordOnly(stockInventoryDto);
    }
 
    private String normalizeBatchNo(String batchNo) {
        if (batchNo == null) {
            return null;
        }
        String normalized = batchNo.trim();
        return normalized.isEmpty() ? null : normalized;
    }
 
    private String normalizeStockType(String stockType) {
        if (stockType == null) {
            return null;
        }
        String normalized = stockType.trim().toLowerCase();
        if (normalized.isEmpty()) {
            return null;
        }
        if ("unqualified".equals(normalized)) {
            return "waste";
        }
        return normalized;
    }
 
    private String resolveLedgerStockType(Long salesLedgerProductId) {
        if (salesLedgerProductId == null) {
            return null;
        }
        SalesLedgerProduct salesLedgerProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
        if (salesLedgerProduct == null) {
            throw new RuntimeException("销售台账产品不存在");
        }
        String stockType = normalizeStockType(salesLedgerProduct.getStockType());
        return stockType == null ? "qualified" : stockType;
    }
}