From 70a0b21595941890a9d26cfde01ff17e3427214a Mon Sep 17 00:00:00 2001
From: huminmin <mac@MacBook-Pro.local>
Date: 星期四, 23 七月 2026 09:24:41 +0800
Subject: [PATCH] 修改工资计算

---
 src/main/java/com/ruoyi/staff/service/impl/StaffSalaryMainServiceImpl.java |  318 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 316 insertions(+), 2 deletions(-)

diff --git a/src/main/java/com/ruoyi/staff/service/impl/StaffSalaryMainServiceImpl.java b/src/main/java/com/ruoyi/staff/service/impl/StaffSalaryMainServiceImpl.java
index 41f8af3..9790532 100644
--- a/src/main/java/com/ruoyi/staff/service/impl/StaffSalaryMainServiceImpl.java
+++ b/src/main/java/com/ruoyi/staff/service/impl/StaffSalaryMainServiceImpl.java
@@ -9,6 +9,10 @@
 import com.ruoyi.project.system.domain.SysDept;
 import com.ruoyi.project.system.mapper.SysDeptMapper;
 import com.ruoyi.project.system.mapper.SysUserDeptMapper;
+import com.ruoyi.production.mapper.ProductionAccountMapper;
+import com.ruoyi.production.pojo.ProductionAccount;
+import com.ruoyi.technology.mapper.TechnologyOperationMapper;
+import com.ruoyi.technology.pojo.TechnologyOperation;
 import com.ruoyi.staff.excel.StaffSalaryExportData;
 import jakarta.servlet.http.HttpServletResponse;
 import com.ruoyi.staff.dto.CalculateSalaryDto;
@@ -25,6 +29,7 @@
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
 
+import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -32,6 +37,15 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.stream.Collectors;
+import java.time.LocalDate;
+import java.time.YearMonth;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import java.io.IOException;
 
 /**
  * <p>
@@ -52,6 +66,8 @@
     private final SysUserDeptMapper sysUserDeptMapper;
     private final StaffLeaveMapper staffLeaveMapper;
     private final SysDeptMapper sysDeptMapper;
+    private final ProductionAccountMapper productionAccountMapper;
+    private final TechnologyOperationMapper technologyOperationMapper;
 
     @Override
     public AjaxResult listPage(Page page, StaffSalaryMain staffSalaryMain) {
@@ -169,22 +185,31 @@
         if(CollectionUtils.isEmpty(calculateSalaryDto.getIds())){
             return AjaxResult.error("鍙傛暟閿欒");
         }
+        java.math.BigDecimal deductAmount = calculateSalaryDto.getDeductAmount() == null
+                ? java.math.BigDecimal.ZERO
+                : calculateSalaryDto.getDeductAmount();
         List<Map<String, Object>> longs = setSchemeApplicableStaffUserInfo(calculateSalaryDto.getIds()); // 閫氳繃閮ㄩ棬ids鑾峰彇鐢ㄦ埛淇℃伅
         if(CollectionUtils.isEmpty(longs)){
             return AjaxResult.error("鏃犲憳宸�");
         }
         List<Map<String, Object>> mapList = new ArrayList<>();
         for (Map<String, Object> id : longs) {
+            Long staffOnJobId = id.get("id") == null ? null : ((Number) id.get("id")).longValue();
             // 鍒ゆ柇鍛樺伐鏄惁涓哄綋鏈堢鑱�
             if((Integer) id.get("staffState") == 0){
                 StaffLeave id1 = staffLeaveMapper.selectOne(new LambdaQueryWrapper<StaffLeave>()
-                        .eq(StaffLeave::getStaffOnJobId, id.get("id"))
+                        .eq(StaffLeave::getStaffOnJobId, staffOnJobId)
                         .like(StaffLeave::getLeaveDate, calculateSalaryDto.getDate()));
                 if(id1 == null){
                     continue;
                 }
             }
-            schemeApplicableStaffService.calculateByEmployeeId((Integer) id.get("id"),id,calculateSalaryDto.getDate());
+            id.put("otherDeduct", deductAmount);
+            Long sysUserId = schemeApplicableStaffService.getUidByStaffId(staffOnJobId);
+            BigDecimal monthTimeTotal = resolveMonthTimeTotal(sysUserId, calculateSalaryDto.getDate());
+            id.put("monthTimeTotal", monthTimeTotal);
+            id.put("convertedWorkHours", monthTimeTotal);
+            schemeApplicableStaffService.calculateByEmployeeId(staffOnJobId == null ? null : staffOnJobId.intValue(), id, calculateSalaryDto.getDate());
             mapList.add(id);
         }
         return AjaxResult.success(mapList);
@@ -207,8 +232,17 @@
         if (staffSalaryCalculateDto.getBasicSalary() != null) {
             map.put("basicSalary", staffSalaryCalculateDto.getBasicSalary());
         }
+        map.put("attendanceBonus", staffSalaryCalculateDto.getAttendanceBonus());
         map.put("pieceSalary", staffSalaryCalculateDto.getPieceSalary());
         map.put("hourlySalary", staffSalaryCalculateDto.getHourlySalary());
+        map.put("monthWorkDays", staffSalaryCalculateDto.getMonthWorkDays());
+        map.put("standardHours", staffSalaryCalculateDto.getStandardHours());
+        map.put("monthTimeTotal", staffSalaryCalculateDto.getMonthTimeTotal());
+        map.put("conversionRatio", staffSalaryCalculateDto.getConversionRatio());
+        map.put("convertedWorkHours", staffSalaryCalculateDto.getConvertedWorkHours());
+        map.put("actualOutput", staffSalaryCalculateDto.getActualOutput());
+        map.put("standardQuantity", staffSalaryCalculateDto.getStandardQuantity());
+        map.put("conversionFactor", staffSalaryCalculateDto.getConversionFactor());
         map.put("otherIncome", staffSalaryCalculateDto.getOtherIncome());
         map.put("socialPersonal", staffSalaryCalculateDto.getSocialPersonal());
         map.put("fundPersonal", staffSalaryCalculateDto.getFundPersonal());
@@ -248,8 +282,14 @@
                 exportData.setStaffName(detail.getStaffName());
                 exportData.setDeptName(detail.getDeptName());
                 exportData.setBasicSalary(detail.getBasicSalary());
+                exportData.setAttendanceBonus(detail.getAttendanceBonus());
                 exportData.setPieceSalary(detail.getPieceSalary());
                 exportData.setHourlySalary(detail.getHourlySalary());
+                exportData.setMonthWorkDays(detail.getMonthWorkDays());
+                exportData.setStandardHours(detail.getStandardHours());
+                exportData.setMonthTimeTotal(detail.getMonthTimeTotal());
+                exportData.setConversionRatio(detail.getConversionRatio());
+                exportData.setConvertedWorkHours(detail.getConvertedWorkHours());
                 exportData.setOtherIncome(detail.getOtherIncome());
                 exportData.setSocialPersonal(detail.getSocialPersonal());
                 exportData.setFundPersonal(detail.getFundPersonal());
@@ -266,6 +306,156 @@
 
         ExcelUtil<StaffSalaryExportData> util = new ExcelUtil<>(StaffSalaryExportData.class);
         util.exportExcel(response, exportDataList, "鍛樺伐钖祫鏄庣粏");
+    }
+
+    /**
+     * 姹囨�诲憳宸ュ綋鏈堟湀鏃堕棿鍚堣銆�
+     * 璁℃椂宸ュ簭鐩存帴鍙栧伐鏃讹紝璁′欢宸ュ簭鎸変骇閲忔姌绠楀悗鍐嶅彔鍔犺ˉ淇悊宸ユ椂銆�
+     */
+    private java.math.BigDecimal resolveMonthTimeTotal(Long sysUserId, String date) {
+        if (sysUserId == null || sysUserId <= 0 || StringUtils.isEmpty(date)) {
+            return java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP);
+        }
+        java.math.BigDecimal total = java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP);
+        java.util.List<java.util.Map<String, Object>> items = productionAccountMapper.selectMonthSalaryCalcItems(sysUserId, date);
+        for (java.util.Map<String, Object> item : items) {
+            Integer operationType = item.get("operationType") == null ? null : ((Number) item.get("operationType")).intValue();
+            java.math.BigDecimal finishedNum = toDecimal(item.get("finishedNum"));
+            java.math.BigDecimal workHour = toDecimal(item.get("workHour"));
+            java.math.BigDecimal repairWorkHour = toDecimal(item.get("repairWorkHour"));
+            java.math.BigDecimal standardQuantity = toDecimal(item.get("standardQuantity"));
+            java.math.BigDecimal conversionFactor = toDecimal(item.get("conversionFactor"));
+            java.math.BigDecimal rowTotal;
+            if (Integer.valueOf(0).equals(operationType)) {
+                rowTotal = workHour.add(repairWorkHour);
+            } else {
+                if (standardQuantity.compareTo(java.math.BigDecimal.ZERO) <= 0) {
+                    rowTotal = java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP);
+                } else {
+                    rowTotal = finishedNum
+                            .divide(standardQuantity, 8, java.math.RoundingMode.HALF_UP)
+                            .multiply(new java.math.BigDecimal("8"))
+                            .multiply(conversionFactor)
+                            .add(repairWorkHour)
+                            .setScale(2, java.math.RoundingMode.HALF_UP);
+                }
+            }
+            total = total.add(rowTotal).setScale(2, java.math.RoundingMode.HALF_UP);
+        }
+        return total;
+    }
+
+    private java.math.BigDecimal toDecimal(Object value) {
+        if (value == null) {
+            return java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP);
+        }
+        if (value instanceof java.math.BigDecimal) {
+            return ((java.math.BigDecimal) value).setScale(2, java.math.RoundingMode.HALF_UP);
+        }
+        if (value instanceof Number) {
+            return new java.math.BigDecimal(String.valueOf(value)).setScale(2, java.math.RoundingMode.HALF_UP);
+        }
+        String text = String.valueOf(value).trim();
+        if (text.isEmpty()) {
+            return java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP);
+        }
+        return new java.math.BigDecimal(text).setScale(2, java.math.RoundingMode.HALF_UP);
+    }
+
+    @Override
+    public void exportWorkHours(HttpServletResponse response, String salaryMonth) {
+        List<ProductionAccount> accountList = queryProductionAccounts(salaryMonth);
+        List<String> operationNames = accountList.stream()
+                .map(ProductionAccount::getTechnologyOperationName)
+                .filter(StringUtils::isNotEmpty)
+                .distinct()
+                .sorted()
+                .collect(Collectors.toList());
+        Workbook workbook = new XSSFWorkbook();
+        CellStyle titleStyle = createStyle(workbook, true, HorizontalAlignment.CENTER, 14, false);
+        CellStyle headerStyle = createStyle(workbook, false, HorizontalAlignment.CENTER, 11, false);
+        CellStyle labelStyle = createStyle(workbook, false, HorizontalAlignment.CENTER, 10, false);
+        CellStyle numStyle = createStyle(workbook, false, HorizontalAlignment.CENTER, 10, false);
+        DataFormat dataFormat = workbook.createDataFormat();
+        numStyle.setDataFormat(dataFormat.getFormat("0.00"));
+
+        if (CollectionUtils.isEmpty(operationNames)) {
+            operationNames = new ArrayList<>();
+        }
+
+        int sheetIndex = 1;
+        for (String operationName : operationNames) {
+            TechnologyOperation operation = technologyOperationMapper.selectOne(
+                    new LambdaQueryWrapper<TechnologyOperation>().eq(TechnologyOperation::getName, operationName).last("limit 1"));
+            String sheetName = operationName;
+            if (sheetName.length() > 31) {
+                sheetName = sheetName.substring(0, 31);
+            }
+            Sheet sheet = workbook.createSheet(sheetName);
+            int rowIdx = 0;
+            Row titleRow = sheet.createRow(rowIdx++);
+            titleRow.setHeightInPoints(52.5f);
+            titleRow.createCell(0).setCellValue(operationName + "宸ユ椂缁熻");
+            titleRow.getCell(0).setCellStyle(titleStyle);
+            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
+
+            Row workDayRow = sheet.createRow(rowIdx++);
+            workDayRow.createCell(0).setCellValue("宸ヤ綔鏃�");
+            workDayRow.getCell(0).setCellStyle(headerStyle);
+            Integer monthWorkDays = calculateWorkDays(salaryMonth);
+            createNumberCell(workDayRow, 2, monthWorkDays == null ? null : new java.math.BigDecimal(monthWorkDays), headerStyle);
+            workDayRow.createCell(3).setCellValue("澶�");
+            workDayRow.getCell(3).setCellStyle(headerStyle);
+            createNumberCell(workDayRow, 4, monthWorkDays == null ? null : new java.math.BigDecimal(monthWorkDays * 8), headerStyle);
+            workDayRow.createCell(5).setCellValue("灏忔椂");
+            workDayRow.getCell(5).setCellStyle(headerStyle);
+
+            Row headRow = sheet.createRow(rowIdx++);
+            headRow.createCell(0).setCellValue("浜哄憳");
+            headRow.getCell(0).setCellStyle(headerStyle);
+            headRow.createCell(1).setCellValue("鏈堜骇閲�");
+            headRow.getCell(1).setCellStyle(headerStyle);
+            headRow.createCell(2).setCellValue("鎶樼畻鏃堕暱");
+            headRow.getCell(2).setCellStyle(headerStyle);
+            headRow.createCell(3).setCellValue("宸ヨ祫");
+            headRow.getCell(3).setCellStyle(headerStyle);
+
+            Map<String, java.math.BigDecimal> standardMap = buildStandardQuantityMap(List.of(operationName));
+            Map<String, java.math.BigDecimal> opQtyMap = buildOperationQuantityMap(accountList, operationName);
+            Set<String> employeeNames = accountList.stream()
+                    .map(ProductionAccount::getSchedulingUserName)
+                    .filter(StringUtils::isNotEmpty)
+                    .collect(Collectors.toCollection(LinkedHashSet::new));
+            for (String staffName : employeeNames) {
+                Row row = sheet.createRow(rowIdx++);
+                row.createCell(0).setCellValue(staffName);
+                row.getCell(0).setCellStyle(labelStyle);
+                java.math.BigDecimal qty = opQtyMap.getOrDefault(staffName, java.math.BigDecimal.ZERO);
+                createNumberCell(row, 1, qty, numStyle);
+                java.math.BigDecimal standardQty = standardMap.getOrDefault(operationName, java.math.BigDecimal.ONE);
+                createNumberCell(row, 2, standardQty.compareTo(java.math.BigDecimal.ZERO) == 0 ? java.math.BigDecimal.ZERO : qty.divide(standardQty, 2, java.math.RoundingMode.HALF_UP).multiply(new java.math.BigDecimal("8")), numStyle);
+                java.math.BigDecimal wage = operation == null || operation.getSalaryQuota() == null
+                        ? java.math.BigDecimal.ZERO
+                        : (Integer.valueOf(1).equals(operation.getType()) ? operation.getSalaryQuota().multiply(qty) : operation.getSalaryQuota());
+                createNumberCell(row, 3, wage, numStyle);
+            }
+
+            for (int i = 0; i <= 3; i++) {
+                sheet.autoSizeColumn(i);
+            }
+            sheetIndex++;
+        }
+
+        try {
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+            response.setCharacterEncoding("UTF-8");
+            String fileName = java.net.URLEncoder.encode("宸ユ椂琛�.xlsx", java.nio.charset.StandardCharsets.UTF_8);
+            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
+            workbook.write(response.getOutputStream());
+            workbook.close();
+        } catch (IOException e) {
+            throw new RuntimeException("瀵煎嚭宸ユ椂琛ㄥけ璐�", e);
+        }
     }
 
     public List<Map<String, Object>> setSchemeApplicableStaffUserInfo(List<Long> ids) {
@@ -324,4 +514,128 @@
         return false;
     }
 
+    private String buildWorkHoursTitle(StaffSalaryMain main) {
+        String month = StringUtils.isNotEmpty(main.getSalaryMonth()) ? main.getSalaryMonth() : "鏈煡鏈堜唤";
+        return month + "宸ユ椂缁熻";
+    }
+
+    private Integer calculateWorkDays(String salaryMonth) {
+        if (StringUtils.isEmpty(salaryMonth)) {
+            return 0;
+        }
+        java.time.YearMonth yearMonth = java.time.YearMonth.parse(salaryMonth);
+        int workDays = 0;
+        for (int day = 1; day <= yearMonth.lengthOfMonth(); day++) {
+            java.time.DayOfWeek dayOfWeek = yearMonth.atDay(day).getDayOfWeek();
+            if (dayOfWeek != java.time.DayOfWeek.SATURDAY && dayOfWeek != java.time.DayOfWeek.SUNDAY) {
+                workDays++;
+            }
+        }
+        return workDays;
+    }
+
+    private CellStyle createStyle(Workbook workbook, boolean bold, HorizontalAlignment alignment, int fontSize, boolean fill) {
+        Font font = workbook.createFont();
+        font.setFontName("Microsoft YaHei");
+        font.setFontHeightInPoints((short) fontSize);
+        font.setBold(bold);
+        CellStyle style = workbook.createCellStyle();
+        style.setFont(font);
+        style.setAlignment(alignment);
+        style.setVerticalAlignment(VerticalAlignment.CENTER);
+        style.setBorderTop(BorderStyle.THIN);
+        style.setBorderBottom(BorderStyle.THIN);
+        style.setBorderLeft(BorderStyle.THIN);
+        style.setBorderRight(BorderStyle.THIN);
+        if (fill) {
+            style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
+            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+        }
+        return style;
+    }
+
+    private void createTextCell(Row row, int colIndex, String value, CellStyle style) {
+        Cell cell = row.createCell(colIndex);
+        cell.setCellValue(value == null ? "" : value);
+        cell.setCellStyle(style);
+    }
+
+    private void createNumberCell(Row row, int colIndex, java.math.BigDecimal value, CellStyle style) {
+        Cell cell = row.createCell(colIndex);
+        if (value != null) {
+            cell.setCellValue(value.doubleValue());
+        }
+        cell.setCellStyle(style);
+    }
+
+    private void createFormulaCell(Row row, int colIndex, String formula, CellStyle style) {
+        Cell cell = row.createCell(colIndex);
+        cell.setCellFormula(formula.startsWith("=") ? formula.substring(1) : formula);
+        cell.setCellStyle(style);
+    }
+
+    private String toCellRef(int colIndex, int rowNum1Based) {
+        return cellRef(colIndex) + rowNum1Based;
+    }
+
+    private String cellRef(int colIndex) {
+        StringBuilder sb = new StringBuilder();
+        int col = colIndex;
+        do {
+            int rem = col % 26;
+            sb.insert(0, (char) ('A' + rem));
+            col = col / 26 - 1;
+        } while (col >= 0);
+        return sb.toString();
+    }
+
+    private List<ProductionAccount> queryProductionAccounts(String salaryMonth) {
+        if (StringUtils.isEmpty(salaryMonth)) {
+            return new ArrayList<>();
+        }
+        YearMonth ym = YearMonth.parse(salaryMonth);
+        LocalDate start = ym.atDay(1);
+        LocalDate end = ym.atEndOfMonth();
+        return productionAccountMapper.selectList(new LambdaQueryWrapper<ProductionAccount>()
+                .ge(ProductionAccount::getSchedulingDate, start.atStartOfDay())
+                .le(ProductionAccount::getSchedulingDate, end.atTime(23, 59, 59)));
+    }
+
+    private Map<String, java.math.BigDecimal> buildOperationQuantityMap(List<ProductionAccount> accountList, String operationName) {
+        Map<String, java.math.BigDecimal> map = new LinkedHashMap<>();
+        if (CollectionUtils.isEmpty(accountList) || StringUtils.isEmpty(operationName)) {
+            return map;
+        }
+        accountList.stream()
+                .filter(item -> item != null && operationName.equals(item.getTechnologyOperationName()))
+                .filter(item -> StringUtils.isNotEmpty(item.getSchedulingUserName()))
+                .forEach(item -> map.merge(item.getSchedulingUserName(),
+                        item.getFinishedNum() == null ? java.math.BigDecimal.ZERO : item.getFinishedNum(),
+                        java.math.BigDecimal::add));
+        return map;
+    }
+
+    private Map<String, java.math.BigDecimal> buildStandardQuantityMap(List<String> operationNames) {
+        Map<String, java.math.BigDecimal> map = new LinkedHashMap<>();
+        if (CollectionUtils.isEmpty(operationNames)) {
+            return map;
+        }
+        List<TechnologyOperation> operations = technologyOperationMapper.selectList(
+                new LambdaQueryWrapper<TechnologyOperation>()
+                        .in(TechnologyOperation::getName, operationNames)
+        );
+        Map<String, java.math.BigDecimal> opMap = operations.stream()
+                .filter(item -> item != null && StringUtils.isNotEmpty(item.getName()))
+                .collect(Collectors.toMap(
+                        TechnologyOperation::getName,
+                        item -> item.getStandardQuantity() == null ? java.math.BigDecimal.ZERO : item.getStandardQuantity(),
+                        (left, right) -> left,
+                        LinkedHashMap::new
+                ));
+        for (String operationName : operationNames) {
+            map.put(operationName, opMap.getOrDefault(operationName, java.math.BigDecimal.ZERO));
+        }
+        return map;
+    }
+
 }

--
Gitblit v1.9.3