huminmin
4 天以前 b8607f49fb2ec4a4113aeb01455e90ae83781bcc
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
package com.ruoyi.staff.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.production.bean.dto.UserAccountDto;
import com.ruoyi.production.bean.dto.UserProductionAccountingDto;
import com.ruoyi.production.service.SalesLedgerProductionAccountingService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.staff.controller.TaxCalculator;
import com.ruoyi.staff.mapper.*;
import com.ruoyi.staff.pojo.*;
import com.ruoyi.staff.service.SchemeApplicableStaffService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 社保方案适用人员表 服务实现类
 * </p>
 *
 * @author 芯导软件(江苏)有限公司
 * @since 2026-03-05 11:50:17
 */
@Service
@RequiredArgsConstructor
public class SchemeApplicableStaffServiceImpl extends ServiceImpl<SchemeApplicableStaffMapper, SchemeApplicableStaff> implements SchemeApplicableStaffService {
 
    private final SchemeApplicableStaffMapper schemeApplicableStaffMapper;
    private final SchemeInsuranceDetailMapper schemeInsuranceDetailMapper;
    private final SysUserMapper sysUserMapper;
    private final SysDeptMapper sysDeptMapper;
    private final StaffOnJobMapper staffOnJobMapper;
    private final PersonalShiftMapper personalShiftMapper;
    private final PersonalAttendanceLocationConfigMapper personalAttendanceLocationConfigMapper;
    private final SalesLedgerProductionAccountingService salesLedgerProductionAccountingService;
    private final SubsidyConfigurationMapper subsidyConfigurationMapper;
 
 
    @Override
    public AjaxResult listPage(Page page, SchemeApplicableStaff schemeApplicableStaff) {
        LambdaQueryWrapper<SchemeApplicableStaff> schemeApplicableStaffLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(schemeApplicableStaff != null){
            if(StringUtils.isNotEmpty(schemeApplicableStaff.getTitle())){
                schemeApplicableStaffLambdaQueryWrapper.like(SchemeApplicableStaff::getTitle, schemeApplicableStaff.getTitle());
            }
        }
        schemeApplicableStaffLambdaQueryWrapper.orderByDesc(SchemeApplicableStaff::getId);
        Page<SchemeApplicableStaff> page1 = schemeApplicableStaffMapper.selectPage(page, schemeApplicableStaffLambdaQueryWrapper);
        List<Long> collect = page1.getRecords().stream().map(SchemeApplicableStaff::getId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(collect)){
            return AjaxResult.success(page1);
        }
        List<SchemeInsuranceDetail> schemeInsuranceDetails = schemeInsuranceDetailMapper
                .selectList(new LambdaQueryWrapper<SchemeInsuranceDetail>()
                        .in(SchemeInsuranceDetail::getSchemeId, collect));
        page1.getRecords().forEach(item -> {
            item.setSchemeInsuranceDetailList(schemeInsuranceDetails
                    .stream()
                    .filter(detail -> detail.getSchemeId().equals(item.getId()))
                    .collect(Collectors.toList()));
            SysUser sysUser = sysUserMapper.selectUserById(item.getCreateUser().longValue());
            item.setCreateUserName(sysUser == null ? "未知" : sysUser.getNickName());
            // 获取部门信息
            String[] split = item.getDeptIds().split(",");
            List<SysDept> sysDepts = sysDeptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                    .in(SysDept::getDeptId, Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList())));
            if(!CollectionUtils.isEmpty(sysDepts)){
                item.setDeptNames(sysDepts.stream().map(SysDept::getDeptName).collect(Collectors.joining(",")));
            }
        });
        return AjaxResult.success(page1);
    }
 
    public void setSchemeApplicableStaffUserInfo(SchemeApplicableStaff schemeApplicableStaff) {
        // 通过部门获取人员id
        String[] split = schemeApplicableStaff.getDeptIds().split(",");
        List<StaffOnJob> staffOnJobs = staffOnJobMapper.selectList(new LambdaQueryWrapper<StaffOnJob>()
                .in(StaffOnJob::getSysDeptId, Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList())));
        if(CollectionUtils.isEmpty(staffOnJobs)){
            throw new IllegalArgumentException("部门下无员工");
        }
        schemeApplicableStaff.setStaffIds(staffOnJobs
                .stream()
                .map(StaffOnJob::getId)
                .filter(Objects::nonNull)         // 过滤掉 null 值
                .map(String::valueOf)
                .collect(Collectors.joining( ",")));
        schemeApplicableStaff.setStaffNames(staffOnJobs.stream().map(StaffOnJob::getStaffName).collect(Collectors.joining(",")));
    }
 
    @Override
    public AjaxResult add(SchemeApplicableStaff schemeApplicableStaff) {
        if(schemeApplicableStaff == null){
            return AjaxResult.error("参数错误");
        }
        if(CollectionUtils.isEmpty(schemeApplicableStaff.getSchemeInsuranceDetailList())){
            return AjaxResult.error("请选择方案明细");
        }
        setSchemeApplicableStaffUserInfo(schemeApplicableStaff); //根据部门设置用户信息
        int insert = schemeApplicableStaffMapper.insert(schemeApplicableStaff);
        schemeApplicableStaff.getSchemeInsuranceDetailList().forEach(item -> {
            item.setSchemeId(schemeApplicableStaff.getId());
            schemeInsuranceDetailMapper.insert(item);
        });
        return AjaxResult.success(insert);
    }
 
    @Override
    public AjaxResult updateSchemeApplicableStaff(SchemeApplicableStaff schemeApplicableStaff) {
        if(schemeApplicableStaff == null){
            return AjaxResult.error("参数错误");
        }
        setSchemeApplicableStaffUserInfo(schemeApplicableStaff); //根据部门设置用户信息
        int update = schemeApplicableStaffMapper.updateById(schemeApplicableStaff);
        // 先删,重新绑定
        schemeInsuranceDetailMapper.delete(new LambdaQueryWrapper<SchemeInsuranceDetail>()
                .eq(SchemeInsuranceDetail::getSchemeId, schemeApplicableStaff.getId()));
        schemeApplicableStaff.getSchemeInsuranceDetailList().forEach(item -> {
            item.setSchemeId(schemeApplicableStaff.getId());
            schemeInsuranceDetailMapper.insert(item);
        });
        return AjaxResult.success(update);
    }
 
    @Override
    public AjaxResult delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return AjaxResult.error("参数错误");
        }
        int delete = schemeApplicableStaffMapper.deleteBatchIds(ids);
        schemeInsuranceDetailMapper.delete(new LambdaQueryWrapper<SchemeInsuranceDetail>()
                .in(SchemeInsuranceDetail::getSchemeId, ids));
        return AjaxResult.success(delete);
    }
 
    /**
     * 通过员工id计算社保方案
     * @param id
     */
    public void calculateByEmployeeId(Integer id,Map<String, Object> map,String date) {
        // 1. 入参校验
        if (id == null) {
            return; // 或返回空列表,根据业务需求调整
        }
        Long staffId = id.longValue();
        // 社保金额
        BigDecimal socialPersonal = new BigDecimal("0.00");
        // 公积金金额
        BigDecimal fundPersonal = new BigDecimal("0.00");
        // 基本工资
        BigDecimal basicSalary = new BigDecimal("0.00");
        map.put("fundPersonal", fundPersonal); // 公积金
        map.put("socialPersonal", socialPersonal); // 社保金额
        map.put("basicSalary", basicSalary); // 基本工资
        // 个税金额
        BigDecimal salaryTax = new BigDecimal("0.00");
        map.put("salaryTax", salaryTax);
        // 计件工资
        BigDecimal pieceSalary = new BigDecimal("0.00");
        map.put("pieceSalary", pieceSalary);
        // 计时工资
        BigDecimal hourlySalary = new BigDecimal("0.00");
        map.put("hourlySalary", hourlySalary);
        // 其他收入
        BigDecimal otherIncome = new BigDecimal("0.00");
        map.put("otherIncome", otherIncome);
        // 其他支出
        BigDecimal otherDeduct = new BigDecimal("0.00");
        map.put("otherDeduct", otherDeduct);
        // 应发工资
        BigDecimal grossSalary = new BigDecimal("0.00");
        map.put("grossSalary", grossSalary);
        // 应扣工资
        BigDecimal deductSalary = new BigDecimal("0.00");
        map.put("deductSalary", deductSalary);
        // 实发工资
        BigDecimal netSalary = new BigDecimal("0.00");
        map.put("netSalary", netSalary);
        // 根据排班数据计算白班天数和夜班天数
        BigDecimal dayDays = new BigDecimal("0.00");
        BigDecimal nightDays = new BigDecimal("0.00");
 
        // 查询当月排班记录
        List<PersonalShift> shiftList = personalShiftMapper.selectList(new LambdaQueryWrapper<PersonalShift>()
                .eq(PersonalShift::getStaffOnJobId, staffId)
                .like(PersonalShift::getWorkTime, date));
 
        if(!CollectionUtils.isEmpty(shiftList)){
            // 收集所有班次配置ID
            List<Integer> configIds = shiftList.stream()
                    .map(PersonalShift::getPersonalAttendanceLocationConfigId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
 
            if(!CollectionUtils.isEmpty(configIds)){
                // 查询班次配置信息
                List<PersonalAttendanceLocationConfig> configList = personalAttendanceLocationConfigMapper.selectList(
                        new LambdaQueryWrapper<PersonalAttendanceLocationConfig>()
                                .in(PersonalAttendanceLocationConfig::getId, configIds));
 
                // 构建班次配置映射
                Map<Integer, String> configMap = configList.stream()
                        .collect(Collectors.toMap(
                                PersonalAttendanceLocationConfig::getId,
                                PersonalAttendanceLocationConfig::getShift,
                                (a, b) -> a));
 
                // 统计白班和夜班天数
                for (PersonalShift shift : shiftList) {
                    Integer configId = shift.getPersonalAttendanceLocationConfigId();
                    String shiftName = configMap.get(configId);
                    if(shiftName != null){
                        // 根据班次名称判断:包含"白"或"日"为白班,包含"夜"为夜班
                        if(shiftName.contains("白") || shiftName.contains("日")){
                            dayDays = dayDays.add(BigDecimal.ONE);
                        } else if(shiftName.contains("夜")){
                            nightDays = nightDays.add(BigDecimal.ONE);
                        }
                    }
                }
            }
        }
        map.put("dayDays", dayDays); // 白班天数
        map.put("nightDays", nightDays); // 夜班天数
 
        // 查询餐补和夜班补贴
        // 计算餐补(回族特有)和夜班补助
        BigDecimal mealAmount = new BigDecimal("0.00"); // 餐补
        BigDecimal nightAmount = new BigDecimal("0.00"); // 夜班补助
 
        // 获取餐补和夜班补贴标准(从补贴配置中获取)
        SubsidyConfiguration subsidyConfig = subsidyConfigurationMapper.selectOne(null);
        BigDecimal mealStandard = new BigDecimal("0.00"); // 餐补标准
        BigDecimal nightStandard = new BigDecimal("0.00"); // 夜班补贴标准
        if(subsidyConfig != null){
            mealStandard = subsidyConfig.getMealAmount() != null ? subsidyConfig.getMealAmount() : new BigDecimal("0.00");
            nightStandard = subsidyConfig.getNightAmount() != null ? subsidyConfig.getNightAmount() : new BigDecimal("0.00");
        }
 
        // 餐补:民族为回族特有,计算方式为(白班天数+夜班天数)*餐补标准
        StaffOnJob staffOnJobDto = staffOnJobMapper.selectById(staffId);
        if(staffOnJobDto == null){
            return;
        }
 
        String nation = staffOnJobDto.getNation();
        if("回族".equals(nation)){
            mealAmount = dayDays.add(nightDays).multiply(mealStandard);
        }
 
        // 夜班补助:夜班天数*夜班补贴标准
        nightAmount = nightDays.multiply(nightStandard);
 
        map.put("mealAmount", mealAmount); // 餐补
        map.put("nightAmount", nightAmount); // 夜班补助
 
        // 调用基本工资
        basicSalary = staffOnJobDto.getBasicSalary();
        map.put("basicSalary", basicSalary);
        // 应发工资(基本工资+餐补+夜班补助+其他收入)
        grossSalary = basicSalary.add(mealAmount).add(nightAmount).add(otherIncome);
        map.put("grossSalary", grossSalary);
        // 实发工资初始值
        netSalary = grossSalary;
        map.put("netSalary", netSalary);
        // 个税金额(无社保版)
        BigDecimal bigDecimal = TaxCalculator.calculateMonthlyTax(basicSalary, socialPersonal, fundPersonal);
        map.put("salaryTax", bigDecimal);
        // 计时工资 计件工资
        UserProductionAccountingDto userProductionAccountingDto = new UserProductionAccountingDto();
        userProductionAccountingDto.setUserId(getUidByStaffId(staffId));
        userProductionAccountingDto.setDate(date);
        UserAccountDto byUserId = salesLedgerProductionAccountingService.getByUserId(userProductionAccountingDto);
        if(byUserId != null){
            map.put("pieceSalary", byUserId.getAccountBalance());
            map.put("hourlySalary", byUserId.getAccount());
            // 应发 实发增加
            grossSalary = grossSalary.add(byUserId.getAccountBalance()).add(byUserId.getAccount());
            map.put("grossSalary", grossSalary);
            netSalary = netSalary.add(byUserId.getAccountBalance()).add(byUserId.getAccount());
            map.put("netSalary", netSalary);
        }
        // 2. 查询该人员对应的社保方案
        List<SchemeApplicableStaff> schemeList = schemeApplicableStaffMapper.selectSchemeByStaffId(staffId);
        if (CollectionUtils.isEmpty(schemeList)) {
            return; // 无匹配方案,返回空列表
        }
        // 3. 为每个方案关联明细列表
        for (SchemeApplicableStaff scheme : schemeList) {
            List<SchemeInsuranceDetail> detailList = schemeApplicableStaffMapper.selectDetailBySchemeId(scheme.getId());
            // 根据明细列表计算社保缴费金额
            if(CollectionUtils.isEmpty(detailList)){
                continue;
            }
            for (SchemeInsuranceDetail detail : detailList) {
                if("公积金".equals(detail.getInsuranceType())){
                    fundPersonal = fundPersonal.add(calculateByEmployeeIdType(detail.getInsuranceType(),fundPersonal, staffOnJobDto, detail));
                }else{
                    socialPersonal = socialPersonal.add(calculateByEmployeeIdType(detail.getInsuranceType(),socialPersonal, staffOnJobDto, detail));
                }
            }
        }
        map.put("socialPersonal", socialPersonal);
        map.put("fundPersonal", fundPersonal);
        // 个税金额(社保版)
        bigDecimal = TaxCalculator.calculateMonthlyTax(basicSalary, socialPersonal, fundPersonal);
        map.put("salaryTax", bigDecimal);
 
        // 应扣工资 = 个税 + 公积金个人 + 社保个人 + 其他支出
        deductSalary = bigDecimal.add(fundPersonal).add(socialPersonal).add(otherDeduct);
        map.put("deductSalary", deductSalary);
 
        // 实发工资 = 应发工资 - 应扣工资
        netSalary = grossSalary.subtract(deductSalary);
        map.put("netSalary", netSalary);
 
    }
 
    /**
     * 通过员工Id获取用户id
     * @param staffId
     * @return
     */
    public Long getUidByStaffId(Long staffId){
        StaffOnJob staffOnJob = staffOnJobMapper.selectById(staffId);
        if(staffOnJob == null){
            return -1L; // 返回不存在Id
        }
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, staffOnJob.getStaffNo())
                .eq(SysUser::getDelFlag, "0")
                .last("limit 1"));
        if(sysUser == null){
            return -1L; // 返回不存在Id
        }
        return sysUser.getUserId();
    }
 
    /**
     * 计算
     * @param type
     * @param bigDecimal
     * @param staffOnJobDto
     * @param detail
     * @return
     */
    public BigDecimal calculateByEmployeeIdType(String type,BigDecimal bigDecimal, StaffOnJob staffOnJobDto,SchemeInsuranceDetail detail) {
        // 判断是否调用基本工资
        if (detail.getUseBasicSalary() == 1) {
            BigDecimal divide = detail.getPaymentBase().multiply(detail.getPersonalRatio()).divide(new BigDecimal("100"), 2);
            bigDecimal = bigDecimal.add(divide);
        }else{
            // 调用基本工资
            BigDecimal multiply = staffOnJobDto.getBasicSalary().multiply(detail.getPersonalRatio().divide(new BigDecimal("100"), 2));
            bigDecimal = bigDecimal.add(multiply);
        }
        bigDecimal = bigDecimal.add(detail.getPersonalFixed());
        return bigDecimal;
    }
}