skyouc
2 天以前 45a230e870b26b51d3006273a36df78203521253
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
package com.vincent.rsf.server.manager.service.impl;
 
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.vincent.rsf.framework.common.R;
import com.vincent.rsf.framework.exception.CoolException;
import com.vincent.rsf.server.api.entity.enums.TaskStsType;
import com.vincent.rsf.server.api.entity.enums.TaskType;
import com.vincent.rsf.server.manager.entity.*;
import com.vincent.rsf.server.manager.enums.AsnExceStatus;
import com.vincent.rsf.server.manager.enums.WaveExceStatus;
import com.vincent.rsf.server.manager.mapper.WaveMapper;
import com.vincent.rsf.server.manager.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vincent.rsf.server.manager.utils.OptimalAlgorithmUtil;
import com.vincent.rsf.server.system.constant.SerialRuleCode;
import com.vincent.rsf.server.system.utils.SerialRuleUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
import java.util.stream.Collectors;
 
@Service("waveService")
public class WaveServiceImpl extends ServiceImpl<WaveMapper, Wave> implements WaveService {
 
    @Autowired
    private AsnOrderItemService asnOrderItemService;
    @Autowired
    private AsnOrderService asnOrderService;
    @Autowired
    private WaveItemService waveItemService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskItemService taskItemService;
    @Autowired
    private LocItemService locItemService;
    @Autowired
    private LocService locService;
 
    /**
     * @param
     * @param loginUserId
     * @return
     * @author Ryan
     * @description 波次任务下发
     * @time 2025/4/25 16:24
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R publicTask(Map<String, Object> map, Long loginUserId) {
        List<WaveItem> itemParams = (List<WaveItem>) map.get("waveItem");
        if (Objects.isNull(itemParams) || itemParams.isEmpty()) {
            throw new CoolException("参数不能为空!!");
        }
        Wave wave = (Wave) map.get("wave");
        Wave waves = this.getById(new LambdaQueryWrapper<Wave>().in(Wave::getId, wave.getId()));
        if (Objects.isNull(waves)) {
            throw new CoolException("波次数据不存在!!");
        }
        List<Long> list = itemParams.stream().map(WaveItem::getWaveId).collect(Collectors.toList());
        List<WaveItem> waveItems = waveItemService.list(new LambdaQueryWrapper<WaveItem>().in(WaveItem::getWaveId, list));
        if (waveItems.isEmpty()) {
            throw new CoolException("波次明细不存在!!");
        }
        /**生成出库任务*/
        try {
            generateOutTask(itemParams, loginUserId, wave);
        } catch (Exception e) {
            throw new CoolException("库位获取失败!!!");
        }
        //TODO 1. 根据波次明细生成出库任务
        // 2. 根据物料SKU寻找符合物料库位  {1. 根据物料编码,批次,动态字段 查询符合的库位,再根据库位中物料的数量选择最适合的库位 2. 判断当前订单是全拖出库还是拣料入库}
        // 3. 修改主单、波次执行数量
        // 4. 判断全仓出库或拣料出库
        List<Long> orderIds = waveItems.stream().map(WaveItem::getOrderId).collect(Collectors.toList());
 
        List<AsnOrder> orders = asnOrderService.list(new LambdaQueryWrapper<AsnOrder>().in(AsnOrder::getId, orderIds));
        /**修改出库单状态*/
        if (!asnOrderService.update(new LambdaQueryWrapper<AsnOrder>()
                .eq(AsnOrder::getExceStatus, AsnExceStatus.OUT_STOCK_STATUS_TASK_WORKING.val)
                .in(AsnOrder::getId, orders))) {
            throw new CoolException("出库单据状态修改失败!!");
        }
        /**修改波次单据执行状态*/
        if (!this.update(new LambdaUpdateWrapper<Wave>().set(Wave::getExceStatus, WaveExceStatus.WAVE_EXCE_STATUS_TASK).eq(Wave::getId, wave.getId()))) {
            throw new CoolException("波次状态修改失败!!");
        }
        return R.ok();
    }
 
    /**
     * @param
     * @param loginUserId
     * @param wave
     * @return
     * @author Ryan
     * @description 生成出库任务
     * @time 2025/4/28 14:01
     */
    @Transactional(rollbackFor = Exception.class)
    private synchronized void generateOutTask(List<WaveItem> itemParams, Long loginUserId, Wave wave) throws Exception {
        List<LocItem> locItemList = new ArrayList<>();
        for (WaveItem param : itemParams) {
            String locs = param.getStockLocs();
            List<LocItem> locItems = JSONArray.parseArray(locs, LocItem.class);
            if (locItems.isEmpty()) {
                continue;
            }
            List<Long> list = locItems.stream().map(LocItem::getId).collect(Collectors.toList());
            /**根据供应商批次,物料码, 动态字段查询指定的物料库存信息*/
            List<LocItem> items = locItemService.list(new LambdaQueryWrapper<LocItem>()
                    .eq(LocItem::getSplrBatch, param.getSplrBatch())
                    .in(LocItem::getLocId, list)
                    .eq(StringUtils.isNotBlank(param.getFieldsIndex()), LocItem::getFieldsIndex, param.getFieldsIndex())
                    .eq(LocItem::getMatnrCode, param.getMatnrCode()));
            if (items.isEmpty()) {
                throw new CoolException("库存信息有变,请取消当前波次,生新生成新的波次!!");
            }
            /***将有货有的明细信息存放到库位信息中*/
            for (int i = 0; i < items.size(); i++) {
                items.get(i)
                        .setWaveId(param.getWaveId())
                        .setWaveCode(param.getWaveCode())
                        .setWaveItemId(param.getId());
            }
            locItemList.addAll(items);
        }
        if (locItemList.isEmpty()) {
            throw new CoolException("没有合适库位!!");
        }
 
        /**拆分波次明细库位集,合并相同库位,分解任务明细*/
        Map<Long, List<LocItem>> listMap = locItemList.stream().collect(Collectors.groupingBy(LocItem::getLocId));
        /**根据库位汇总信息,生成任务明细**/
        listMap.keySet().forEach(key -> {
            List<LocItem> locItems = listMap.get(key);
            LocItem item1 = locItems.stream().findFirst().get();
            WaveItem waveItem = waveItemService.getById(item1.getWaveItemId());
            if (null == waveItem || Objects.isNull(waveItem)) {
                throw new CoolException("数据错误:波次明细不存在!!");
            }
            //TODO 当前任务完成后,通过定时事件判断是全盘出库,还是拣料再入库
            Loc loc = locService.getById(key);
            Task task = new Task();
            String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_TASK_CODE, null);
            if (StringUtils.isBlank(ruleCode)) {
                throw new CoolException("编码规则错误:请检查「SYS_TASK_CODE」是否设置完成!!");
            }
            if (Objects.isNull(loc)) {
                throw new CoolException("库位不存在!!");
            }
            task.setTaskCode(ruleCode)
                    .setTaskType(TaskType.TASK_TYPE_OUT.type)
                    .setTaskStatus(TaskStsType.GENERATE_OUT.id)
                    .setBarcode(loc.getBarcode())
                    .setOrgLoc(loc.getCode())
                    .setCreateBy(loginUserId)
                    .setUpdateBy(loginUserId)
                    .setTargSite(wave.getTargSite());
 
            if (!taskService.save(task)) {
                throw new CoolException("任务生成失败!!");
            }
            List<TaskItem> taskItems = new ArrayList<>();
            /**生成任务明细信息*/
            for (LocItem item : locItems) {
                TaskItem taskItem = new TaskItem();
                BeanUtils.copyProperties(item, taskItem);
                taskItem.setTaskId(task.getId())
                        .setId(null)
                        .setSource(item.getWaveItemId());
                taskItems.add(taskItem);
            }
            if (!taskItemService.saveBatch(taskItems)) {
                throw new CoolException("任务明细保存失败!!");
            }
 
            /**修改波次执行数量*/
            taskItems.forEach(item -> {
                boolean update = waveItemService.update(new LambdaUpdateWrapper<WaveItem>()
                        .eq(WaveItem::getWaveId, item.getSource())
                        .set(WaveItem::getWorkQty, item.getAnfme()));
                if (!update) {
                    throw new CoolException("波次执行数量修改失败!!");
                }
            });
 
            List<WaveItem> waveItems = waveItemService.list(new LambdaQueryWrapper<WaveItem>().eq(WaveItem::getWaveId, wave.getId()));
            double sum = waveItems.stream().mapToDouble(WaveItem::getWorkQty).sum();
            /**波次主单信息修改*/
            if (!update(new LambdaUpdateWrapper<Wave>()
                    .eq(Wave::getId, wave.getId())
                    .set(Wave::getWorkQty, sum)
                    .set(Wave::getExceStatus, WaveExceStatus.WAVE_EXCE_STATUS_TASK.val))) {
                throw new CoolException("波次主单信息修改失败!!");
            }
 
        });
    }
 
    /**
     * @param
     * @return
     * @author Ryan
     * @description 预览波次下发任务
     * @time 2025/4/27 11:09
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<WaveItem> mergeWavePreview(Long waveId) {
        Wave wave = this.getById(waveId);
        if (Objects.isNull(wave)) {
            throw new CoolException("波次不能存在!!");
        }
        List<WaveItem> waveItems = waveItemService.list(new LambdaQueryWrapper<WaveItem>().eq(WaveItem::getWaveId, waveId));
        if (waveItems.isEmpty()) {
            throw new CoolException("波次明细不存在!!");
        }
        List<WaveItem> itemPreview = null;
        try {
            itemPreview = getLocs(waveItems);
        } catch (Exception e) {
            throw new CoolException("库位获取失败!!!!");
        }
        return itemPreview;
    }
 
    /**
     * @param
     * @param waveItems
     * @return
     * @author Ryan
     * @description 根据物料编码,批次,动态字段 查询符合的库位,再根据库位中物料的数量选择最适合的库位
     * @time 2025/4/27 09:26
     */
    private synchronized List<WaveItem> getLocs(List<WaveItem> waveItems) throws Exception {
        //TODO  根据物料编码,批次,动态字段 查询符合的库位,再根据库位中物料的数量选择最适合的库位
        waveItems.forEach(waveItem -> {
            List<LocItem> locItems = locItemService.list(new QueryWrapper<LocItem>()
                    .select("id", "loc_id", "loc_code", "order_id", "SUM(anfme) anfme", "SUM(qty) qty", "SUM(work_qty) work_qty", "splr_batch", "fields_index", "matnr_code")
                    .lambda()
                    .eq(LocItem::getMatnrCode, waveItem.getMatnrCode())
                    .eq(LocItem::getSplrBatch, waveItem.getSplrBatch())
                    .eq(StringUtils.isNotBlank(waveItem.getFieldsIndex()), LocItem::getFieldsIndex, waveItem.getFieldsIndex())
                    .groupBy(LocItem::getMatnrCode, LocItem::getSplrBatch, LocItem::getFieldsIndex, LocItem::getId));
            List<Double> doubles1 = locItems.stream().map(LocItem::getAnfme).collect(Collectors.toList());
            double[] doubles = doubles1.stream().mapToDouble(Double::doubleValue).toArray();
 
            /**使用回溯算法计算,获取符合出库量的最简组合*/
            List<Integer> result = OptimalAlgorithmUtil.findCombination(doubles, waveItem.getAnfme());
 
            String locs = "[]";
            if (Objects.isNull(result) || result.isEmpty()) {
                waveItem.setStockLocs(locs).setStockQty(0.0);
            } else {
                /**过滤集合中最简短的组合*/
                List<LocItem> locsInfo = result.stream()
                        .filter(i -> i >= 0 && i < locItems.size())
                        .map(locItems::get).collect(Collectors.toList());
 
                locs = JSONArray.toJSONString(locsInfo);
                Double sumQty = locsInfo.stream().mapToDouble(LocItem::getAnfme).sum();
                Double surQty = locsInfo.stream().mapToDouble(LocItem::getWorkQty).sum();
                Double qty = locsInfo.stream().mapToDouble(LocItem::getQty).sum();
                Double v = sumQty - surQty - qty;
                waveItem.setStockLocs(locs).setStockQty(v);
            }
        });
        return waveItems;
    }
}