tuqin
2026-11-03 9494075e6d9d2a4b2b884b4ed740dee0c434734c
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
package cn.iocoder.yudao.module.trade.service.foreign;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.api.storage.StorageAttachmentApi;
import cn.iocoder.yudao.module.system.api.storage.dto.StorageBlobRespDTO;
import cn.iocoder.yudao.module.trade.controller.admin.foreign.vo.TradeForeignDocumentSaveReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.foreign.vo.TradeForeignRequiredDocRespVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.foreign.TradeForeignDocumentDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.foreign.TradeForeignOrderDO;
import cn.iocoder.yudao.module.trade.dal.mysql.foreign.TradeForeignDocumentMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.foreign.TradeForeignOrderMapper;
import cn.iocoder.yudao.module.trade.enums.foreign.TradeForeignDeliveryModeEnum;
import cn.iocoder.yudao.module.trade.enums.foreign.TradeForeignDocTypeEnum;
import cn.iocoder.yudao.module.trade.enums.foreign.TradeForeignOrderStatusEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
 
import java.util.*;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.FOREIGN_ORDER_NOT_APPROVED_FOR_DOC;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.FOREIGN_ORDER_NOT_EXISTS;
 
/**
 * 外贸订单单据 Service 实现类
 *
 * @author mom
 */
@Service
@Validated
public class TradeForeignDocumentServiceImpl implements TradeForeignDocumentService {
 
    /** 统一附件区:application / recordType(与外贸订单附件一致) */
    private static final String ATTACHMENT_APPLICATION = "file";
    private static final String ATTACHMENT_RECORD_TYPE = "trade_foreign_order";
 
    /** 各出货模式的必填单据类型 */
    private static final Map<Integer, Set<String>> REQUIRED_DOCS = new HashMap<>();
 
    static {
        REQUIRED_DOCS.put(TradeForeignDeliveryModeEnum.FACTORY_DIRECT.getMode(),
                new LinkedHashSet<>(Arrays.asList(
                        TradeForeignDocTypeEnum.CONTRACT.getType(),
                        TradeForeignDocTypeEnum.PACKING_LIST.getType(),
                        TradeForeignDocTypeEnum.PRODUCT_OUTBOUND.getType())));
        REQUIRED_DOCS.put(TradeForeignDeliveryModeEnum.PORT_PREPARE.getMode(),
                new LinkedHashSet<>(Arrays.asList(
                        TradeForeignDocTypeEnum.CONTRACT.getType(),
                        TradeForeignDocTypeEnum.PACKING_LIST.getType(),
                        TradeForeignDocTypeEnum.PORT_INBOUND.getType())));
    }
 
    /** 需「审批通过」才能登记的单据类型(报关/出运资料) */
    private static final Set<String> APPROVAL_REQUIRED_DOCS = new HashSet<>(Arrays.asList(
            TradeForeignDocTypeEnum.CUSTOMS_DECLARATION.getType(),
            TradeForeignDocTypeEnum.RELEASE_NOTICE.getType(),
            TradeForeignDocTypeEnum.EXPORT_INVOICE.getType(),
            TradeForeignDocTypeEnum.PACKING_LIST.getType(),
            TradeForeignDocTypeEnum.PRODUCT_OUTBOUND.getType()));
 
    @Resource
    private TradeForeignDocumentMapper documentMapper;
    @Resource
    private TradeForeignOrderMapper orderMapper;
    @Resource
    private StorageAttachmentApi storageAttachmentApi;
 
    @Override
    public Long addDocument(TradeForeignDocumentSaveReqVO reqVO) {
        TradeForeignOrderDO order = orderMapper.selectById(reqVO.getOrderId());
        if (order == null) {
            throw exception(FOREIGN_ORDER_NOT_EXISTS);
        }
        // 需求2:审批通过后才可登记报关/出运资料
        if (APPROVAL_REQUIRED_DOCS.contains(reqVO.getDocType())
                && !TradeForeignOrderStatusEnum.APPROVED.getStatus().equals(order.getStatus())
                && !TradeForeignOrderStatusEnum.COMPLETED.getStatus().equals(order.getStatus())) {
            throw exception(FOREIGN_ORDER_NOT_APPROVED_FOR_DOC, order.getNo());
        }
        TradeForeignDocumentDO document = BeanUtils.toBean(reqVO, TradeForeignDocumentDO.class);
        documentMapper.insert(document);
        // 统一附件区:把文件追加绑定到订单附件(recordType=trade_foreign_order),与表单附件区共用一处。
        // 注意 bindAttachments 是「整体替换」语义,需带上订单已有附件,避免覆盖其它已登记单据的附件
        if (reqVO.getBlobId() != null) {
            List<Long> blobIds = new ArrayList<>();
            List<StorageBlobRespDTO> existing = storageAttachmentApi.listAttachments(ATTACHMENT_RECORD_TYPE, reqVO.getOrderId());
            if (CollUtil.isNotEmpty(existing)) {
                existing.forEach(blob -> {
                    if (blob.getId() != null) {
                        blobIds.add(blob.getId());
                    }
                });
            }
            if (!blobIds.contains(reqVO.getBlobId())) {
                blobIds.add(reqVO.getBlobId());
            }
            storageAttachmentApi.bindAttachments(ATTACHMENT_APPLICATION, ATTACHMENT_RECORD_TYPE, reqVO.getOrderId(), blobIds);
        }
        return document.getId();
    }
 
    @Override
    public List<TradeForeignDocumentDO> getDocumentListByOrderId(Long orderId) {
        List<TradeForeignDocumentDO> documents = documentMapper.selectListByOrderId(orderId);
        if (CollUtil.isEmpty(documents)) {
            return documents;
        }
        // 从统一附件区回填文件 url/name(登记时仅保存了 blobId)
        Map<Long, StorageBlobRespDTO> blobMap = buildAttachmentBlobMap(orderId);
        for (TradeForeignDocumentDO document : documents) {
            StorageBlobRespDTO blob = blobMap.get(document.getBlobId());
            if (blob == null) {
                continue;
            }
            if (StrUtil.isBlank(document.getUrl())) {
                document.setUrl(blob.getUrl());
            }
            if (StrUtil.isBlank(document.getName())) {
                document.setName(blob.getName());
            }
        }
        return documents;
    }
 
    private Map<Long, StorageBlobRespDTO> buildAttachmentBlobMap(Long orderId) {
        Map<Long, StorageBlobRespDTO> map = new HashMap<>();
        List<StorageBlobRespDTO> blobs = storageAttachmentApi.listAttachments(ATTACHMENT_RECORD_TYPE, orderId);
        if (CollUtil.isEmpty(blobs)) {
            return map;
        }
        for (StorageBlobRespDTO blob : blobs) {
            if (blob.getId() != null) {
                map.putIfAbsent(blob.getId(), blob);
            }
        }
        return map;
    }
 
    @Override
    public List<TradeForeignRequiredDocRespVO> getRequiredDocs(Long orderId) {
        TradeForeignOrderDO order = orderMapper.selectById(orderId);
        if (order == null) {
            throw exception(FOREIGN_ORDER_NOT_EXISTS);
        }
        Set<String> required = requiredTypes(order.getDeliveryMode());
        Set<String> uploaded = new HashSet<>();
        for (TradeForeignDocumentDO doc : documentMapper.selectListByOrderId(orderId)) {
            uploaded.add(doc.getDocType());
        }
        List<TradeForeignRequiredDocRespVO> result = new ArrayList<>();
        for (TradeForeignDocTypeEnum type : TradeForeignDocTypeEnum.values()) {
            TradeForeignRequiredDocRespVO vo = new TradeForeignRequiredDocRespVO();
            vo.setDocType(type.getType());
            vo.setDocName(type.getName());
            vo.setRequired(required.contains(type.getType()));
            vo.setUploaded(uploaded.contains(type.getType()));
            result.add(vo);
        }
        return result;
    }
 
    @Override
    public List<String> getMissingRequiredDocNames(Long orderId, boolean excludeApprovalRequired) {
        TradeForeignOrderDO order = orderMapper.selectById(orderId);
        if (order == null) {
            throw exception(FOREIGN_ORDER_NOT_EXISTS);
        }
        Set<String> required = requiredTypes(order.getDeliveryMode());
        if (excludeApprovalRequired) {
            required.removeAll(APPROVAL_REQUIRED_DOCS);
        }
        if (required.isEmpty()) {
            return Collections.emptyList();
        }
        Set<String> uploaded = new HashSet<>();
        for (TradeForeignDocumentDO doc : documentMapper.selectListByOrderId(orderId)) {
            uploaded.add(doc.getDocType());
        }
        return collectMissingNames(required, uploaded);
    }
 
    @Override
    public Map<Long, List<String>> getMissingRequiredDocNamesByOrderIds(Collection<Long> orderIds) {
        Map<Long, List<String>> result = new HashMap<>();
        if (CollUtil.isEmpty(orderIds)) {
            return result;
        }
        Map<Long, Set<String>> uploadedMap = new HashMap<>();
        for (TradeForeignDocumentDO doc : documentMapper.selectListByOrderIds(orderIds)) {
            uploadedMap.computeIfAbsent(doc.getOrderId(), k -> new HashSet<>()).add(doc.getDocType());
        }
        for (TradeForeignOrderDO order : orderMapper.selectBatchIds(orderIds)) {
            Set<String> required = requiredTypes(order.getDeliveryMode());
            Set<String> uploaded = uploadedMap.getOrDefault(order.getId(), Collections.emptySet());
            result.put(order.getId(), collectMissingNames(required, uploaded));
        }
        return result;
    }
 
    /** 复制出货模式对应的必填单据集合(保持顺序,避免污染静态常量) */
    private Set<String> requiredTypes(Integer deliveryMode) {
        return new LinkedHashSet<>(REQUIRED_DOCS.getOrDefault(deliveryMode, Collections.emptySet()));
    }
 
    private List<String> collectMissingNames(Set<String> required, Set<String> uploaded) {
        List<String> missing = new ArrayList<>();
        for (String type : required) {
            if (!uploaded.contains(type)) {
                missing.add(TradeForeignDocTypeEnum.getNameByType(type));
            }
        }
        return missing;
    }
 
}