gaoluyang
2 天以前 8c65f898ed6e5b0c7a94c792c4562f6ec831dccd
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
package cn.iocoder.yudao.module.crm.service.quotation;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.service.definition.BpmCategoryService;
import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService;
import cn.iocoder.yudao.module.crm.controller.admin.contract.vo.contract.CrmContractSaveReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.quotation.vo.CrmSaleQuotationPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.quotation.vo.CrmSaleQuotationSaveReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.contract.CrmContractDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.quotation.CrmSaleQuotationDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.quotation.CrmSaleQuotationProductDO;
import cn.iocoder.yudao.module.crm.dal.mysql.quotation.CrmSaleQuotationMapper;
import cn.iocoder.yudao.module.crm.dal.mysql.quotation.CrmSaleQuotationProductMapper;
import cn.iocoder.yudao.module.crm.dal.redis.no.CrmNoRedisDAO;
import cn.iocoder.yudao.module.crm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.crm.enums.permission.CrmPermissionLevelEnum;
import cn.iocoder.yudao.module.crm.enums.quotation.CrmSaleQuotationStatusEnum;
import cn.iocoder.yudao.module.crm.service.business.CrmBusinessService;
import cn.iocoder.yudao.module.crm.service.contact.CrmContactService;
import cn.iocoder.yudao.module.crm.service.contract.CrmContractService;
import cn.iocoder.yudao.module.crm.service.customer.CrmCustomerService;
import cn.iocoder.yudao.module.crm.api.customer.CrmCustomerApi;
import cn.iocoder.yudao.module.crm.service.permission.CrmPermissionService;
import cn.iocoder.yudao.module.crm.service.permission.bo.CrmPermissionCreateReqBO;
import cn.iocoder.yudao.module.system.api.storage.StorageAttachmentApi;
import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi;
import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
 
import java.math.BigDecimal;
import java.util.*;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.*;
 
/**
 * CRM 销售报价单 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@Slf4j
public class CrmSaleQuotationServiceImpl implements CrmSaleQuotationService {
 
    /**
     * BPM 销售报价审批分类编码
     */
    private static final String SALE_QUOTATION_APPROVE_CATEGORY_CODE = "sale_quotation_approve";
 
    @Resource
    private CrmSaleQuotationMapper saleQuotationMapper;
    @Resource
    private CrmSaleQuotationProductMapper saleQuotationProductMapper;
 
    @Resource
    private CrmNoRedisDAO noRedisDAO;
 
    @Resource
    private MdmItemApi mdmItemApi;
 
    @Resource
    private CrmCustomerService customerService;
    @Resource
    private CrmCustomerApi customerApi;
    @Resource
    private CrmBusinessService businessService;
    @Resource
    private CrmContactService contactService;
    @Resource
    private CrmPermissionService permissionService;
    @Resource
    private StorageAttachmentApi storageAttachmentApi;
    @Resource
    private CrmContractService contractService;
 
    @Resource
    private BpmProcessInstanceApi bpmProcessInstanceApi;
    @Resource
    private BpmCategoryService bpmCategoryService;
    @Resource
    private BpmProcessDefinitionService bpmProcessDefinitionService;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSaleQuotation(CrmSaleQuotationSaveReqVO createReqVO, Long userId) {
        // 1.1 校验物料项的有效性
        List<CrmSaleQuotationProductDO> quotationProducts = validateQuotationItems(createReqVO.getItems());
        // 1.2 确定报价单号(前端填写则用自定义单号,留空则自动生成),并校验唯一性
        String customNo = StrUtil.trim(createReqVO.getNo());
        String no = StrUtil.isBlank(customNo)
                ? noRedisDAO.generate(CrmNoRedisDAO.SALE_QUOTATION_NO_PREFIX) : customNo;
        validateQuotationNoUnique(no, null);
        // 1.3 校验关联字段
        validateRelationDataExists(createReqVO);
 
        // 2.1 插入报价单
        CrmSaleQuotationDO saleQuotation = BeanUtils.toBean(createReqVO, CrmSaleQuotationDO.class, q -> q
                .setNo(no)
                .setStatus(CrmSaleQuotationStatusEnum.DRAFT.getStatus()));
        calculateTotalPrice(saleQuotation, quotationProducts);
        saleQuotationMapper.insert(saleQuotation);
        // 2.2 插入报价明细
        quotationProducts.forEach(p -> p.setQuotationId(saleQuotation.getId()));
        saleQuotationProductMapper.insertBatch(quotationProducts);
        // 2.3 创建数据权限
        permissionService.createPermission(new CrmPermissionCreateReqBO()
                .setUserId(userId)
                .setBizType(CrmBizTypeEnum.CRM_SALE_QUOTATION.getType())
                .setBizId(saleQuotation.getId())
                .setLevel(CrmPermissionLevelEnum.OWNER.getLevel()));
        storageAttachmentApi.bindAttachments("file", "crm_sale_quotation",
                saleQuotation.getId(), createReqVO.getBlobIds());
        return saleQuotation.getId();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleQuotation(CrmSaleQuotationSaveReqVO updateReqVO) {
        // 1.1 校验存在
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(updateReqVO.getId());
        // 1.2 校验状态,只有草稿状态才能修改
        if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())) {
            throw exception(SALE_QUOTATION_UPDATE_FAIL_NOT_DRAFT, saleQuotation.getNo());
        }
        // 1.3 校验物料项的有效性
        List<CrmSaleQuotationProductDO> quotationProducts = validateQuotationItems(updateReqVO.getItems());
        // 1.4 校验关联字段
        validateRelationDataExists(updateReqVO);
 
        // 2.1 更新报价单(报价单号留空表示保持原值,填写则校验唯一性后替换)
        CrmSaleQuotationDO updateObj = BeanUtils.toBean(updateReqVO, CrmSaleQuotationDO.class);
        String no = StrUtil.trim(updateReqVO.getNo());
        if (StrUtil.isBlank(no)) {
            updateObj.setNo(saleQuotation.getNo());
        } else {
            validateQuotationNoUnique(no, saleQuotation.getId());
            updateObj.setNo(no);
        }
        calculateTotalPrice(updateObj, quotationProducts);
        saleQuotationMapper.updateById(updateObj);
        // 2.2 更新报价明细
        updateQuotationProductList(updateReqVO.getId(), quotationProducts);
        storageAttachmentApi.updateAttachments("file", "crm_sale_quotation", updateReqVO.getId(), updateReqVO.getBlobIds());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSaleQuotation(List<Long> ids) {
        // 1. 校验不处于非草稿状态
        List<CrmSaleQuotationDO> saleQuotations = saleQuotationMapper.selectByIds(ids);
        if (CollUtil.isEmpty(saleQuotations)) {
            return;
        }
        saleQuotations.forEach(saleQuotation -> {
            if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())) {
                throw exception(SALE_QUOTATION_DELETE_FAIL_NOT_DRAFT, saleQuotation.getNo());
            }
        });
 
        // 2. 遍历删除
        saleQuotations.forEach(saleQuotation -> {
            // 2.0 删除附件关联
            storageAttachmentApi.deleteAttachmentsByRecord("crm_sale_quotation", saleQuotation.getId());
            // 2.1 删除报价单
            saleQuotationMapper.deleteById(saleQuotation.getId());
            // 2.2 删除报价明细
            saleQuotationProductMapper.deleteByQuotationId(saleQuotation.getId());
            // 2.3 删除数据权限
            permissionService.deletePermission(CrmBizTypeEnum.CRM_SALE_QUOTATION.getType(), saleQuotation.getId());
        });
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitSaleQuotation(Long id, String processDefinitionKey, Long userId) {
        // 1. 校验报价单存在且为草稿状态
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id);
        if (ObjUtil.notEqual(saleQuotation.getStatus(), CrmSaleQuotationStatusEnum.DRAFT.getStatus())) {
            throw exception(SALE_QUOTATION_SUBMIT_FAIL_NOT_DRAFT, saleQuotation.getNo());
        }
 
        // 2. 全局免审批:直接置为审批通过,无需流程模型
        if (bpmProcessInstanceApi.isGlobalAutoApprove()) {
            saleQuotationMapper.updateById(new CrmSaleQuotationDO().setId(id).setProcessInstanceId("")
                    .setStatus(CrmSaleQuotationStatusEnum.PROCESS.getStatus()));
            updateSaleQuotationAuditStatus(id, BpmProcessInstanceStatusEnum.APPROVE.getStatus());
            return;
        }
 
        // 3. 校验审批分类和流程定义
        validateSaleQuotationApproveCategoryAndProcessDefinition();
        ProcessDefinition processDefinition = bpmProcessDefinitionService.getActiveProcessDefinition(processDefinitionKey);
        if (processDefinition == null) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
 
        // 4. 创建审批流程实例
        String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO()
                .setProcessDefinitionKey(processDefinitionKey).setBusinessKey(String.valueOf(id)));
 
        // 5. 更新流程实例编号和状态
        saleQuotationMapper.updateById(new CrmSaleQuotationDO().setId(id).setProcessInstanceId(processInstanceId)
                .setStatus(CrmSaleQuotationStatusEnum.PROCESS.getStatus()));
    }
 
    @Override
    public void updateSaleQuotationAuditStatus(Long id, Integer bpmResult) {
        // 1.1 校验报价单是否存在
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id);
        // 1.2 只有审批中,才可以更新审批结果
        if (ObjUtil.notEqual(saleQuotation.getStatus(), CrmSaleQuotationStatusEnum.PROCESS.getStatus())) {
            log.error("[updateSaleQuotationAuditStatus][报价单({}) 不处于审批中,无法更新审批结果({})]",
                    saleQuotation.getNo(), bpmResult);
            throw exception(SALE_QUOTATION_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS, saleQuotation.getNo());
        }
 
        // 2. 转换 BPM 审批结果并更新
        Integer status;
        if (ObjUtil.equal(bpmResult, BpmProcessInstanceStatusEnum.APPROVE.getStatus())) {
            status = CrmSaleQuotationStatusEnum.APPROVE.getStatus();
        } else if (ObjUtil.equal(bpmResult, BpmProcessInstanceStatusEnum.REJECT.getStatus())) {
            status = CrmSaleQuotationStatusEnum.REJECT.getStatus();
        } else if (ObjUtil.equal(bpmResult, BpmProcessInstanceStatusEnum.CANCEL.getStatus())) {
            status = CrmSaleQuotationStatusEnum.CANCEL.getStatus();
        } else {
            log.warn("[updateSaleQuotationAuditStatus][报价单({}) 收到未知审批结果({}),忽略]", id, bpmResult);
            return;
        }
        saleQuotationMapper.updateById(new CrmSaleQuotationDO().setId(id).setStatus(status));
    }
 
    @Override
    public List<Map<String, Object>> getSaleQuotationApproveProcessDefinitionList() {
        validateSaleQuotationApproveCategoryAndProcessDefinition();
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(SALE_QUOTATION_APPROVE_CATEGORY_CODE);
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        // 只保留激活状态,且相同 key 只保留最新版本
        Map<String, ProcessDefinition> latestVersionMap = new HashMap<>();
        for (ProcessDefinition pd : processDefinitions) {
            if (pd.isSuspended()) {
                continue;
            }
            ProcessDefinition existing = latestVersionMap.get(pd.getKey());
            if (existing == null || pd.getVersion() > existing.getVersion()) {
                latestVersionMap.put(pd.getKey(), pd);
            }
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (ProcessDefinition pd : latestVersionMap.values()) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", pd.getId());
            item.put("key", pd.getKey());
            item.put("name", pd.getName());
            item.put("version", pd.getVersion());
            result.add(item);
        }
        return result;
    }
 
    /**
     * 校验 BPM 销售报价审批分类和流程定义是否存在
     */
    private void validateSaleQuotationApproveCategoryAndProcessDefinition() {
        List<String> codes = Collections.singletonList(SALE_QUOTATION_APPROVE_CATEGORY_CODE);
        Map<String, ?> categoryMap = bpmCategoryService.getCategoryMap(codes);
        if (!categoryMap.containsKey(SALE_QUOTATION_APPROVE_CATEGORY_CODE)) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(SALE_QUOTATION_APPROVE_CATEGORY_CODE);
        if (CollUtil.isEmpty(definitionInfoList)) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        boolean hasActiveDefinition = processDefinitions.stream().anyMatch(pd -> !pd.isSuspended());
        if (!hasActiveDefinition) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
    }
 
    private CrmSaleQuotationDO validateSaleQuotationExists(Long id) {
        CrmSaleQuotationDO saleQuotation = saleQuotationMapper.selectById(id);
        if (saleQuotation == null) {
            throw exception(SALE_QUOTATION_NOT_EXISTS);
        }
        return saleQuotation;
    }
 
    /**
     * 校验报价单号唯一(含已逻辑删除的报价单,因 uk_no 唯一索引覆盖已删除行)
     *
     * @param no       报价单号
     * @param selfId   自身编号(修改时排除自己,新增传 null)
     */
    private void validateQuotationNoUnique(String no, Long selfId) {
        CrmSaleQuotationDO exists = saleQuotationMapper.selectAnyByNo(no);
        if (exists != null && !exists.getId().equals(selfId)) {
            throw exception(SALE_QUOTATION_NO_EXISTS, no);
        }
    }
 
    private List<CrmSaleQuotationProductDO> validateQuotationItems(List<CrmSaleQuotationSaveReqVO.Item> list) {
        // 1. 校验物料存在且启用
        Set<Long> itemIds = convertSet(list, CrmSaleQuotationSaveReqVO.Item::getItemId);
        Map<Long, MdmItemRespDTO> itemMap = mdmItemApi.getItemMap(itemIds);
        // 2. 转换为 CrmSaleQuotationProductDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, CrmSaleQuotationProductDO.class, item -> {
            MdmItemRespDTO mdmItem = itemMap.get(item.getItemId());
            if (mdmItem == null) {
                throw exception(SALE_QUOTATION_ITEM_NOT_EXISTS);
            }
            item.setItemUnitId(mdmItem.getUnitMeasureId());
            // 物料原价,如果 MDM 中没有则默认为 0
            item.setItemPrice(mdmItem.getSalesPrice() != null ? mdmItem.getSalesPrice() : BigDecimal.ZERO);
            if (item.getQuotationPrice() != null && item.getCount() != null) {
                item.setTotalPrice(MoneyUtils.priceMultiply(item.getQuotationPrice(), item.getCount()));
                if (item.getTaxPercent() != null) {
                    item.setTaxPrice(MoneyUtils.priceMultiplyPercent(item.getTotalPrice(), item.getTaxPercent()));
                }
            }
        }));
    }
 
    private void validateRelationDataExists(CrmSaleQuotationSaveReqVO reqVO) {
        // 1. 校验客户
        customerService.validateCustomer(reqVO.getCustomerId());
        // 2. 校验商机(可选)
        if (reqVO.getBusinessId() != null) {
            businessService.validateBusiness(reqVO.getBusinessId());
        }
        // 3. 校验联系人(可选)
        if (reqVO.getContactId() != null) {
            contactService.validateContact(reqVO.getContactId());
        }
    }
 
    private void updateQuotationProductList(Long id, List<CrmSaleQuotationProductDO> newList) {
        // 第一步,对比新老数据,获得添加、修改、删除的列表
        List<CrmSaleQuotationProductDO> oldList = saleQuotationProductMapper.selectListByQuotationId(id);
        List<List<CrmSaleQuotationProductDO>> diffList = diffList(oldList, newList,
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));
 
        // 第二步,批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setQuotationId(id));
            saleQuotationProductMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            saleQuotationProductMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            saleQuotationProductMapper.deleteByIds(convertList(diffList.get(2), CrmSaleQuotationProductDO::getId));
        }
    }
 
    private void calculateTotalPrice(CrmSaleQuotationDO saleQuotation, List<CrmSaleQuotationProductDO> items) {
        saleQuotation.setTotalProductPrice(getSumValue(items, CrmSaleQuotationProductDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
        BigDecimal totalTaxPrice = getSumValue(items, CrmSaleQuotationProductDO::getTaxPrice, BigDecimal::add, BigDecimal.ZERO);
        saleQuotation.setTaxPrice(totalTaxPrice);
        // 计算优惠价格
        if (saleQuotation.getDiscountPercent() == null) {
            saleQuotation.setDiscountPercent(BigDecimal.ZERO);
        }
        BigDecimal basePrice = saleQuotation.getTotalProductPrice().add(totalTaxPrice);
        saleQuotation.setDiscountPrice(MoneyUtils.priceMultiplyPercent(basePrice, saleQuotation.getDiscountPercent()));
        saleQuotation.setTotalPrice(basePrice.subtract(saleQuotation.getDiscountPrice()));
    }
 
    @Override
    public CrmSaleQuotationDO getSaleQuotation(Long id) {
        return saleQuotationMapper.selectById(id);
    }
 
    @Override
    public PageResult<CrmSaleQuotationDO> getSaleQuotationPage(CrmSaleQuotationPageReqVO pageReqVO, Long userId) {
        // 获取用户有权限的客户 ID 列表
        List<Long> permittedCustomerIds = customerApi.getPermittedCustomerIds();
        return saleQuotationMapper.selectPage(pageReqVO, userId, permittedCustomerIds);
    }
 
    @Override
    public PageResult<CrmSaleQuotationDO> getSaleQuotationPageByCustomerId(CrmSaleQuotationPageReqVO pageReqVO) {
        return saleQuotationMapper.selectPageByCustomerId(pageReqVO);
    }
 
    @Override
    public PageResult<CrmSaleQuotationDO> getSaleQuotationPageByBusinessId(CrmSaleQuotationPageReqVO pageReqVO) {
        return saleQuotationMapper.selectPageByBusinessId(pageReqVO);
    }
 
    @Override
    public List<CrmSaleQuotationProductDO> getSaleQuotationProductListByQuotationId(Long quotationId) {
        return saleQuotationProductMapper.selectListByQuotationId(quotationId);
    }
 
    @Override
    public List<CrmSaleQuotationProductDO> getSaleQuotationProductListByQuotationIds(Collection<Long> quotationIds) {
        if (CollUtil.isEmpty(quotationIds)) {
            return Collections.emptyList();
        }
        return saleQuotationProductMapper.selectListByQuotationIds(quotationIds);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long convertToContract(Long id, Long userId) {
        // 1. 校验报价单存在,且为草稿或审批通过状态
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id);
        if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())
                && !CrmSaleQuotationStatusEnum.APPROVE.getStatus().equals(saleQuotation.getStatus())) {
            CrmSaleQuotationStatusEnum current = CrmSaleQuotationStatusEnum.getByStatus(saleQuotation.getStatus());
            throw exception(SALE_QUOTATION_CONVERT_FAIL_NOT_DRAFT, saleQuotation.getNo(),
                    current != null ? current.getName() : String.valueOf(saleQuotation.getStatus()));
        }
        // 校验是否已转合同
        if (saleQuotation.getContractId() != null) {
            throw exception(SALE_QUOTATION_CONTRACT_EXISTS);
        }
 
        // 2. 获取报价明细
        List<CrmSaleQuotationProductDO> quotationProducts = saleQuotationProductMapper.selectListByQuotationId(id);
 
        // 3. 构建合同创建 VO
        CrmContractSaveReqVO contractVO = new CrmContractSaveReqVO();
        contractVO.setName(saleQuotation.getName() + "-合同");
        contractVO.setCustomerId(saleQuotation.getCustomerId());
        contractVO.setBusinessId(saleQuotation.getBusinessId());
        contractVO.setOwnerUserId(saleQuotation.getOwnerUserId());
        contractVO.setOrderDate(saleQuotation.getQuotationTime());
        contractVO.setDiscountPercent(saleQuotation.getDiscountPercent());
        contractVO.setRemark("由报价单[" + saleQuotation.getNo() + "]生成");
        // 转换明细项:报价单物料 -> 合同产品
        List<CrmContractSaveReqVO.Product> contractProducts = convertList(quotationProducts, qp -> {
            CrmContractSaveReqVO.Product product = new CrmContractSaveReqVO.Product();
            product.setItemId(qp.getItemId());
            product.setItemPrice(qp.getItemPrice());
            product.setContractPrice(qp.getQuotationPrice());
            product.setCount(qp.getCount());
            return product;
        });
        contractVO.setProducts(contractProducts);
 
        // 4. 创建合同(会自动检测合同审批流程并提交审批)
        Long contractId = contractService.createContract(contractVO, userId);
 
        // 5. 更新报价单关联信息
        CrmContractDO contract = contractService.getContract(contractId);
        saleQuotationMapper.updateById(new CrmSaleQuotationDO()
                .setId(id)
                .setContractId(contractId)
                .setContractNo(contract.getNo())
                .setStatus(CrmSaleQuotationStatusEnum.CONVERTED.getStatus()));
 
        return contractId;
    }
 
    @Override
    public CrmSaleQuotationDO getByContractId(Long id) {
        return saleQuotationMapper.selectOne(new LambdaQueryWrapper<CrmSaleQuotationDO>().eq(CrmSaleQuotationDO::getContractId,id));
    }
 
    @Override
    public void clearContractReference(Long quotationId) {
        saleQuotationMapper.clearContractReference(quotationId);
    }
 
}