gaoluyang
昨天 8c65f898ed6e5b0c7a94c792c4562f6ec831dccd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package cn.iocoder.yudao.module.mes.controller.admin.pro.mps;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.mes.controller.admin.pro.mps.vo.MesProMpsPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.pro.mps.vo.MesProMpsRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.pro.mps.vo.MesProMpsSaveReqVO;
import cn.iocoder.yudao.module.crm.api.customer.CrmCustomerApi;
import cn.iocoder.yudao.module.crm.api.customer.dto.CrmCustomerRespDTO;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.erp.api.sale.ErpSaleOrderApi;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.mes.dal.dataobject.md.item.MesMdItemDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.md.unitmeasure.MesMdUnitMeasureDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.pro.mps.MesProMpsDO;
import cn.iocoder.yudao.module.mes.service.md.item.MesMdItemService;
import cn.iocoder.yudao.module.mes.service.md.unitmeasure.MesMdUnitMeasureService;
import cn.iocoder.yudao.module.mes.service.pro.mps.MesProMpsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
 
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.PRO_MPS_MERGE_ISSUE_DISABLED;
 
@Tag(name = "管理后台 - MES 生产主计划")
@RestController
@RequestMapping("/mes/pro-mps")
@Validated
@Slf4j
public class MesProMpsController {
 
    @Resource
    private MesProMpsService mpsService;
    @Resource
    private MesMdItemService itemService;
    @Resource
    private MesMdUnitMeasureService unitMeasureService;
    @Resource
    private CrmCustomerApi customerApi;
    @Resource
    private ErpSaleOrderApi saleOrderApi;
    @Resource
    private PermissionApi permissionApi;
 
    @PostMapping("/create")
    @Operation(summary = "创建生产主计划")
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:create')")
    public CommonResult<Long> createMps(@Valid @RequestBody MesProMpsSaveReqVO createReqVO) {
        return success(mpsService.createMps(createReqVO));
    }
 
    @PutMapping("/update")
    @Operation(summary = "更新生产主计划")
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:update')")
    public CommonResult<Boolean> updateMps(@Valid @RequestBody MesProMpsSaveReqVO updateReqVO) {
        mpsService.updateMps(updateReqVO);
        return success(true);
    }
 
    @DeleteMapping("/delete")
    @Operation(summary = "删除生产主计划")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:delete')")
    public CommonResult<Boolean> deleteMps(@RequestParam("id") Long id) {
        mpsService.deleteMps(id);
        return success(true);
    }
 
    @GetMapping("/get")
    @Operation(summary = "获得生产主计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<MesProMpsRespVO> getMps(@RequestParam("id") Long id) {
        MesProMpsDO mps = mpsService.getMps(id);
        if (mps == null) {
            return success(null);
        }
        return success(buildMpsRespVOList(ListUtil.of(mps)).get(0));
    }
 
    @GetMapping("/page")
    @Operation(summary = "获得生产主计划分页")
    public CommonResult<PageResult<MesProMpsRespVO>> getMpsPage(@Valid MesProMpsPageReqVO pageReqVO) {
        PageResult<MesProMpsDO> pageResult = mpsService.getMpsPage(pageReqVO);
        return success(new PageResult<>(buildMpsRespVOList(pageResult.getList()), pageResult.getTotal()));
    }
 
    @GetMapping("/export-excel")
    @Operation(summary = "导出生产主计划 Excel")
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMpsExcel(@Valid MesProMpsPageReqVO pageReqVO,
                               HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MesProMpsDO> list = mpsService.getMpsPage(pageReqVO).getList();
        List<MesProMpsRespVO> voList = buildMpsRespVOList(list);
        ExcelUtils.write(response, "生产主计划.xls", "数据", MesProMpsRespVO.class, voList);
    }
 
    @PostMapping("/issue")
    @Operation(summary = "下发生产主计划")
    @Parameter(name = "id", description = "MPS 编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:issue')")
    public CommonResult<Long> issueMps(@RequestParam("id") Long id) {
        return success(mpsService.issueMps(id));
    }
 
    @PostMapping("/merge-issue")
    @Operation(summary = "合并下发生产主计划")
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:merge-issue')")
    public CommonResult<Long> mergeAndIssueMps(@RequestBody List<Long> mpsIds) {
        // 旧入口保留用于明确提示旧客户端升级,禁止绕过新的逐条下发权限校验。
        throw exception(PRO_MPS_MERGE_ISSUE_DISABLED);
    }
 
    @PostMapping("/batch-issue")
    @Operation(summary = "批量逐条下发生产主计划")
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:issue')")
    public CommonResult<List<BatchIssueResult>> batchIssueMps(@RequestBody @NotEmpty List<@NotNull Long> ids) {
        List<BatchIssueResult> results = new ArrayList<>();
        for (Long id : ids) {
            BatchIssueResult result = new BatchIssueResult();
            result.setMpsId(id);
            try {
                result.setWorkOrderId(mpsService.issueMps(id));
            } catch (ServiceException ex) {
                result.setError(ex.getMessage());
            } catch (Exception ex) {
                log.error("[batchIssueMps] 下发失败,mpsId={}", id, ex);
                result.setError("下发失败,请联系管理员查看日志");
            }
            results.add(result);
        }
        return success(results);
    }
 
    @Data
    public static class BatchIssueResult {
        private Long mpsId;
        private Long workOrderId;
        private String error;
    }
 
    @PostMapping("/cancel")
    @Operation(summary = "取消生产主计划")
    @Parameter(name = "id", description = "MPS 编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:pro-mps:cancel')")
    public CommonResult<Boolean> cancelMps(@RequestParam("id") Long id) {
        mpsService.cancelMps(id);
        return success(true);
    }
 
    // ==================== 拼接 VO ====================
 
    private List<MesProMpsRespVO> buildMpsRespVOList(List<MesProMpsDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 1. 批量获取关联数据
        Map<Long, MesMdItemDO> itemMap = itemService.getItemMap(
                convertSet(list, MesProMpsDO::getProductId));
        Map<Long, MesMdUnitMeasureDO> unitMap = unitMeasureService.getUnitMeasureMap(
                convertSet(itemMap.values(), MesMdItemDO::getUnitMeasureId));
        Map<Long, CrmCustomerRespDTO> clientMap = customerApi.getCustomerMap(
                convertSet(list, MesProMpsDO::getClientId));
        // 2. 下发权限:与 MesProMpsServiceImpl#validateIssuePermission 保持一致
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        boolean superAdmin = loginUserId != null && permissionApi.hasAnyRoles(loginUserId, "super_admin");
        Map<Long, MesProMpsDO> mpsMap = list.stream()
                .collect(java.util.stream.Collectors.toMap(MesProMpsDO::getId, mps -> mps));
        Map<Long, String> saleOrderCreatorMap = new java.util.HashMap<>();
        // 3. 拼接 VO
        return BeanUtils.toBean(list, MesProMpsRespVO.class, vo -> {
            MapUtils.findAndThen(itemMap, vo.getProductId(), item -> {
                vo.setProductName(item.getName())
                        .setProductCode(item.getCode())
                        .setProductSpecification(item.getSpecification());
                MapUtils.findAndThen(unitMap, item.getUnitMeasureId(),
                        unit -> vo.setUnitMeasureName(unit.getName()));
            });
            MapUtils.findAndThen(clientMap, vo.getClientId(),
                    client -> vo.setClientName(client.getName()));
            MesProMpsDO mps = mpsMap.get(vo.getId());
            if (mps != null) {
                String creator = mps.getCreator();
                if (mps.getSaleOrderId() != null) {
                    creator = saleOrderCreatorMap.computeIfAbsent(mps.getSaleOrderId(), orderId -> {
                        var order = saleOrderApi.getSaleOrder(orderId).getCheckedData();
                        return order != null ? order.getCreator() : null;
                    });
                }
                vo.setCreator(creator);
                vo.setCanIssue(superAdmin || (loginUserId != null && String.valueOf(loginUserId).equals(creator)));
            }
        });
    }
 
}