liding
6 天以前 0050395dfb05425f0a929bc1587b971d78f1e95e
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
package com.ruoyi.purchase.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.mapper.SupplierManageMapper;
import com.ruoyi.basic.pojo.SupplierManage;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.purchase.dto.PaymentLedgerDto;
import com.ruoyi.purchase.dto.PaymentRegistrationDto;
import com.ruoyi.purchase.mapper.*;
import com.ruoyi.purchase.pojo.PaymentRegistration;
import com.ruoyi.purchase.pojo.ProductRecord;
import com.ruoyi.purchase.pojo.PurchaseLedger;
import com.ruoyi.purchase.pojo.TicketRegistration;
import com.ruoyi.purchase.service.IPaymentRegistrationService;
import com.ruoyi.sales.mapper.SalesLedgerMapper;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.pojo.SalesLedger;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 付款登记Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-15
 */
@Service
@AllArgsConstructor
public class PaymentRegistrationServiceImpl extends ServiceImpl<PaymentRegistrationMapper, PaymentRegistration> implements IPaymentRegistrationService {
    private PaymentRegistrationMapper paymentRegistrationMapper;
 
    private PurchaseLedgerMapper purchaseLedgerMapper;
 
    private InvoicePurchaseMapper invoicePurchaseMapper;
 
    private SalesLedgerMapper salesLedgerMapper;
 
    private SupplierManageMapper supplierManageMapper;
 
    private SalesLedgerProductMapper salesLedgerProductMapper;
 
    private TicketRegistrationMapper ticketRegistrationMapper;
 
    private ProductRecordMapper productRecordMapper;
 
    /**
     * 查询付款登记
     *
     * @param id 付款登记主键
     * @return 付款登记
     */
    @Override
    public PaymentRegistration selectPaymentRegistrationById(Long id) {
        return paymentRegistrationMapper.selectPaymentRegistrationById(id);
    }
 
    /**
     * 查询付款登记列表
     *
     * @param paymentRegistrationDto 付款登记
     * @return 付款登记
     */
    @Override
    public List<PaymentRegistrationDto> selectPaymentRegistrationList(PaymentRegistrationDto paymentRegistrationDto) {
        List<PaymentRegistrationDto> list = paymentRegistrationMapper.selectPaymentRegistrationList(paymentRegistrationDto);
        for (PaymentRegistrationDto registrationDto : list) {
            List<PaymentRegistration> paymentRegistrations = paymentRegistrationMapper.selectList(new QueryWrapper<PaymentRegistration>()
                    .eq("ticket_registration_id", registrationDto.getTicketRegistrationId()));
            BigDecimal total = paymentRegistrations.stream().map(PaymentRegistration::getCurrentPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            registrationDto.setUnPaymentAmount(registrationDto.getInvoiceAmount().subtract(total));
        }
        return list;
    }
 
    /**
     * 新增付款登记
     *
     * @param paymentRegistration 付款登记
     * @return 结果
     */
    @Override
    public int insertPaymentRegistration(PaymentRegistration paymentRegistration) {
        PurchaseLedger purchaseLedger = purchaseLedgerMapper.selectById(paymentRegistration.getPurchaseLedgerId());
        SalesLedger salesLedger = salesLedgerMapper.selectOne(new QueryWrapper<SalesLedger>().
                eq("sales_contract_no", purchaseLedger.getSalesContractNo()));
        if (salesLedger == null) {
            throw new RuntimeException("关联销售合同号不存在");
        }
 
        paymentRegistration.setSaleLedgerId(salesLedger.getId());
        paymentRegistration.setSupplierId(purchaseLedger.getSupplierId());
 
        TicketRegistration tr = ticketRegistrationMapper.selectOne(new LambdaQueryWrapper<TicketRegistration>().eq(TicketRegistration::getId, paymentRegistration.getTicketRegistrationId()));
 
        if (tr == null) {
            throw new RuntimeException("关联发票不存在");
        }
 
        List<PaymentRegistration> paymentRegistrations = paymentRegistrationMapper.selectList(new QueryWrapper<PaymentRegistration>()
                .eq("ticket_registration_id", tr.getId()));
        BigDecimal total = paymentRegistrations.stream().map(PaymentRegistration::getCurrentPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
 
        if (total.add(paymentRegistration.getCurrentPaymentAmount()).compareTo(tr.getInvoiceAmount()) > 0) {
            throw new RuntimeException("付款金额超出发票金额");
        }
 
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Integer tenantId = loginUser.getTenantId();
        paymentRegistration.setTenantId(tenantId.longValue());
        paymentRegistration.setRegistrantId(loginUser.getUserId());
        paymentRegistration.setCreateTime(DateUtils.getNowDate());
        paymentRegistration.setUpdateTime(DateUtils.getNowDate());
        return paymentRegistrationMapper.insert(paymentRegistration);
    }
 
    /**
     * 修改付款登记
     *
     * @param paymentRegistration 付款登记
     * @return 结果
     */
    @Override
    public int updatePaymentRegistration(PaymentRegistration paymentRegistration) {
        TicketRegistration ticketRegistration = ticketRegistrationMapper.selectById(paymentRegistration.getTicketRegistrationId());
 
        List<PaymentRegistration> paymentRegistrations = paymentRegistrationMapper.selectList(new QueryWrapper<PaymentRegistration>()
                .eq("ticket_registration_id", paymentRegistration.getTicketRegistrationId()).ne("id", paymentRegistration.getId()));
        BigDecimal total = paymentRegistrations.stream().map(PaymentRegistration::getCurrentPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
 
        if (total.add(paymentRegistration.getCurrentPaymentAmount()).compareTo(ticketRegistration.getInvoiceAmount()) > 0) {
            throw new RuntimeException("付款金额超出发票金额");
        }
 
        paymentRegistration.setUpdateTime(DateUtils.getNowDate());
        return paymentRegistrationMapper.updateById(paymentRegistration);
    }
 
    /**
     * 批量删除付款登记
     *
     * @param ids 需要删除的付款登记主键
     * @return 结果
     */
    @Override
    public int deletePaymentRegistrationByIds(Long[] ids) {
        return paymentRegistrationMapper.delete(new QueryWrapper<PaymentRegistration>().in("id", ids));
    }
 
    @Override
    public PaymentRegistration selectPaymentRegistrationByPurchaseId(Long id) {
        PaymentRegistrationDto paymentRegistrationDto = new PaymentRegistrationDto();
        PurchaseLedger purchaseLedger = purchaseLedgerMapper.selectById(id);
        paymentRegistrationDto.setSalesContractNo(purchaseLedger.getSalesContractNo());
        paymentRegistrationDto.setSupplierName(purchaseLedger.getSupplierName());
        paymentRegistrationDto.setSupplierId(purchaseLedger.getSupplierId());
 
        List<TicketRegistration> ticketRegistrations = ticketRegistrationMapper.selectList(new QueryWrapper<TicketRegistration>()
                .eq("purchase_contract_number", purchaseLedger.getPurchaseContractNumber()));
        if (ticketRegistrations != null && ticketRegistrations.size() > 0) {
            paymentRegistrationDto.setInvoiceNumber(ticketRegistrations.get(0).getInvoiceNumber());
            paymentRegistrationDto.setInvoiceAmount(ticketRegistrations.get(0).getInvoiceAmount());
        }
        return paymentRegistrationDto;
    }
 
    @Override
    public IPage<Map<String, Object>> selectPaymentLedgerList(
            PaymentLedgerDto paymentLedgerDto,
            Page page,
            Integer detailPageNum,
            Integer detailPageSize) {
        LambdaQueryWrapper<SupplierManage> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(paymentLedgerDto)
                .ifPresent(dto -> {
                    if (StringUtils.hasText(dto.getSupplierName())) {
                        queryWrapper.like(SupplierManage::getSupplierName, dto.getSupplierName());
                    }
                });
 
        IPage<SupplierManage> supplierPage = supplierManageMapper.selectPage(page, queryWrapper);
        List<SupplierManage> supplierManages = supplierPage.getRecords();
 
        IPage<Map<String, Object>> resultPage = new Page<>(page.getCurrent(), page.getSize(), supplierPage.getTotal());
        List<Map<String, Object>> result = new ArrayList<>();
 
        for (SupplierManage supplierManage : supplierManages) {
            Map<String, Object> res = new HashMap<>();
            res.put("supplierName", supplierManage.getSupplierName());
 
            // 应付金额计算
            BigDecimal payableAmount = BigDecimal.ZERO;
            List<PurchaseLedger> purchaseLedgers = purchaseLedgerMapper.selectList(
                    new QueryWrapper<PurchaseLedger>().eq("supplier_id", supplierManage.getId())
            );
            List<SalesLedgerProduct> salesLedgerProducts = purchaseLedgers.stream()
                    .filter(Objects::nonNull)
                    .map(PurchaseLedger::getId)
                    .filter(Objects::nonNull)
                    .flatMap(id -> salesLedgerProductMapper.selectList(
                            new QueryWrapper<SalesLedgerProduct>().eq("sales_ledger_id", id)
                    ).stream())
                    .collect(Collectors.toList());
            payableAmount = salesLedgerProducts.stream()
                    .map(SalesLedgerProduct::getTaxInclusiveTotalPrice)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
 
            // 来票金额计算
            List<TicketRegistration> ticketRegistrations = purchaseLedgers.stream()
                    .map(PurchaseLedger::getId)
                    .filter(Objects::nonNull)
                    .map(id -> ticketRegistrationMapper.selectList(
                            new LambdaQueryWrapper<TicketRegistration>().eq(TicketRegistration::getPurchaseLedgerId, id)
                    ))
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
            BigDecimal invoiceAmount = ticketRegistrations.stream()
                    .map(TicketRegistration::getInvoiceAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
 
            // 付款记录及详情分页
            List<PaymentRegistration> paymentRegistrations = paymentRegistrationMapper.selectList(
                    new QueryWrapper<PaymentRegistration>().eq("supplier_id", supplierManage.getId())
            );
            BigDecimal paymentAmount = paymentRegistrations.stream()
                    .map(PaymentRegistration::getCurrentPaymentAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
 
            // 详情分页处理
            detailPageNum = detailPageNum != null ? detailPageNum : 1;
            detailPageSize = detailPageSize != null ? detailPageSize : paymentRegistrations.size(); // 默认显示全部
            int totalDetails = paymentRegistrations.size();
            int start = (detailPageNum - 1) * detailPageSize;
            int end = Math.min(start + detailPageSize, totalDetails);
            List<PaymentRegistration> pagedDetails = paymentRegistrations.subList(start, end);
 
            // 构建详情列表
            List<Map<String, Object>> details = pagedDetails.stream()
                    .filter(Objects::nonNull)
                    .map(pr -> {
                        Map<String, Object> detail = new HashMap<>();
                        detail.put("paymentAmount", pr.getCurrentPaymentAmount());
 
                        // 批量查询 TicketRegistration(避免 N+1)
                        TicketRegistration ticketRegistration = ticketRegistrationMapper.selectById(pr.getTicketRegistrationId());
                        if (ticketRegistration != null) {
                            detail.put("payableAmount", ticketRegistration.getInvoiceAmount());
                            BigDecimal voteCount = productRecordMapper.selectList(
                                            new LambdaQueryWrapper<ProductRecord>().eq(ProductRecord::getTicketRegistrationId, ticketRegistration.getId())
                                    ).stream()
                                    .map(ProductRecord::getTicketsNum)
                                    .map(BigDecimal::new)
                                    .filter(Objects::nonNull)
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            detail.put("voteCount", voteCount);
                        }
 
                        // 日期格式化(建议使用 LocalDateTime)
                        if (pr.getPaymentDate() != null) {
                            detail.put("paymentDate", new SimpleDateFormat("yyyy-MM-dd").format(pr.getPaymentDate()));
                        }
                        return detail;
                    })
                    .collect(Collectors.toList());
 
            // 封装详情分页元数据
            Map<String, Object> detailPagination = new HashMap<>();
            detailPagination.put("total", totalDetails);
            detailPagination.put("pageNum", detailPageNum);
            detailPagination.put("pageSize", detailPageSize);
            detailPagination.put("pages", (int) Math.ceil((double) totalDetails / detailPageSize));
 
            res.put("invoiceAmount", invoiceAmount);
            res.put("payableAmount", payableAmount);
            res.put("paymentAmount", paymentAmount);
            res.put("details", details);
            res.put("detailPagination", detailPagination); // 添加详情分页信息
            result.add(res);
        }
 
        resultPage.setRecords(result);
        return resultPage;
    }
 
    @Override
    public Map<String, BigDecimal> paymentMonthList() {
 
        // 查询供应商列表
        List<SupplierManage> suppliers = supplierManageMapper.selectList(null);
        if (CollectionUtils.isEmpty(suppliers)) {
            Map<String, BigDecimal> result = new HashMap<>();
            result.put("payableAmount", BigDecimal.ZERO);
            result.put("paymentAmount", BigDecimal.ZERO);
            return result;
        }
 
        // 提取所有供应商ID
        List<Long> supplierIds = suppliers.stream()
                .map(SupplierManage::getId) // 先获取Integer类型的ID
                .filter(Objects::nonNull)    // 过滤掉可能的null值
                .map(Integer::longValue)    // 将Integer转换为Long
                .collect(Collectors.toList());
 
        // 获取当月的开始和结束日期
        YearMonth currentMonth = YearMonth.now();
        LocalDate startDate = currentMonth.atDay(1);
        LocalDate endDate = currentMonth.atEndOfMonth();
 
        // 批量查询采购台账(当月)
        Map<Long, List<PurchaseLedger>> purchaseLedgerMap = batchQueryPurchaseLedgers(supplierIds, startDate, endDate);
 
        // 批量查询销售台账产品
        Map<Long, List<SalesLedgerProduct>> salesLedgerProductMap = batchQuerySalesLedgerProducts(purchaseLedgerMap);
 
        // 批量查询付款记录(当月)
        Map<Long, List<PaymentRegistration>> paymentRegistrationMap = batchQueryPaymentRegistrations(supplierIds, startDate, endDate);
 
        // 计算应付金额和付款金额
        BigDecimal totalPayableAmount = calculateTotalPayableAmount(purchaseLedgerMap, salesLedgerProductMap);
        BigDecimal totalPaymentAmount = calculateTotalPaymentAmount(paymentRegistrationMap);
 
        // 构建结果
        Map<String, BigDecimal> result = new HashMap<>();
        result.put("payableAmount", totalPayableAmount);
        result.put("paymentAmount", totalPaymentAmount);
        return result;
    }
 
    // 批量查询采购台账(当月)
    private Map<Long, List<PurchaseLedger>> batchQueryPurchaseLedgers(List<Long> supplierIds, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<PurchaseLedger> query = new LambdaQueryWrapper<>();
        query.in(PurchaseLedger::getSupplierId, supplierIds)
                .ge(PurchaseLedger::getCreatedAt, startDate)
                .le(PurchaseLedger::getCreatedAt, endDate);
        List<PurchaseLedger> purchaseLedgers = purchaseLedgerMapper.selectList(query);
 
        return purchaseLedgers.stream()
                .filter(pl -> pl.getSupplierId() != null)
                .collect(Collectors.groupingBy(PurchaseLedger::getSupplierId));
    }
 
    // 批量查询销售台账产品
    private Map<Long, List<SalesLedgerProduct>> batchQuerySalesLedgerProducts(Map<Long, List<PurchaseLedger>> purchaseLedgerMap) {
        // 提取所有采购台账ID
        List<Long> purchaseLedgerIds = purchaseLedgerMap.values().stream()
                .flatMap(Collection::stream)
                .map(PurchaseLedger::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
 
        if (purchaseLedgerIds.isEmpty()) {
            return Collections.emptyMap();
        }
 
        LambdaQueryWrapper<SalesLedgerProduct> query = new LambdaQueryWrapper<>();
        query.in(SalesLedgerProduct::getSalesLedgerId, purchaseLedgerIds);
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(query);
 
        return products.stream()
                .filter(slp -> slp.getSalesLedgerId() != null)
                .collect(Collectors.groupingBy(SalesLedgerProduct::getSalesLedgerId));
    }
 
    // 批量查询付款记录(当月)
    private Map<Long, List<PaymentRegistration>> batchQueryPaymentRegistrations(List<Long> supplierIds, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<PaymentRegistration> query = new LambdaQueryWrapper<>();
        query.in(PaymentRegistration::getSupplierId, supplierIds)
                .ge(PaymentRegistration::getPaymentDate, startDate)
                .le(PaymentRegistration::getPaymentDate, endDate);
        List<PaymentRegistration> paymentRegistrations = paymentRegistrationMapper.selectList(query);
 
        return paymentRegistrations.stream()
                .filter(pr -> pr.getSupplierId() != null)
                .collect(Collectors.groupingBy(PaymentRegistration::getSupplierId));
    }
 
    // 计算总应付金额
    private BigDecimal calculateTotalPayableAmount(Map<Long, List<PurchaseLedger>> purchaseLedgerMap,
                                                   Map<Long, List<SalesLedgerProduct>> salesLedgerProductMap) {
        return purchaseLedgerMap.values().stream()
                .flatMap(Collection::stream)
                .map(pl -> salesLedgerProductMap.getOrDefault(pl.getId(), Collections.emptyList()))
                .flatMap(Collection::stream)
                .map(SalesLedgerProduct::getTaxInclusiveTotalPrice)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
 
    // 计算总付款金额
    private BigDecimal calculateTotalPaymentAmount(Map<Long, List<PaymentRegistration>> paymentRegistrationMap) {
        return paymentRegistrationMap.values().stream()
                .flatMap(Collection::stream)
                .map(PaymentRegistration::getCurrentPaymentAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}