From 6f888b234148d1a4dbd1e6c28a8d9ed85ebfda09 Mon Sep 17 00:00:00 2001
From: yaowanxin <3588231647@qq.com>
Date: 星期四, 29 一月 2026 18:11:26 +0800
Subject: [PATCH] Merge remote-tracking branch 'origin/dev_New' into dev_New
---
src/main/java/com/ruoyi/home/service/impl/HomeServiceImpl.java | 1384 ++++++++++++++++++++++++++++++++++++++++++++++++++++-----
1 files changed, 1,249 insertions(+), 135 deletions(-)
diff --git a/src/main/java/com/ruoyi/home/service/impl/HomeServiceImpl.java b/src/main/java/com/ruoyi/home/service/impl/HomeServiceImpl.java
index d346d41..828d6ae 100644
--- a/src/main/java/com/ruoyi/home/service/impl/HomeServiceImpl.java
+++ b/src/main/java/com/ruoyi/home/service/impl/HomeServiceImpl.java
@@ -1,19 +1,45 @@
package com.ruoyi.home.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.ruoyi.account.mapper.AccountIncomeMapper;
+import com.ruoyi.account.pojo.AccountExpense;
+import com.ruoyi.home.mapper.HomeMapper;
+import com.ruoyi.account.mapper.AccountExpenseMapper;
import com.ruoyi.approve.mapper.ApproveProcessMapper;
import com.ruoyi.approve.pojo.ApproveProcess;
+import com.ruoyi.basic.mapper.CustomerMapper;
+import com.ruoyi.basic.mapper.ProductMapper;
+import com.ruoyi.basic.mapper.ProductModelMapper;
+import com.ruoyi.basic.mapper.SupplierManageMapper;
+import com.ruoyi.basic.pojo.Customer;
+import com.ruoyi.basic.pojo.Product;
+import com.ruoyi.basic.pojo.SupplierManage;
+import com.ruoyi.collaborativeApproval.mapper.NoticeMapper;
+import com.ruoyi.collaborativeApproval.pojo.Notice;
+import com.ruoyi.common.enums.ApproveTypeEnum;
import com.ruoyi.common.utils.SecurityUtils;
+import com.ruoyi.device.mapper.DeviceRepairMapper;
+import com.ruoyi.device.pojo.DeviceRepair;
import com.ruoyi.dto.MapDto;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.home.dto.*;
import com.ruoyi.home.service.HomeService;
import com.ruoyi.procurementrecord.mapper.ProcurementRecordMapper;
-import com.ruoyi.procurementrecord.mapper.ProcurementRecordOutMapper;
-import com.ruoyi.procurementrecord.pojo.ProcurementRecordOut;
import com.ruoyi.procurementrecord.pojo.ProcurementRecordStorage;
+import com.ruoyi.procurementrecord.utils.StockUtils;
+import com.ruoyi.production.dto.ProductOrderDto;
+import com.ruoyi.production.dto.ProductWorkOrderDto;
+import com.ruoyi.production.mapper.ProductOrderMapper;
+import com.ruoyi.production.mapper.ProductWorkOrderMapper;
+import com.ruoyi.production.pojo.ProductWorkOrder;
import com.ruoyi.project.system.domain.SysDept;
+import com.ruoyi.project.system.domain.SysUser;
+import com.ruoyi.project.system.domain.SysUserDept;
import com.ruoyi.project.system.mapper.SysDeptMapper;
+import com.ruoyi.project.system.mapper.SysUserDeptMapper;
+import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.purchase.mapper.PaymentRegistrationMapper;
import com.ruoyi.purchase.mapper.PurchaseLedgerMapper;
import com.ruoyi.purchase.pojo.PaymentRegistration;
@@ -26,16 +52,22 @@
import com.ruoyi.sales.pojo.ReceiptPayment;
import com.ruoyi.sales.pojo.SalesLedger;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
+import com.ruoyi.staff.mapper.StaffOnJobMapper;
+import com.ruoyi.staff.pojo.StaffOnJob;
+import com.ruoyi.stock.mapper.StockInventoryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
+import java.text.ParseException;
import java.time.*;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
@@ -56,7 +88,7 @@
private SalesLedgerProductMapper salesLedgerProductMapper;
@Autowired
- private ProcurementRecordOutMapper procurementRecordOutMapper;
+ private StockInventoryMapper stockInventoryMapper;
@Autowired
private ProcurementRecordMapper procurementRecordStorageMapper;
@@ -76,8 +108,36 @@
@Autowired
private SysDeptMapper sysDeptMapper;
+ @Autowired
+ private NoticeMapper noticeMapper;
+ @Autowired
+ private ProductOrderMapper productOrderMapper;
+ @Autowired
+ private ProductWorkOrderMapper productWorkOrderMapper;
+ @Autowired
+ private ProductModelMapper productModelMapper;
+ @Autowired
+ private ProductMapper productMapper;
+ @Autowired
+ private StockUtils stockUtils;
+ @Autowired
+ private StaffOnJobMapper staffOnJobMapper;
+ @Autowired
+ private CustomerMapper customerMapper;
+ @Autowired
+ private SupplierManageMapper supplierManageMapper;
+ @Autowired
+ private SysUserMapper sysUserMapper;
+ @Autowired
+ private SysUserDeptMapper sysUserDeptMapper;
+
+ @Autowired
+ private HomeMapper homeMapper;
+
@Override
public HomeBusinessDto business() {
+ // 鏋勫缓缁撴灉
+ HomeBusinessDto homeBusinessDto = new HomeBusinessDto();
LocalDate now = LocalDate.now();
YearMonth currentMonth = YearMonth.from(now);
// 鍒涘缓LambdaQueryWrapper
@@ -85,72 +145,54 @@
salesLedgerLambdaQueryWrapper.ge(SalesLedger::getEntryDate, currentMonth.atDay(1).atStartOfDay()) // 澶т簬绛変簬鏈湀绗竴澶�
.lt(SalesLedger::getEntryDate, currentMonth.plusMonths(1).atDay(1).atStartOfDay()); // 灏忎簬涓嬫湀绗竴澶�
List<SalesLedger> salesLedgers = salesLedgerMapper.selectList(salesLedgerLambdaQueryWrapper);
- // 鍚堣鍚堝悓閲戦
- BigDecimal contractAmount = salesLedgers.stream().map(SalesLedger::getContractAmount)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- LambdaQueryWrapper<SalesLedgerProduct> salesLedgerProductMapperLambdaQueryWrapper = new LambdaQueryWrapper<SalesLedgerProduct>();
- salesLedgerProductMapperLambdaQueryWrapper.eq(SalesLedgerProduct::getType, 1)
- .in(SalesLedgerProduct::getSalesLedgerId, salesLedgers.stream().map(SalesLedger::getId).collect(Collectors.toList()));
- List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(salesLedgerProductMapperLambdaQueryWrapper);
- // 鏈紑绁ㄩ噾棰�
- BigDecimal noInvoiceAmountTotal = salesLedgerProducts.stream().map(SalesLedgerProduct::getNoInvoiceAmount)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
-
+ if (!CollectionUtils.isEmpty(salesLedgers)) {
+ // 鍚堣鍚堝悓閲戦
+ BigDecimal contractAmount = salesLedgers.stream().map(SalesLedger::getContractAmount)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ LambdaQueryWrapper<SalesLedgerProduct> salesLedgerProductMapperLambdaQueryWrapper = new LambdaQueryWrapper<SalesLedgerProduct>();
+ salesLedgerProductMapperLambdaQueryWrapper.eq(SalesLedgerProduct::getType, 1)
+ .in(SalesLedgerProduct::getSalesLedgerId, salesLedgers.stream().map(SalesLedger::getId).collect(Collectors.toList()));
+ List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(salesLedgerProductMapperLambdaQueryWrapper);
+ // 鏈紑绁ㄩ噾棰�
+ BigDecimal noInvoiceAmountTotal = salesLedgerProducts.stream().map(SalesLedgerProduct::getNoInvoiceAmount)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ homeBusinessDto.setMonthSaleMoney(contractAmount.setScale(2, RoundingMode.HALF_UP).toString());
+ homeBusinessDto.setMonthSaleHaveMoney(noInvoiceAmountTotal.setScale(2, RoundingMode.HALF_UP).toString());
+ }
// 鍒涘缓LambdaQueryWrapper
LambdaQueryWrapper<PurchaseLedger> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.ge(PurchaseLedger::getEntryDate, currentMonth.atDay(1).atStartOfDay()) // 澶т簬绛変簬鏈湀绗竴澶�
.lt(PurchaseLedger::getEntryDate, currentMonth.plusMonths(1).atDay(1).atStartOfDay()); // 灏忎簬涓嬫湀绗竴澶�
-
// 鎵ц鏌ヨ骞惰绠楁�诲拰
List<PurchaseLedger> purchaseLedgers = purchaseLedgerMapper.selectList(queryWrapper);
-
- LambdaQueryWrapper<SalesLedgerProduct> salesLedgerProductMapperLambdaQueryWrapperCopy = new LambdaQueryWrapper<SalesLedgerProduct>();
- salesLedgerProductMapperLambdaQueryWrapper.eq(SalesLedgerProduct::getType, 2)
- .in(SalesLedgerProduct::getSalesLedgerId, purchaseLedgers.stream().map(PurchaseLedger::getId).collect(Collectors.toList()));
- List<SalesLedgerProduct> salesLedgerProductsCopy = salesLedgerProductMapper.selectList(salesLedgerProductMapperLambdaQueryWrapperCopy);
- // 鍚堣鍚堝悓閲戦
- BigDecimal receiveAmount = purchaseLedgers.stream()
- .map(PurchaseLedger::getContractAmount)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- // 鏈紑绁ㄩ噾棰�
- BigDecimal unReceiptPaymentAmount = salesLedgerProductsCopy.stream()
- .map(SalesLedgerProduct::getNoInvoiceAmount)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
-
+ if (!CollectionUtils.isEmpty(purchaseLedgers)) {
+ LambdaQueryWrapper<SalesLedgerProduct> salesLedgerProductMapperLambdaQueryWrapperCopy = new LambdaQueryWrapper<SalesLedgerProduct>();
+ salesLedgerProductMapperLambdaQueryWrapperCopy.eq(SalesLedgerProduct::getType, 2)
+ .in(SalesLedgerProduct::getSalesLedgerId, purchaseLedgers.stream().map(PurchaseLedger::getId).collect(Collectors.toList()));
+ List<SalesLedgerProduct> salesLedgerProductsCopy = salesLedgerProductMapper.selectList(salesLedgerProductMapperLambdaQueryWrapperCopy);
+ // 鍚堣鍚堝悓閲戦
+ BigDecimal receiveAmount = purchaseLedgers.stream()
+ .map(PurchaseLedger::getContractAmount)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ // 鏈紑绁ㄩ噾棰�
+ BigDecimal unReceiptPaymentAmount = salesLedgerProductsCopy.stream()
+ .map(SalesLedgerProduct::getNoInvoiceAmount)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ homeBusinessDto.setMonthPurchaseMoney(receiveAmount.setScale(2, RoundingMode.HALF_UP).toString());
+ homeBusinessDto.setMonthPurchaseHaveMoney(unReceiptPaymentAmount.setScale(2, RoundingMode.HALF_UP).toString());
+ }
// 缁熻搴撳瓨
- List<ProcurementRecordStorage> procurementRecordStorages = procurementRecordStorageMapper.selectList(null);
- BigDecimal stockAmount = procurementRecordStorages.stream()
- .map(ProcurementRecordStorage::getInboundNum)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- List<ProcurementRecordOut> procurementRecordOuts = procurementRecordOutMapper.selectList(null);
- BigDecimal outboundAmount = procurementRecordOuts.stream()
- .map(ProcurementRecordOut::getInboundNum)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- BigDecimal stock = stockAmount.subtract(outboundAmount);
- // 鑾峰彇褰撳ぉ鍏ュ簱鏁伴噺
- LambdaQueryWrapper<ProcurementRecordStorage> procurementRecordStorageLambdaQueryWrapper = new LambdaQueryWrapper<>();
- procurementRecordStorageLambdaQueryWrapper.ge(ProcurementRecordStorage::getCreateTime, now) // 澶т簬绛変簬褰撳ぉ
- .lt(ProcurementRecordStorage::getCreateTime, now.plusDays(1)); // 灏忎簬鏄庡ぉ
- List<ProcurementRecordStorage> procurementRecordStorages1 = procurementRecordStorageMapper.selectList(procurementRecordStorageLambdaQueryWrapper);
- BigDecimal stockAmount1 = procurementRecordStorages1.stream()
- .map(ProcurementRecordStorage::getInboundNum)
- .filter(Objects::nonNull)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- // 鏋勫缓缁撴灉
- HomeBusinessDto homeBusinessDto = new HomeBusinessDto();
- homeBusinessDto.setMonthSaleMoney(contractAmount);
- homeBusinessDto.setMonthSaleHaveMoney(noInvoiceAmountTotal);
- homeBusinessDto.setMonthPurchaseMoney(receiveAmount);
- homeBusinessDto.setMonthPurchaseHaveMoney(unReceiptPaymentAmount);
- homeBusinessDto.setInventoryNum(stock);
- homeBusinessDto.setTodayInventoryNum(stockAmount1);
+ BigDecimal stockQuantityTotal = stockInventoryMapper.selectTotal();
+ homeBusinessDto.setInventoryNum(stockQuantityTotal.setScale(2, RoundingMode.HALF_UP).toString());
+
+ // 鑾峰彇褰撳ぉ鍏ュ簱鏁伴噺
+ BigDecimal bigDecimal = stockInventoryMapper.selectTotalByDate(LocalDate.now());
+ homeBusinessDto.setTodayInventoryNum(bigDecimal.setScale(2, RoundingMode.HALF_UP).toString());
return homeBusinessDto;
}
@@ -172,7 +214,7 @@
LocalDate endOfWeek = today.with(DayOfWeek.SUNDAY);
List<SalesLedger> salesLedgers1 = salesLedgerMapper.selectList(new LambdaQueryWrapper<SalesLedger>()
.ge(SalesLedger::getEntryDate, startOfWeek) // 澶т簬绛変簬鏈懆鍛ㄤ竴
- .gt(SalesLedger::getEntryDate, endOfWeek));
+ .lt(SalesLedger::getEntryDate, endOfWeek.plusDays(1))); // 淇敼锛氫娇鐢� lt 骞跺姞涓婁竴澶╂潵鍖呭惈鍛ㄦ棩
BigDecimal weekContractAmount = salesLedgers1.stream().map(SalesLedger::getContractAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
@@ -181,16 +223,16 @@
LocalDate lastYearEndOfWeek = today.minusYears(1).with(DayOfWeek.SUNDAY);
List<SalesLedger> salesLedgers2 = salesLedgerMapper.selectList(new LambdaQueryWrapper<SalesLedger>()
.ge(SalesLedger::getEntryDate, lastYearStartOfWeek) // 澶т簬绛変簬鍘诲勾鏈懆鍛ㄤ竴
- .gt(SalesLedger::getEntryDate, lastYearEndOfWeek));
+ .lt(SalesLedger::getEntryDate, lastYearEndOfWeek.plusDays(1))); // 淇敼锛氫娇鐢� lt 骞跺姞涓婁竴澶╂潵鍖呭惈鍛ㄦ棩
BigDecimal lastYearWeekContractAmount = salesLedgers2.stream().map(SalesLedger::getContractAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal subtract = weekContractAmount.subtract(lastYearWeekContractAmount);
String weekYny = "";
// 鍛ㄥ悓姣�
- if(subtract.compareTo(BigDecimal.ZERO) == 0 || lastYearWeekContractAmount.compareTo(BigDecimal.ZERO) == 0){
+ if (subtract.compareTo(BigDecimal.ZERO) == 0 || lastYearWeekContractAmount.compareTo(BigDecimal.ZERO) == 0) {
weekYny = "0.00";
- }else{
+ } else {
weekYny = String.format("%.2f", subtract.divide(lastYearWeekContractAmount, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
}
@@ -199,42 +241,44 @@
LocalDate yesterday = today.minusDays(1);
LocalDate plusDays = today.plusDays(1);
List<SalesLedger> salesLedgers3 = salesLedgerMapper.selectList(new LambdaQueryWrapper<SalesLedger>()
- .ge(SalesLedger::getEntryDate, today) // 澶т簬绛変簬鏄ㄥぉ
- .lt(SalesLedger::getEntryDate, plusDays));
- BigDecimal yesterdayContractAmount = salesLedgers3.stream().map(SalesLedger::getContractAmount)
+ .ge(SalesLedger::getEntryDate, today) // 澶т簬绛変簬浠婂ぉ
+ .lt(SalesLedger::getEntryDate, plusDays)); // 淇敼锛氫娇鐢� lt 骞跺姞涓婁竴澶╂潵鍖呭惈褰撳ぉ
+ BigDecimal todayContractAmount = salesLedgers3.stream().map(SalesLedger::getContractAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
List<SalesLedger> salesLedgers4 = salesLedgerMapper.selectList(new LambdaQueryWrapper<SalesLedger>()
- .ge(SalesLedger::getEntryDate, yesterday) // 澶т簬绛変簬鍘诲勾鏄ㄥぉ
- .lt(SalesLedger::getEntryDate, today));
+ .ge(SalesLedger::getEntryDate, yesterday) // 澶т簬绛変簬鏄ㄥぉ
+ .lt(SalesLedger::getEntryDate, today)); // 淇敼锛氫娇鐢� lt 鑰屼笉鏄� gt
BigDecimal lastYearYesterdayContractAmount = salesLedgers4.stream().map(SalesLedger::getContractAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
- BigDecimal subtract1 = yesterdayContractAmount.subtract(lastYearYesterdayContractAmount);
+ BigDecimal subtract1 = todayContractAmount.subtract(lastYearYesterdayContractAmount); // 淇敼锛氫娇鐢� todayContractAmount 鑰屼笉鏄� yesterdayContractAmount
// 鏃ョ幆姣�
String chain = "";
- if(subtract1.compareTo(BigDecimal.ZERO) == 0 || lastYearYesterdayContractAmount.compareTo(BigDecimal.ZERO) == 0){
+ if (subtract1.compareTo(BigDecimal.ZERO) == 0 || lastYearYesterdayContractAmount.compareTo(BigDecimal.ZERO) == 0) {
chain = "0.00";
- }else{
+ } else {
chain = String.format("%.2f", subtract1.divide(lastYearYesterdayContractAmount, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
}
AnalysisCustomerContractAmountsDto analysisCustomerContractAmountsDto = new AnalysisCustomerContractAmountsDto();
- analysisCustomerContractAmountsDto.setSum(contractAmount);
+ // 淇敼锛氬皢鍚堝悓閲戦淇濈暀涓や綅灏忔暟
+ analysisCustomerContractAmountsDto.setSum(contractAmount.setScale(2, RoundingMode.HALF_UP).toString());
analysisCustomerContractAmountsDto.setYny(weekYny);
analysisCustomerContractAmountsDto.setChain(chain);
Map<String, BigDecimal> collect = salesLedgers.stream().collect(Collectors.groupingBy(SalesLedger::getCustomerName, Collectors.reducing(BigDecimal.ZERO,
SalesLedger::getContractAmount, BigDecimal::add)));
List<MapDto> mapDtos = new ArrayList<>();
- collect.forEach((k,v)->{
+ collect.forEach((k, v) -> {
MapDto mapDto = new MapDto();
mapDto.setName(k);
- mapDto.setValue(v);
- if(contractAmount.compareTo(new BigDecimal(0)) == 0){
+ // 淇敼锛氬皢閲戦鍊间繚鐣欎袱浣嶅皬鏁�
+ mapDto.setValue(v.setScale(2, RoundingMode.HALF_UP).toString());
+ if (contractAmount.compareTo(new BigDecimal(0)) == 0) {
mapDto.setRate("0");
- }else{
+ } else {
mapDto.setRate(String.format("%.2f", v.divide(contractAmount, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))));
}
mapDtos.add(mapDto);
@@ -243,68 +287,130 @@
return analysisCustomerContractAmountsDto;
}
+
@Override
public QualityStatisticsDto qualityStatistics() {
- // 鑾峰彇涓�鍛ㄦ暟鎹�
- // 鑾峰彇褰撳墠鏃堕棿
+ // 鑾峰彇杩戝洓涓湀鏁版嵁锛堝線鍓嶆帹涓変釜鏈堬紝鍏�4涓畬鏁存湀浠斤級
LocalDate today = LocalDate.now();
- // 鑾峰彇鏈懆鍛ㄤ竴
- LocalDate startOfWeek = today.with(DayOfWeek.MONDAY);
- // 鑾峰彇鏈懆鍛ㄦ棩
- LocalDate endOfWeek = today.with(DayOfWeek.SUNDAY);
- LambdaQueryWrapper<QualityInspect> qualityInspectLambdaQueryWrapper = new LambdaQueryWrapper<>();
- qualityInspectLambdaQueryWrapper.ge(QualityInspect::getCheckTime, startOfWeek)
- .gt(QualityInspect::getCheckTime, endOfWeek);
- List<QualityInspect> qualityInspects = qualityStatisticsMapper.selectList(qualityInspectLambdaQueryWrapper);
+ // 瀹氫箟鏃ユ湡鏍煎紡鍖栧櫒锛堢敤浜庢樉绀衡�滃勾鏈堚�濇牸寮忥級
+ DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
+
QualityStatisticsDto qualityStatisticsDto = new QualityStatisticsDto();
- qualityStatisticsDto.setSupplierNum(qualityInspects.stream().filter(item -> item.getInspectType().equals(0)).map(QualityInspect::getQuantity).reduce(BigDecimal.ZERO, BigDecimal::add));
- qualityStatisticsDto.setProcessNum(qualityInspects.stream().filter(item -> item.getInspectType().equals(1)).map(QualityInspect::getQuantity).reduce(BigDecimal.ZERO, BigDecimal::add));
- qualityStatisticsDto.setFactoryNum(qualityInspects.stream().filter(item -> item.getInspectType().equals(2)).map(QualityInspect::getQuantity).reduce(BigDecimal.ZERO, BigDecimal::add));
List<QualityStatisticsItem> qualityStatisticsItems = new ArrayList<>();
- for (int j = 1; j < 8; j++) {
- LocalDate endTime = startOfWeek.plusDays(j);
- LocalDate startTime = endTime.minusDays(1);
- QualityStatisticsItem qualityStatisticsItem = new QualityStatisticsItem();
- qualityStatisticsItem.setDate(startTime.toString());
- qualityStatisticsItem.setSupplierNum(qualityInspects.stream()
- .filter(item -> item.getInspectType().equals(0) && "涓嶅悎鏍�".equals(item.getCheckResult())
- && (startTime.isEqual(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) || startTime.isAfter(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()))
- && endTime.isBefore(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()))
+
+ BigDecimal supplierNum = new BigDecimal(0);
+ BigDecimal factoryNum = new BigDecimal(0);
+ BigDecimal processNum = new BigDecimal(0);
+ // 寰幆4娆★紝鍒嗗埆缁熻杩�4涓湀鐨勬暟鎹紙褰撳墠鏈堛�佸墠1涓湀銆佸墠2涓湀銆佸墠3涓湀锛�
+ for (int i = 3; i >= 0; i--) {
+ // 璁$畻褰撳墠寰幆瀵瑰簲鐨勬湀浠斤紙i=0锛氬綋鍓嶆湀锛宨=1锛氬墠1涓湀锛屼互姝ょ被鎺級
+ LocalDate currentMonth = today.minusMonths(i);
+ // 褰撴湀鐨勫紑濮嬫棩鏈燂紙姣忔湀1鍙凤級
+ LocalDate monthStart = currentMonth.withDayOfMonth(1);
+ // 褰撴湀鐨勭粨鏉熸棩鏈燂紙姣忔湀鏈�鍚庝竴澶╋級
+ LocalDate monthEnd = currentMonth.withDayOfMonth(currentMonth.lengthOfMonth());
+
+ // 鏋勫缓褰撴湀鐨勬煡璇㈡潯浠讹紙濡傛灉鎯充竴娆℃�ф煡鍏�4涓湀鏁版嵁鍐嶅唴瀛樼瓫閫夛紝鍙紭鍖栦负鍏堟煡鍏ㄥ啀寰幆绛涢�夛級
+ LambdaQueryWrapper<QualityInspect> queryWrapper = new LambdaQueryWrapper<>();
+ queryWrapper.ge(QualityInspect::getCheckTime, monthStart)
+ .le(QualityInspect::getCheckTime, monthEnd); // 绛涢�夊綋鏈堟暟鎹�
+ List<QualityInspect> monthInspects = qualityStatisticsMapper.selectList(queryWrapper);
+ BigDecimal reduce = monthInspects.stream()
+ .filter(inspect -> inspect.getInspectType().equals(0))
.map(QualityInspect::getQuantity)
- .reduce(BigDecimal.ZERO, BigDecimal::add)
- );
- qualityStatisticsItem.setFactoryNum(qualityInspects.stream()
- .filter(item -> item.getInspectType().equals(1) && "涓嶅悎鏍�".equals(item.getCheckResult())
- && (startTime.isEqual(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) || startTime.isAfter(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()))
- && endTime.isBefore(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()))
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ supplierNum = supplierNum.add(reduce);
+ BigDecimal reduce1 = monthInspects.stream()
+ .filter(inspect -> inspect.getInspectType().equals(1))
.map(QualityInspect::getQuantity)
- .reduce(BigDecimal.ZERO, BigDecimal::add)
- );
- qualityStatisticsItem.setProcessNum(qualityInspects.stream()
- .filter(item -> item.getInspectType().equals(2) && "涓嶅悎鏍�".equals(item.getCheckResult())
- && (startTime.isEqual(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) || startTime.isAfter(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()))
- && endTime.isBefore(item.getCheckTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()))
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ processNum = processNum.add(reduce1);
+ BigDecimal reduce2 = monthInspects.stream()
+ .filter(inspect -> inspect.getInspectType().equals(2))
.map(QualityInspect::getQuantity)
- .reduce(BigDecimal.ZERO, BigDecimal::add));
- qualityStatisticsItems.add(qualityStatisticsItem);
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ factoryNum = factoryNum.add(reduce2);
+
+ // 鏋勫缓褰撴湀缁熻椤�
+ QualityStatisticsItem item = new QualityStatisticsItem();
+ item.setDate(monthStart.format(monthFormatter)); // 鏃ユ湡鏄剧ず涓衡�滃勾鏈堚�濓紙濡� 2025-10锛�
+
+ // 1. 渚涘簲鍟嗘楠岋紙绫诲瀷0锛�- 鍚堟牸鏁伴噺
+ BigDecimal supplierQualified = monthInspects.stream()
+ .filter(inspect -> inspect.getInspectType().equals(0)
+ && "鍚堟牸".equals(inspect.getCheckResult()))
+ .map(QualityInspect::getQuantity)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ item.setSupplierNum(supplierQualified);
+
+ // 2. 宸ュ簭妫�楠岋紙绫诲瀷1锛�- 鍚堟牸鏁伴噺
+ BigDecimal processQualified = monthInspects.stream()
+ .filter(inspect -> inspect.getInspectType().equals(1)
+ && "鍚堟牸".equals(inspect.getCheckResult()))
+ .map(QualityInspect::getQuantity)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ item.setProcessNum(processQualified);
+
+ // 3. 宸ュ巶妫�楠岋紙绫诲瀷2锛�- 鍚堟牸鏁伴噺
+ BigDecimal factoryQualified = monthInspects.stream()
+ .filter(inspect -> inspect.getInspectType().equals(2)
+ && "鍚堟牸".equals(inspect.getCheckResult()))
+ .map(QualityInspect::getQuantity)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ item.setFactoryNum(factoryQualified);
+
+ qualityStatisticsItems.add(item);
}
+ // 缁熻杩�4涓湀鎬绘暟鎹紙鎵�鏈夋湀浠芥眹鎬伙級
+ qualityStatisticsDto.setProcessNum(processNum);
+ qualityStatisticsDto.setSupplierNum(supplierNum);
+ qualityStatisticsDto.setFactoryNum(factoryNum);
qualityStatisticsDto.setItem(qualityStatisticsItems);
+
return qualityStatisticsDto;
}
@Override
- public List<ApproveProcess> todos() {
+ public List<ApproveProcess> todos() throws ParseException {
LoginUser loginUser = SecurityUtils.getLoginUser();
LambdaQueryWrapper<ApproveProcess> approveProcessLambdaQueryWrapper = new LambdaQueryWrapper<>();
approveProcessLambdaQueryWrapper.eq(ApproveProcess::getApproveDelete, 0)
.eq(ApproveProcess::getApproveUserCurrentId, loginUser.getUserId())
- .ne(ApproveProcess::getApproveStatus, 2)
- .eq(ApproveProcess::getTenantId, loginUser.getTenantId());
- return approveProcessMapper.selectList(approveProcessLambdaQueryWrapper);
+ .ne(ApproveProcess::getApproveStatus, 2);
+// .eq(ApproveProcess::getTenantId, loginUser.getTenantId());
+ List<ApproveProcess> approveProcesses = approveProcessMapper.selectList(approveProcessLambdaQueryWrapper);
+ if (CollectionUtils.isEmpty(approveProcesses)) {
+ approveProcesses = new ArrayList<>();
+ }
+
+ approveProcesses.forEach(a -> {
+ if (a.getApproveType() != null) {
+ a.setApproveTypeName(ApproveTypeEnum.getNameByCode(a.getApproveType()));
+ }
+ });
+// // 鏌ヨ鏈鐢ㄥ姵淇濊褰�
+// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+//
+// LaborIssue laborIssue1 = new LaborIssue();
+// laborIssue1.setAdoptedDate(new Date());
+// laborIssue1.setIssueDate(sdf.parse(sdf.format(new Date())));
+// List<LaborIssue> laborIssues = lavorIssueMapper.list(laborIssue1); //staff_join_leave_record琛ㄨ鍒犻櫎
+// if(!CollectionUtils.isEmpty(laborIssues)){
+// for (LaborIssue laborIssue : laborIssues) {
+// ApproveProcess approveProcess = new ApproveProcess();
+// approveProcess.setApproveId(laborIssue.getOrderNo());
+// approveProcess.setApproveDeptName(sysDeptMapper.selectDeptById(loginUser.getTenantId()).getDeptName());
+// approveProcess.setApproveTime(laborIssue.getIssueDate());
+// approveProcess.setApproveReason(laborIssue.getDictTypeName() + "-" + laborIssue.getDictName() + "瓒呮椂鏈鍙�");
+// approveProcesses.add(approveProcess);
+// }
+// }
+
+
+ return approveProcesses;
}
/**
- *
* @param type 1-鍛� 2-鏈� 3-瀛e害
* @return
*/
@@ -313,7 +419,7 @@
LocalDate today = LocalDate.now();
LocalDate startDate = null;
LocalDate endDate = null;
- switch (type){
+ switch (type) {
case 1:
// 鑾峰彇鏈懆鍛ㄤ竴
startDate = today.with(DayOfWeek.MONDAY);
@@ -337,32 +443,1040 @@
}
// 搴旀敹
List<SalesLedger> salesLedgers = salesLedgerMapper.selectList(new LambdaQueryWrapper<SalesLedger>()
- .ge(SalesLedger::getEntryDate, startDate)
- .lt(SalesLedger::getEntryDate, endDate)
+// .ge(SalesLedger::getEntryDate, startDate)
+// .lt(SalesLedger::getEntryDate, endDate)
);
- BigDecimal receivableMoney = salesLedgers.stream().map(SalesLedger::getContractAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+// BigDecimal receivableMoney = salesLedgers.stream().map(SalesLedger::getContractAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+ BigDecimal receivableMoney = sumAmount(salesLedgers, SalesLedger::getContractAmount);
// 搴斾粯
List<PurchaseLedger> procurementRecords = purchaseLedgerMapper.selectList(new LambdaQueryWrapper<PurchaseLedger>()
- .ge(PurchaseLedger::getEntryDate, startDate)
- .lt(PurchaseLedger::getEntryDate, endDate)
+// .ge(PurchaseLedger::getEntryDate, startDate)
+// .lt(PurchaseLedger::getEntryDate, endDate)
);
- BigDecimal payableMoney = procurementRecords.stream().map(PurchaseLedger::getContractAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+// BigDecimal payableMoney = procurementRecords.stream().map(PurchaseLedger::getContractAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+ BigDecimal payableMoney = sumAmount(procurementRecords, PurchaseLedger::getContractAmount);
// 棰勬敹
List<ReceiptPayment> receiptPayments = receiptPaymentMapper.selectList(new LambdaQueryWrapper<ReceiptPayment>()
- .ge(ReceiptPayment::getReceiptPaymentDate, startDate)
- .lt(ReceiptPayment::getReceiptPaymentDate, endDate));
- BigDecimal advanceMoney = receiptPayments.stream().map(ReceiptPayment::getReceiptPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+// .ge(ReceiptPayment::getReceiptPaymentDate, startDate)
+// .lt(ReceiptPayment::getReceiptPaymentDate, endDate)
+ );
+// BigDecimal advanceMoney = receiptPayments.stream().map(ReceiptPayment::getReceiptPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+ BigDecimal advanceMoney = sumAmount(receiptPayments, ReceiptPayment::getReceiptPaymentAmount);
// 棰勪粯
List<PaymentRegistration> paymentRegistrations = paymentRegistrationMapper.selectList(new LambdaQueryWrapper<PaymentRegistration>()
- .ge(PaymentRegistration::getPaymentDate, startDate)
- .lt(PaymentRegistration::getPaymentDate, endDate));
- BigDecimal prepayMoney = paymentRegistrations.stream().map(PaymentRegistration::getCurrentPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+// .ge(PaymentRegistration::getPaymentDate, startDate)
+// .lt(PaymentRegistration::getPaymentDate, endDate)
+ );
+// BigDecimal prepayMoney = paymentRegistrations.stream().map(PaymentRegistration::getCurrentPaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+ BigDecimal prepayMoney = sumAmount(paymentRegistrations, PaymentRegistration::getCurrentPaymentAmount);
StatisticsReceivablePayableDto statisticsReceivablePayableDto = new StatisticsReceivablePayableDto();
- statisticsReceivablePayableDto.setPayableMoney(payableMoney);
- statisticsReceivablePayableDto.setReceivableMoney(receivableMoney);
+ statisticsReceivablePayableDto.setPayableMoney(payableMoney.subtract(prepayMoney));
+ statisticsReceivablePayableDto.setReceivableMoney(receivableMoney.subtract(advanceMoney));
statisticsReceivablePayableDto.setAdvanceMoney(advanceMoney);
statisticsReceivablePayableDto.setPrepayMoney(prepayMoney);
return statisticsReceivablePayableDto;
}
+
+ public static <T> BigDecimal sumAmount(List<T> list, java.util.function.Function<T, BigDecimal> amountExtractor) {
+ return list.stream()
+ // 鎻愬彇閲戦鏃讹紝灏唍ull鏇挎崲涓築igDecimal.ZERO
+ .map(item -> Optional.ofNullable(amountExtractor.apply(item)).orElse(BigDecimal.ZERO))
+ // 绱姞锛屽垵濮嬪�间负0锛岄伩鍏嶇┖娴侀棶棰�
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ }
+
+ @Autowired
+ private DeviceRepairMapper deviceRepairMapper;
+
+ @Override
+ public Map<String, Object> approveAndDeviceTodos() {
+ // 瀹℃壒鍗忓悓寰呭姙
+ Long aLong = approveProcessMapper.selectCount(new LambdaQueryWrapper<ApproveProcess>()
+ .eq(ApproveProcess::getApproveUserCurrentId, SecurityUtils.getUserId())
+ .eq(ApproveProcess::getApproveDelete, 0)
+ .in(ApproveProcess::getApproveStatus, 0, 1, 3));
+ // 璁惧鎶ヤ慨寰呭姙
+ Long aLong1 = deviceRepairMapper.selectCount(new LambdaQueryWrapper<DeviceRepair>()
+ .eq(DeviceRepair::getStatus, 0)
+ .eq(DeviceRepair::getRepairName, SecurityUtils.getLoginUser().getNickName()));
+ return new HashMap<String, Object>() {{
+ put("approveTodo", aLong);
+ put("deviceRepairTodo", aLong1);
+ }};
+ }
+
+ @Override
+ public Long noticesCount() {
+ // 鏌ヨ鏈繃鏈熺殑閫氱煡鏁伴噺锛氱姸鎬佷负鍙戝竷涓旇繃鏈熸椂闂村ぇ浜庣瓑浜庡綋鍓嶆棩鏈�
+ return noticeMapper.selectCount(new LambdaQueryWrapper<Notice>()
+ .eq(Notice::getStatus, 1) // 1琛ㄧず鍙戝竷鐘舵��
+ .ge(Notice::getExpirationDate, new Date())); // 杩囨湡鏃堕棿澶т簬绛変簬褰撳墠鏃ユ湡
+ }
+
+ @Override
+ public ProductionProgressDto productionProgress() {
+ ProductionProgressDto productionProgressDto = new ProductionProgressDto();
+ ProductOrderDto orderDto = new ProductOrderDto();
+ orderDto.setStartTime(LocalDateTime.now().minusMonths(1));
+ orderDto.setEndTime(LocalDateTime.now());
+ List<ProductOrderDto> productOrderDtos = productOrderMapper.pageProductOrder(new Page<>(1, -1), orderDto).getRecords();
+ productionProgressDto.setCompletedOrderDetails(productOrderDtos);
+ long totalCount = productOrderDtos.size();
+ long count = productOrderDtos.stream().filter(productOrderDto -> productOrderDto.getCompleteQuantity().compareTo(productOrderDto.getQuantity()) >= 0).count();
+ long count2 = productOrderDtos.stream().filter(productOrderDto -> productOrderDto.getCompleteQuantity().compareTo(BigDecimal.ZERO) == 0).count();
+ productionProgressDto.setTotalOrderCount(totalCount);
+ productionProgressDto.setCompletedOrderCount(count);
+ productionProgressDto.setUncompletedOrderCount(count2);
+ productionProgressDto.setPartialCompletedOrderCount(totalCount - count - count2);
+ return productionProgressDto;
+ }
+
+ @Override
+ public ProductionTurnoverDto workInProcessTurnover() {
+ ProductionTurnoverDto productionTurnoverDto = new ProductionTurnoverDto();
+ ProductWorkOrderDto workOrder = new ProductWorkOrderDto();
+ workOrder.setPlanStartTime(LocalDate.now().minusMonths(1));
+ workOrder.setPlanEndTime(LocalDate.now());
+ List<ProductWorkOrderDto> productWorkOrders = productWorkOrderMapper.pageProductWorkOrder(new Page<>(1, -1), workOrder).getRecords();
+ long sum = productWorkOrders.stream()
+ .filter(productWorkOrder -> productWorkOrder.getPlanQuantity().compareTo(productWorkOrder.getCompleteQuantity()) > 0)
+ .map(ProductWorkOrder::getPlanQuantity)
+ .mapToLong(BigDecimal::longValue)
+ .sum();
+ if (sum == 0) return null;
+ productionTurnoverDto.setTotalOrderCount(sum);//鎬诲湪鍒跺搧鏁伴噺
+ productionTurnoverDto.setAverageTurnoverDays(BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(ChronoUnit.DAYS.between(LocalDateTime.now().minusMonths(1), LocalDateTime.now())), 2, RoundingMode.HALF_UP));
+ long completeQuantity = productWorkOrders.stream()
+ .filter(productWorkOrder -> productWorkOrder.getCompleteQuantity().compareTo(productWorkOrder.getPlanQuantity()) >= 0)
+ .map(ProductWorkOrder::getCompleteQuantity)
+ .mapToLong(BigDecimal::longValue)
+ .sum();
+ productionTurnoverDto.setTurnoverEfficiency(BigDecimal.valueOf(completeQuantity).divide(BigDecimal.valueOf(sum), 2, RoundingMode.HALF_UP));
+ Map<String, List<ProductWorkOrderDto>> map = productWorkOrders.stream()
+ .filter(productWorkOrder -> productWorkOrder.getPlanQuantity().compareTo(productWorkOrder.getCompleteQuantity()) > 0)
+ .collect(Collectors.groupingBy(ProductWorkOrderDto::getProcessName));
+ List<String> strings = new ArrayList<>();
+ List<Long> processQuantityDetails = new ArrayList<>();
+ map.entrySet().stream().forEach(entry -> {
+ String key = entry.getKey();
+ long completeSum = entry.getValue().stream().map(ProductWorkOrderDto::getCompleteQuantity).mapToLong(BigDecimal::longValue).sum();
+ strings.add(key);
+ processQuantityDetails.add(completeSum);
+ });
+ productionTurnoverDto.setProcessDetails(strings);
+ productionTurnoverDto.setProcessQuantityDetails(processQuantityDetails);
+ return productionTurnoverDto;
+ }
+
+ @Override
+ public DeptStaffDistributionDto deptStaffDistribution() {
+ DeptStaffDistributionDto dto = new DeptStaffDistributionDto();
+ List<MapDto> items = new ArrayList<>();
+
+ // 鏌ヨ鎵�鏈夋甯镐笖鏈垹闄ょ殑閮ㄩ棬
+ List<SysDept> depts = sysDeptMapper.selectDeptList(new SysDept());
+ if (CollectionUtils.isEmpty(depts)) {
+ dto.setItems(items);
+ return dto;
+ }
+
+ long totalUsers = 0;
+ List<Map<String, Object>> countsByDept = new ArrayList<>();
+
+ for (SysDept dept : depts) {
+ if ("0".equals(dept.getStatus()) && "0".equals(dept.getDelFlag())) {
+ Long count = sysUserDeptMapper.selectCount(new LambdaQueryWrapper<SysUserDept>()
+ .eq(SysUserDept::getDeptId, dept.getDeptId()));
+ if (count > 0) {
+ Map<String, Object> map = new HashMap<>();
+ map.put("name", dept.getDeptName());
+ map.put("count", count);
+ countsByDept.add(map);
+ totalUsers += count;
+ }
+ }
+ }
+
+ if (totalUsers > 0) {
+ BigDecimal total = BigDecimal.valueOf(totalUsers);
+ for (Map<String, Object> map : countsByDept) {
+ MapDto mapDto = new MapDto();
+ mapDto.setName((String) map.get("name"));
+ Long count = (Long) map.get("count");
+ mapDto.setValue(count.toString());
+ mapDto.setRate(BigDecimal.valueOf(count).multiply(new BigDecimal("100"))
+ .divide(total, 2, RoundingMode.HALF_UP).toString());
+ items.add(mapDto);
+ }
+ }
+
+ dto.setTotal(totalUsers);
+ dto.setItems(items);
+ return dto;
+ }
+
+ @Override
+ public HomeSummaryDto summaryStatistics() {
+ HomeSummaryDto dto = new HomeSummaryDto();
+ LocalDate now = LocalDate.now();
+ YearMonth currentMonth = YearMonth.from(now);
+ YearMonth prevMonth = currentMonth.minusMonths(1);
+
+ LocalDateTime currentMonthEnd = currentMonth.atEndOfMonth().atTime(23, 59, 59);
+ LocalDateTime prevMonthEnd = prevMonth.atEndOfMonth().atTime(23, 59, 59);
+
+ // 鎬诲伐浣滀汉鍛�
+ Long currentStaff = countStaff(currentMonthEnd);
+ Long prevStaff = countStaff(prevMonthEnd);
+ dto.setTotalStaff(currentStaff);
+ dto.setStaffGrowthRate(calculateMoM(currentStaff, prevStaff));
+
+ // 鎬诲鎴锋暟
+ Long currentCustomers = countCustomers(currentMonthEnd);
+ Long prevCustomers = countCustomers(prevMonthEnd);
+ dto.setTotalCustomer(currentCustomers);
+ dto.setCustomerGrowthRate(calculateMoM(currentCustomers, prevCustomers));
+
+ // 鎬讳緵搴斿晢鏁�
+ Long currentSuppliers = countSuppliers(currentMonthEnd);
+ Long prevSuppliers = countSuppliers(prevMonthEnd);
+ dto.setTotalSupplier(currentSuppliers);
+ dto.setSupplierGrowthRate(calculateMoM(currentSuppliers, prevSuppliers));
+
+ return dto;
+ }
+
+ private Long countStaff(LocalDateTime dateTime) {
+ Long sysUserCount = sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>()
+ .eq(SysUser::getDelFlag, "0")
+ .le(SysUser::getCreateTime, dateTime));
+ Long staffCountItem = staffOnJobMapper.selectCount(new LambdaQueryWrapper<StaffOnJob>()
+ .le(StaffOnJob::getCreateTime, dateTime));
+ return sysUserCount + staffCountItem;
+ }
+
+
+ private Long countCustomers(LocalDateTime dateTime) {
+ return customerMapper.selectCount(new LambdaQueryWrapper<Customer>()
+ .le(Customer::getMaintenanceTime, dateTime.toLocalDate()));
+ }
+
+ private Long countSuppliers(LocalDateTime dateTime) {
+ return supplierManageMapper.selectCount(new LambdaQueryWrapper<SupplierManage>()
+ .le(SupplierManage::getCreateTime, dateTime));
+ }
+
+ private String calculateMoM(Number current, Number prev) {
+ BigDecimal curVal = new BigDecimal(current.toString());
+ BigDecimal prevVal = new BigDecimal(prev.toString());
+ if (prevVal.compareTo(BigDecimal.ZERO) == 0) {
+ return curVal.compareTo(BigDecimal.ZERO) > 0 ? "100.00" : "0.00";
+ }
+ return curVal.subtract(prevVal)
+ .divide(prevVal, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ }
+
+ @Override
+ public List<SupplierPurchaseRankingDto> supplierPurchaseRanking(Integer type) {
+ LocalDate today = LocalDate.now();
+ LocalDate startDate;
+ LocalDate endDate;
+ switch (type) {
+ case 1: // 鍛�
+ startDate = today.with(DayOfWeek.MONDAY);
+ endDate = today.with(DayOfWeek.SUNDAY);
+ break;
+ case 2: // 鏈�
+ startDate = today.with(TemporalAdjusters.firstDayOfMonth());
+ endDate = today.with(TemporalAdjusters.lastDayOfMonth());
+ break;
+ case 3: // 瀛e害
+ Month currentMonth = today.getMonth();
+ Month firstMonthOfQuarter = currentMonth.firstMonthOfQuarter();
+ Month lastMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
+
+ startDate = today.withMonth(firstMonthOfQuarter.getValue()).with(TemporalAdjusters.firstDayOfMonth());
+ endDate = today.withMonth(lastMonthOfQuarter.getValue()).with(TemporalAdjusters.lastDayOfMonth());
+ break;
+ default:
+ return new ArrayList<>();
+ }
+
+ QueryWrapper<PurchaseLedger> queryWrapper = new QueryWrapper<>();
+ queryWrapper.select("supplier_name", "SUM(contract_amount) as total_amount")
+ .ge("entry_date", startDate)
+ .le("entry_date", endDate)
+// .ne("approval_status", 3)
+ .groupBy("supplier_name")
+ .orderByDesc("total_amount")
+ .last("LIMIT 5");
+
+ List<Map<String, Object>> maps = purchaseLedgerMapper.selectMaps(queryWrapper);
+ return maps.stream().map(map -> {
+ SupplierPurchaseRankingDto dto = new SupplierPurchaseRankingDto();
+ dto.setSupplierName(map.get("supplier_name") != null ? map.get("supplier_name").toString() : "");
+ Object amount = map.get("total_amount");
+ dto.setTotalAmount(amount != null ? new BigDecimal(amount.toString()) : BigDecimal.ZERO);
+ return dto;
+ }).collect(Collectors.toList());
+ }
+
+ @Override
+ public CustomerRevenueAnalysisDto customerRevenueAnalysis(Long customerId, Integer type) {
+ CustomerRevenueAnalysisDto dto = new CustomerRevenueAnalysisDto();
+ List<MapDto> items = new ArrayList<>();
+ LocalDate today = LocalDate.now();
+
+ LocalDate start;
+ LocalDate end;
+ boolean groupByMonth = false;
+
+ switch (type) {
+ case 1: // 鍛�
+ start = today.with(DayOfWeek.MONDAY);
+ end = today.with(DayOfWeek.SUNDAY);
+ break;
+ case 2: // 鏈�
+ start = today.with(TemporalAdjusters.firstDayOfMonth());
+ end = today.with(TemporalAdjusters.lastDayOfMonth());
+ break;
+ case 3: // 瀛e害
+ Month firstMonthOfQuarter = today.getMonth().firstMonthOfQuarter();
+ start = today.withMonth(firstMonthOfQuarter.getValue()).with(TemporalAdjusters.firstDayOfMonth());
+ end = today.withMonth(firstMonthOfQuarter.plus(2).getValue()).with(TemporalAdjusters.lastDayOfMonth());
+ groupByMonth = true;
+ break;
+ default:
+ dto.setItems(items);
+ return dto;
+ }
+
+ List<SalesLedger> list = salesLedgerMapper.selectList(new LambdaQueryWrapper<SalesLedger>()
+ .eq(SalesLedger::getCustomerId, customerId)
+ .ge(SalesLedger::getEntryDate, start)
+ .le(SalesLedger::getEntryDate, end));
+
+ if (groupByMonth) {
+ for (int i = 0; i < 3; i++) {
+ LocalDate m = start.plusMonths(i);
+ String monthName = m.getMonthValue() + "鏈�";
+ BigDecimal sum = list.stream()
+ .filter(l -> l.getEntryDate() != null)
+ .filter(l -> {
+ LocalDate ld = l.getEntryDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
+ return ld.getMonth() == m.getMonth() && ld.getYear() == m.getYear();
+ })
+ .map(SalesLedger::getContractAmount)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ MapDto mapDto = new MapDto();
+ mapDto.setName(monthName);
+ mapDto.setValue(sum.setScale(2, RoundingMode.HALF_UP).toString());
+ items.add(mapDto);
+ }
+ } else {
+ long days = ChronoUnit.DAYS.between(start, end) + 1;
+ for (int i = 0; i < days; i++) {
+ LocalDate d = start.plusDays(i);
+ String dayName = d.getMonthValue() + "/" + d.getDayOfMonth();
+ BigDecimal sum = list.stream()
+ .filter(l -> l.getEntryDate() != null)
+ .filter(l -> l.getEntryDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().equals(d))
+ .map(SalesLedger::getContractAmount)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ MapDto mapDto = new MapDto();
+ mapDto.setName(dayName);
+ mapDto.setValue(sum.setScale(2, RoundingMode.HALF_UP).toString());
+ items.add(mapDto);
+ }
+ }
+
+ dto.setItems(items);
+ return dto;
+ }
+
+ @Override
+ public ProductCategoryDistributionDto productCategoryDistribution() {
+ ProductCategoryDistributionDto dto = new ProductCategoryDistributionDto();
+ List<ProductCategoryDistributionDto.MajorCategoryDto> majorItems = new ArrayList<>();
+
+ // 鏌ヨ鎵�鏈夌殑浜у搧绫诲埆
+ List<Product> allProducts = productMapper.selectList(new LambdaQueryWrapper<>());
+ if (CollectionUtils.isEmpty(allProducts)) {
+ dto.setItems(majorItems);
+ return dto;
+ }
+
+ // 鍒嗙澶х被鍜屽皬绫�
+ List<Product> majorCategories = allProducts.stream()
+ .filter(p -> p.getParentId() == null)
+ .collect(Collectors.toList());
+ List<Product> minorCategories = allProducts.stream()
+ .filter(p -> p.getParentId() != null)
+ .collect(Collectors.toList());
+
+ // 鎸夌埗绫籌D瀵瑰皬绫昏繘琛屽垎缁�
+ Map<Long, List<Product>> minorGroupMap = minorCategories.stream()
+ .collect(Collectors.groupingBy(Product::getParentId));
+
+ int totalMinorCount = minorCategories.size();
+
+ for (Product major : majorCategories) {
+ ProductCategoryDistributionDto.MajorCategoryDto majorDto = new ProductCategoryDistributionDto.MajorCategoryDto();
+ majorDto.setName(major.getProductName());
+
+ List<Product> children = minorGroupMap.getOrDefault(major.getId(), new ArrayList<>());
+ int childrenSize = children.size();
+ // 璁剧疆灏忕被鐨勬�绘暟
+ majorDto.setValue(String.valueOf(childrenSize));
+
+ // 璁$畻鍗犳瘮
+ if (totalMinorCount > 0) {
+ BigDecimal rate = BigDecimal.valueOf(childrenSize)
+ .multiply(new BigDecimal("100"))
+ .divide(BigDecimal.valueOf(totalMinorCount), 2, RoundingMode.HALF_UP);
+ majorDto.setRate(rate.toString());
+ } else {
+ majorDto.setRate("0.00");
+ }
+
+ List<ProductCategoryDistributionDto.MinorCategoryDto> minorDtos = new ArrayList<>();
+ for (Product minor : children) {
+ ProductCategoryDistributionDto.MinorCategoryDto minorDto = new ProductCategoryDistributionDto.MinorCategoryDto();
+ minorDto.setName(minor.getProductName());
+ minorDto.setValue("0");
+ minorDto.setRate("0.00");
+ minorDto.setChildren(new ArrayList<>());
+ minorDtos.add(minorDto);
+ }
+ majorDto.setChildren(minorDtos);
+ majorItems.add(majorDto);
+ }
+
+ dto.setItems(majorItems);
+ return dto;
+ }
+
+ @Override
+ public List<CustomerContributionRankingDto> customerContributionRanking(Integer type) {
+ LocalDate today = LocalDate.now();
+ LocalDate startDate = null;
+ LocalDate endDate = null;
+ switch (type) {
+ case 1:
+ startDate = today.with(DayOfWeek.MONDAY);
+ endDate = today.with(DayOfWeek.SUNDAY);
+ break;
+ case 2:
+ startDate = today.with(TemporalAdjusters.firstDayOfMonth());
+ endDate = today.with(TemporalAdjusters.lastDayOfMonth());
+ break;
+ case 3:
+ Month currentMonth = today.getMonth();
+ Month firstMonthOfQuarter = currentMonth.firstMonthOfQuarter();
+ Month lastMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
+ startDate = today.withMonth(firstMonthOfQuarter.getValue()).with(TemporalAdjusters.firstDayOfMonth());
+ endDate = today.withMonth(lastMonthOfQuarter.getValue()).with(TemporalAdjusters.lastDayOfMonth());
+ break;
+ }
+
+ QueryWrapper<SalesLedger> queryWrapper = new QueryWrapper<>();
+ queryWrapper.select("customer_name", "SUM(contract_amount) as total_amount")
+ .isNotNull("customer_name")
+ .groupBy("customer_name")
+ .orderByDesc("total_amount")
+ .last("LIMIT 5");
+
+ if (startDate != null && endDate != null) {
+ queryWrapper.between("entry_date", startDate, endDate);
+ }
+
+ List<Map<String, Object>> maps = salesLedgerMapper.selectMaps(queryWrapper);
+ List<CustomerContributionRankingDto> result = new ArrayList<>();
+ for (Map<String, Object> map : maps) {
+ CustomerContributionRankingDto rankingDto = new CustomerContributionRankingDto();
+ rankingDto.setCustomerName(map.get("customer_name").toString());
+ rankingDto.setTotalAmount(map.get("total_amount") != null ? new BigDecimal(map.get("total_amount").toString()) : BigDecimal.ZERO);
+ result.add(rankingDto);
+ }
+ return result;
+ }
+
+ @Override
+ public List<MapDto> productSalesAnalysis() {
+ // 鑾峰彇鎵�鏈変骇鍝佸ぇ绫荤殑閿�鍞
+ List<Map<String, Object>> analysisResults = salesLedgerProductMapper.selectProductSalesAnalysis();
+ if (CollectionUtils.isEmpty(analysisResults)) {
+ return new ArrayList<>();
+ }
+
+ // 璁$畻鎬婚攢鍞
+ BigDecimal totalSalesAmount = analysisResults.stream()
+ .map(r -> (BigDecimal) r.get("value"))
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+ return analysisResults.stream()
+ .map(result -> {
+ MapDto mapDto = new MapDto();
+ String name = (String) result.get("name");
+ BigDecimal value = (BigDecimal) result.get("value");
+
+ mapDto.setName(name);
+ mapDto.setValue(value != null ? value.setScale(2, RoundingMode.HALF_UP).toString() : "0.00");
+
+ if (totalSalesAmount.compareTo(BigDecimal.ZERO) == 0 || value == null) {
+ mapDto.setRate("0.00");
+ } else {
+ String rate = value.divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ mapDto.setRate(rate);
+ }
+ return mapDto;
+ })
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public List<MapDto> rawMaterialPurchaseAmountRatio() {
+ // 鑾峰彇鎵�鏈夊師鏉愭枡鐨勯噰璐
+ List<Map<String, Object>> analysisResults = salesLedgerProductMapper.selectRawMaterialPurchaseAnalysis();
+ if (CollectionUtils.isEmpty(analysisResults)) {
+ return new ArrayList<>();
+ }
+
+ // 璁$畻鎬婚噰璐
+ BigDecimal totalPurchaseAmount = analysisResults.stream()
+ .map(r -> (BigDecimal) r.get("value"))
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+ return analysisResults.stream()
+ .map(result -> {
+ MapDto mapDto = new MapDto();
+ String name = (String) result.get("name");
+ BigDecimal value = (BigDecimal) result.get("value");
+
+ mapDto.setName(name);
+ mapDto.setValue(value != null ? value.setScale(2, RoundingMode.HALF_UP).toString() : "0.00");
+
+ if (totalPurchaseAmount.compareTo(BigDecimal.ZERO) == 0 || value == null) {
+ mapDto.setRate("0.00");
+ } else {
+ String rate = value.divide(totalPurchaseAmount, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ mapDto.setRate(rate);
+ }
+ return mapDto;
+ })
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public List<MapDto> salesPurchaseStorageProductCount() {
+ LocalDate now = LocalDate.now();
+ DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+
+ String currentMonthStart = now.with(TemporalAdjusters.firstDayOfMonth()).format(dtf);
+ String currentMonthNow = now.format(dtf);
+
+ LocalDate lastMonth = now.minusMonths(1);
+ String lastMonthStart = lastMonth.with(TemporalAdjusters.firstDayOfMonth()).format(dtf);
+ String lastMonthEnd = lastMonth.with(TemporalAdjusters.lastDayOfMonth()).format(dtf);
+
+ // 閿�鍞�
+ int currentSales = salesLedgerProductMapper.selectProductCountByTypeAndDate(1, currentMonthStart, currentMonthNow);
+ int lastSales = salesLedgerProductMapper.selectProductCountByTypeAndDate(1, lastMonthStart, lastMonthEnd);
+
+ // 閲囪喘
+ int currentPurchase = salesLedgerProductMapper.selectProductCountByTypeAndDate(2, currentMonthStart, currentMonthNow);
+ int lastPurchase = salesLedgerProductMapper.selectProductCountByTypeAndDate(2, lastMonthStart, lastMonthEnd);
+
+ // 鍌ㄥ瓨
+ int currentStorage = stockInventoryMapper.selectStorageProductCountByDate(currentMonthStart, currentMonthNow);
+ int lastStorage = stockInventoryMapper.selectStorageProductCountByDate(lastMonthStart, lastMonthEnd);
+
+ List<MapDto> list = new ArrayList<>();
+ list.add(createMapDto("閿�鍞骇鍝佹暟", currentSales, lastSales));
+ list.add(createMapDto("閲囪喘浜у搧鏁�", currentPurchase, lastPurchase));
+ list.add(createMapDto("鍌ㄥ瓨浜у搧鏁�", currentStorage, lastStorage));
+
+ return list;
+ }
+
+ private MapDto createMapDto(String name, int current, int last) {
+ MapDto dto = new MapDto();
+ dto.setName(name);
+ dto.setValue(String.valueOf(current));
+
+ if (last == 0) {
+ dto.setRate(current > 0 ? "100.00" : "0.00");
+ } else {
+ BigDecimal curDec = new BigDecimal(current);
+ BigDecimal lastDec = new BigDecimal(last);
+ // 澧為暱鐜�
+ String rate = curDec.subtract(lastDec)
+ .divide(lastDec, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ dto.setRate(rate);
+ }
+ return dto;
+ }
+
+ @Override
+ public List<Map<String, Object>> productInOutAnalysis(Integer type) {
+ String targetName;
+ if (type == 1) {
+ targetName = "鍘熸潗鏂�";
+ } else if (type == 2) {
+ targetName = "鎴愬搧";
+ } else if (type == 3) {
+ targetName = "鍗婃垚鍝�";
+ } else {
+ return new ArrayList<>();
+ }
+
+ LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
+ queryWrapper.eq(Product::getProductName, targetName).isNull(Product::getParentId);
+ Product rootCategory = productMapper.selectOne(queryWrapper);
+
+ if (rootCategory == null) {
+ log.warn("鏈壘鍒板悕绉颁负 {} 鐨勯《绾т骇鍝佸垎绫�", targetName);
+ return new ArrayList<>();
+ }
+ Long rootCategoryId = rootCategory.getId();
+
+ LocalDate now = LocalDate.now();
+ DateTimeFormatter displayDtf = DateTimeFormatter.ofPattern("M/d");
+
+ String startDate = now.minusDays(6).toString();
+ String endDate = now.toString();
+
+ List<Map<String, Object>> inCounts = stockInventoryMapper.selectDailyStockInCounts(rootCategoryId, startDate, endDate + " 23:59:59");
+
+ List<Map<String, Object>> outCounts = stockInventoryMapper.selectDailyStockOutCounts(rootCategoryId, startDate, endDate + " 23:59:59");
+
+ Map<LocalDate, BigDecimal> inMap = inCounts.stream()
+ .collect(Collectors.toMap(
+ m -> ((java.sql.Date) m.get("date")).toLocalDate(),
+ m -> (BigDecimal) m.get("count"),
+ BigDecimal::add
+ ));
+
+ Map<LocalDate, BigDecimal> outMap = outCounts.stream()
+ .collect(Collectors.toMap(
+ m -> ((java.sql.Date) m.get("date")).toLocalDate(),
+ m -> (BigDecimal) m.get("count"),
+ BigDecimal::add
+ ));
+
+ List<Map<String, Object>> result = new ArrayList<>();
+
+ for (int i = 6; i >= 0; i--) {
+ LocalDate date = now.minusDays(i);
+
+ Map<String, Object> dataPoint = new LinkedHashMap<>();
+ dataPoint.put("date", date.format(displayDtf)); // 1/23
+ dataPoint.put("inCount", inMap.getOrDefault(date, BigDecimal.ZERO));
+ dataPoint.put("outCount", outMap.getOrDefault(date, BigDecimal.ZERO));
+
+ result.add(dataPoint);
+ }
+
+ return result;
+ }
+
+ @Override
+ public List<MapDto> productTurnoverDays() {
+ return homeMapper.productTurnoverDays();
+ }
+
+ @Autowired
+ private AccountExpenseMapper accountExpenseMapper;
+
+ @Autowired
+ private AccountIncomeMapper accountIncomeMapper;
+
+
+ public List<Map<String, Object>> incomeExpenseAnalysis(Integer type) {
+
+ LocalDate today = LocalDate.now();
+ LocalDate startDate;
+ LocalDate endDate;
+ String dateFormat;
+ DateTimeFormatter formatter;
+ List<String> xAxis = new ArrayList<>();
+
+ // 1. 鏃堕棿鑼冨洿 & X 杞�
+ if (type == 3) {
+ // 鏈搴︼紙鎸夋湀锛�
+ Month currentMonth = today.getMonth();
+ Month firstMonthOfQuarter = currentMonth.firstMonthOfQuarter();
+ startDate = today.withMonth(firstMonthOfQuarter.getValue())
+ .with(TemporalAdjusters.firstDayOfMonth());
+ endDate = startDate.plusMonths(2)
+ .with(TemporalAdjusters.lastDayOfMonth());
+
+ dateFormat = "%Y-%m";
+ formatter = DateTimeFormatter.ofPattern("yyyy-MM");
+
+ LocalDate tmp = startDate;
+ while (!tmp.isAfter(endDate)) {
+ xAxis.add(tmp.format(formatter));
+ tmp = tmp.plusMonths(1);
+ }
+
+ } else {
+ // 鍛� / 鏈堬紙鎸夊ぉ锛�
+ dateFormat = "%Y-%m-%d";
+ formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+
+ if (type == 1) {
+ startDate = today.with(DayOfWeek.MONDAY);
+ endDate = today.with(DayOfWeek.SUNDAY);
+ } else {
+ startDate = today.with(TemporalAdjusters.firstDayOfMonth());
+ endDate = today.with(TemporalAdjusters.lastDayOfMonth());
+ }
+
+ LocalDate tmp = startDate;
+ while (!tmp.isAfter(endDate)) {
+ xAxis.add(tmp.format(formatter));
+ tmp = tmp.plusDays(1);
+ }
+ }
+
+ String startStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+ String endStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+
+ // 2. 鏌ヨ鏁版嵁
+ List<IncomeExpenseAnalysisDto> incomeList = accountIncomeMapper.selectIncomeStats(startStr, endStr, dateFormat);
+
+// List<IncomeExpenseAnalysisDto> purchaseList =
+// purchaseLedgerMapper.selectPurchaseStats(startStr, endStr, dateFormat);
+
+ List<IncomeExpenseAnalysisDto> expenseList = accountExpenseMapper.selectAccountExpenseStats(startStr, endStr, dateFormat);
+
+ // 3. 杞� Map锛堣嚜鍔ㄥ悎骞讹級
+ Map<String, BigDecimal> incomeMap = incomeList.stream()
+ .collect(Collectors.toMap(
+ IncomeExpenseAnalysisDto::getDateStr,
+ IncomeExpenseAnalysisDto::getAmount,
+ BigDecimal::add));
+
+// Map<String, BigDecimal> purchaseMap = purchaseList.stream()
+// .collect(Collectors.toMap(
+// IncomeExpenseAnalysisDto::getDateStr,
+// IncomeExpenseAnalysisDto::getAmount,
+// BigDecimal::add));
+
+ Map<String, BigDecimal> expenseMap = expenseList.stream()
+ .collect(Collectors.toMap(
+ IncomeExpenseAnalysisDto::getDateStr,
+ IncomeExpenseAnalysisDto::getAmount,
+ BigDecimal::add));
+
+ // 4. 缁勮杩斿洖
+ List<Map<String, Object>> result = new ArrayList<>();
+
+ for (String dateStr : xAxis) {
+ Map<String, Object> item = new HashMap<>();
+ item.put("date", dateStr);
+
+ // 鏀跺叆
+ BigDecimal income = incomeMap.getOrDefault(dateStr, BigDecimal.ZERO);
+ item.put("income", income.setScale(2, RoundingMode.HALF_UP));
+
+ // 鏀嚭 = 閲囪喘 + 璐㈠姟鏀嚭
+// BigDecimal purchase = purchaseMap.getOrDefault(dateStr, BigDecimal.ZERO);
+ BigDecimal expense = expenseMap.getOrDefault(dateStr, BigDecimal.ZERO);
+// BigDecimal totalExpense = purchase.add(expense);
+ BigDecimal totalExpense = expense;
+
+ item.put("expense", totalExpense.setScale(2, RoundingMode.HALF_UP));
+
+ result.add(item);
+ }
+
+ return result;
+ }
+
+
+ @Override
+ public List<MapDto> profitTrendAnalysis() {
+ LocalDate today = LocalDate.now();
+ LocalDate startDate = today.minusMonths(11).with(TemporalAdjusters.firstDayOfMonth());
+ LocalDate endDate = today.with(TemporalAdjusters.lastDayOfMonth());
+
+ String dateFormat = "%Y-%m";
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
+
+ List<String> months = new ArrayList<>();
+ LocalDate temp = startDate;
+ while (!temp.isAfter(endDate)) {
+ months.add(temp.format(formatter));
+ temp = temp.plusMonths(1);
+ }
+
+ String startStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+ String endStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+
+// List<IncomeExpenseAnalysisDto> incomeList = salesLedgerMapper.selectIncomeStats(startStr, endStr, dateFormat);
+ List<IncomeExpenseAnalysisDto> incomeList = new ArrayList<>();
+ List<IncomeExpenseAnalysisDto> purchaseList = purchaseLedgerMapper.selectPurchaseStats(startStr, endStr, dateFormat);
+ List<IncomeExpenseAnalysisDto> expenseList = accountExpenseMapper.selectAccountExpenseStats(startStr, endStr, dateFormat);
+
+ Map<String, BigDecimal> incomeMap = incomeList.stream().collect(Collectors.toMap(IncomeExpenseAnalysisDto::getDateStr, IncomeExpenseAnalysisDto::getAmount, BigDecimal::add));
+ Map<String, BigDecimal> purchaseMap = purchaseList.stream().collect(Collectors.toMap(IncomeExpenseAnalysisDto::getDateStr, IncomeExpenseAnalysisDto::getAmount, BigDecimal::add));
+ Map<String, BigDecimal> expenseMap = expenseList.stream().collect(Collectors.toMap(IncomeExpenseAnalysisDto::getDateStr, IncomeExpenseAnalysisDto::getAmount, BigDecimal::add));
+
+ List<MapDto> result = new ArrayList<>();
+
+ for (String month : months) {
+ MapDto dto = new MapDto();
+ dto.setName(month);
+
+ BigDecimal income = incomeMap.getOrDefault(month, BigDecimal.ZERO);
+
+ BigDecimal purchase = purchaseMap.getOrDefault(month, BigDecimal.ZERO);
+ income = BigDecimal.ZERO;
+ BigDecimal expense = expenseMap.getOrDefault(month, BigDecimal.ZERO);
+ BigDecimal totalExpense = purchase.add(expense);
+
+ BigDecimal profit = income.subtract(totalExpense);
+
+ dto.setValue(profit.setScale(2, RoundingMode.HALF_UP).toString());
+ result.add(dto);
+ }
+
+ return result;
+ }
+
+ @Override
+ public List<MapDto> expenseCompositionAnalysis(Integer type) {
+ List<MapDto> result = new ArrayList<>();
+
+ if (type == 2) {
+ List<MapDto> customerList = salesLedgerMapper.selectCustomerSalesComposition();
+ if (customerList != null) {
+ result.addAll(customerList);
+ }
+ } else {
+ BigDecimal rawMaterialAmount = salesLedgerProductMapper.selectRawMaterialExpense();
+ MapDto rawMaterialDto = new MapDto();
+ rawMaterialDto.setName("鍘熸潗鏂�");
+ rawMaterialDto.setValue(rawMaterialAmount != null ? rawMaterialAmount.toString() : "0");
+ result.add(rawMaterialDto);
+
+ List<MapDto> expenseList = accountExpenseMapper.selectExpenseComposition(null, null);
+ if (expenseList != null) {
+ result.addAll(expenseList);
+ }
+ }
+
+ BigDecimal total = BigDecimal.ZERO;
+ for (MapDto dto : result) {
+ if (dto.getValue() != null) {
+ total = total.add(new BigDecimal(dto.getValue()));
+ }
+ }
+
+ if (total.compareTo(BigDecimal.ZERO) > 0) {
+ for (MapDto dto : result) {
+ if (dto.getValue() != null) {
+ BigDecimal val = new BigDecimal(dto.getValue());
+ String rate = val.divide(total, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ dto.setRate(rate);
+ } else {
+ dto.setRate("0.00");
+ }
+ }
+ } else {
+ for (MapDto dto : result) {
+ dto.setRate("0.00");
+ }
+ }
+
+ return result;
+ }
+
+
+ @Override
+ public MonthlyIncomeDto monthlyIncome() {
+ MonthlyIncomeDto dto = new MonthlyIncomeDto();
+ LocalDate now = LocalDate.now();
+ YearMonth currentMonth = YearMonth.from(now);
+ LocalDateTime startOfMonth = currentMonth.atDay(1).atStartOfDay();
+ LocalDateTime endOfMonth = currentMonth.atEndOfMonth().atTime(23, 59, 59);
+
+ LambdaQueryWrapper<SalesLedgerProduct> wrapper = new LambdaQueryWrapper<>();
+ wrapper.eq(SalesLedgerProduct::getType, 1);
+ wrapper.ge(SalesLedgerProduct::getRegisterDate, startOfMonth);
+ wrapper.le(SalesLedgerProduct::getRegisterDate, endOfMonth);
+
+ List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(wrapper);
+
+ if (CollectionUtils.isEmpty(products)) {
+ return dto;
+ }
+
+ BigDecimal collected = products.stream()
+ .map(SalesLedgerProduct::getInvoiceTotal)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ dto.setMonthlyIncome(collected);
+
+ BigDecimal overdue = products.stream()
+ .map(SalesLedgerProduct::getPendingInvoiceTotal)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ dto.setOverdueNum(overdue);
+
+ BigDecimal total = collected.add(overdue);
+
+ if (total.compareTo(BigDecimal.ZERO) > 0) {
+ String collectionRate = collected.divide(total, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ dto.setCollectionRate(collectionRate);
+
+ String overdueRate = overdue.divide(total, 4, RoundingMode.HALF_UP)
+ .multiply(new BigDecimal("100"))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ dto.setOverdueRate(overdueRate);
+ }
+
+ return dto;
+ }
+
+ public MonthlyExpenditureDto monthlyExpenditure() {
+
+ MonthlyExpenditureDto dto = new MonthlyExpenditureDto();
+
+ // 褰撴湀鏃堕棿鑼冨洿
+ LocalDate now = LocalDate.now();
+ YearMonth currentMonth = YearMonth.from(now);
+ LocalDateTime startOfMonth = currentMonth.atDay(1).atStartOfDay();
+ LocalDateTime endOfMonth = currentMonth.atEndOfMonth().atTime(23, 59, 59);
+
+ // 閲囪喘鍙拌处锛坱ype = 2锛�
+ LambdaQueryWrapper<SalesLedgerProduct> purchaseWrapper = new LambdaQueryWrapper<>();
+ purchaseWrapper.eq(SalesLedgerProduct::getType, 2);
+ purchaseWrapper.ge(SalesLedgerProduct::getRegisterDate, startOfMonth);
+ purchaseWrapper.le(SalesLedgerProduct::getRegisterDate, endOfMonth);
+
+ List<SalesLedgerProduct> purchaseProducts =
+ salesLedgerProductMapper.selectList(purchaseWrapper);
+
+ BigDecimal rawMaterialCost = BigDecimal.ZERO; // 鍘熸潗鏂欐垚鏈�
+ BigDecimal paidAmount = BigDecimal.ZERO; // 宸蹭粯娆鹃噾棰�
+ BigDecimal pendingAmount = BigDecimal.ZERO; // 寰呬粯娆鹃噾棰�
+
+ if (!CollectionUtils.isEmpty(purchaseProducts)) {
+ for (SalesLedgerProduct p : purchaseProducts) {
+
+ if (p.getTaxInclusiveTotalPrice() != null) {
+ rawMaterialCost = rawMaterialCost.add(p.getTaxInclusiveTotalPrice());
+ }
+
+ if (p.getTicketsTotal() != null) {
+ paidAmount = paidAmount.add(p.getTicketsTotal());
+ }
+
+ if (p.getPendingTicketsTotal() != null) {
+ pendingAmount = pendingAmount.add(p.getPendingTicketsTotal());
+ }
+ }
+ }
+
+ // 鍏朵粬璐圭敤
+ LambdaQueryWrapper<AccountExpense> expenseWrapper = new LambdaQueryWrapper<>();
+ expenseWrapper.ge(AccountExpense::getExpenseDate,
+ java.sql.Date.valueOf(currentMonth.atDay(1)));
+ expenseWrapper.le(AccountExpense::getExpenseDate,
+ java.sql.Date.valueOf(currentMonth.atEndOfMonth()));
+
+ List<AccountExpense> expenses =
+ accountExpenseMapper.selectList(expenseWrapper);
+
+ BigDecimal otherExpense = BigDecimal.ZERO;
+ if (!CollectionUtils.isEmpty(expenses)) {
+ for (AccountExpense e : expenses) {
+ if (e.getExpenseMoney() != null) {
+ otherExpense = otherExpense.add(e.getExpenseMoney());
+ }
+ }
+ }
+
+ // 鏈堝害鎬绘敮鍑�
+// BigDecimal monthlyExpenditure = rawMaterialCost.add(otherExpense);
+ BigDecimal monthlyExpenditure = otherExpense;
+ dto.setMonthlyExpenditure(monthlyExpenditure);
+
+ // 宸蹭粯娆� 梅锛堝凡浠樻 + 寰呬粯娆撅級
+ BigDecimal totalPayable = paidAmount.add(pendingAmount);
+ if (totalPayable.compareTo(BigDecimal.ZERO) > 0) {
+ String paymentRate = paidAmount
+ .divide(totalPayable, 4, RoundingMode.HALF_UP)
+ .multiply(BigDecimal.valueOf(100))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+ dto.setPaymentRate(paymentRate);
+ }
+
+ // 鍞彴璐︼紙type = 1锛�
+ LambdaQueryWrapper<SalesLedgerProduct> salesWrapper = new LambdaQueryWrapper<>();
+ salesWrapper.eq(SalesLedgerProduct::getType, 1);
+ salesWrapper.ge(SalesLedgerProduct::getRegisterDate, startOfMonth);
+ salesWrapper.le(SalesLedgerProduct::getRegisterDate, endOfMonth);
+
+ List<SalesLedgerProduct> salesProducts =
+ salesLedgerProductMapper.selectList(salesWrapper);
+
+ BigDecimal revenue = BigDecimal.ZERO;
+ if (!CollectionUtils.isEmpty(salesProducts)) {
+ for (SalesLedgerProduct s : salesProducts) {
+ if (s.getInvoiceAmount() != null) {
+ revenue = revenue.add(s.getInvoiceAmount());
+ }
+ }
+ }
+
+ // 姣涘埄娑� & 鍒╂鼎鐜�
+ if (revenue.compareTo(BigDecimal.ZERO) > 0) {
+
+ // 姣涘埄娑� = 閿�鍞敹鍏� - 鍘熸潗鏂欐垚鏈�
+ BigDecimal grossProfit = revenue.subtract(rawMaterialCost);
+ dto.setGrossProfit(grossProfit);
+
+ // 鍒╂鼎鐜� = (閿�鍞敹鍏� - 鏈堝害鎬绘敮鍑�) / 閿�鍞敹鍏�
+ BigDecimal profit = revenue.subtract(monthlyExpenditure);
+ String profitMarginRate = profit
+ .divide(revenue, 4, RoundingMode.HALF_UP)
+ .multiply(BigDecimal.valueOf(100))
+ .setScale(2, RoundingMode.HALF_UP)
+ .toString();
+
+ dto.setProfitMarginRate(profitMarginRate);
+ }
+
+ return dto;
+ }
+
}
--
Gitblit v1.9.3