tuqin
2026-10-29 0a3129cb06fcea6677245097715dcc6fa3de65e5
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package com.ruoyi.lims.controller;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.lims.pojo.Experiment;
import com.ruoyi.lims.pojo.ExperimentResource;
import com.ruoyi.lims.pojo.ExperimentStep;
import com.ruoyi.lims.pojo.Reagent;
import com.ruoyi.lims.pojo.ReagentRecord;
import com.ruoyi.lims.service.ExperimentResourceService;
import com.ruoyi.lims.service.ExperimentService;
import com.ruoyi.lims.service.ExperimentStepService;
import com.ruoyi.lims.service.ReagentRecordService;
import com.ruoyi.lims.service.ReagentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
 
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
@RestController
@AllArgsConstructor
@RequestMapping("/lims/experiment")
@Api(value = "Experiment", tags = "实验管理表")
public class ExperimentController {
 
    private ExperimentService experimentservice;
    private ExperimentStepService stepService;
    private ExperimentResourceService resourceService;
    private ReagentService reagentService;
    private ReagentRecordService reagentRecordService;
 
    @GetMapping("/listPage")
    @ApiOperation("分页查询所有实验管理表")
    public AjaxResult listPage(Page<Experiment> page, Experiment experiment) {
        IPage<Experiment> listPage = experimentservice.listPage(page, experiment);
        return AjaxResult.success(listPage);
    }
 
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询实验管理表")
    public AjaxResult getExperiment(@PathVariable Long id) {
        return AjaxResult.success(experimentservice.getById(id));
    }
 
    /**
     * 实验详情:实验本体 + 流程节点 + 已分配资源 + 执行进度
     */
    @GetMapping("/detail/{id}")
    @ApiOperation("实验详情(含流程节点与资源分配)")
    public AjaxResult detail(@PathVariable Long id) {
        Experiment exp = experimentservice.getById(id);
        if (exp == null) {
            return AjaxResult.error("实验不存在");
        }
 
        QueryWrapper<ExperimentStep> sw = new QueryWrapper<>();
        sw.eq("experiment_id", id).orderByAsc("step_no").orderByAsc("id");
        List<ExperimentStep> steps = stepService.list(sw);
 
        QueryWrapper<ExperimentResource> rw = new QueryWrapper<>();
        rw.eq("experiment_id", id).orderByAsc("id");
        List<ExperimentResource> resources = resourceService.list(rw);
 
        int total = steps.size();
        long done = steps.stream().filter(s -> "completed".equals(s.getStepStatus())).count();
        int progress = total == 0 ? 0 : (int) Math.round(done * 100.0 / total);
 
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("experiment", exp);
        result.put("steps", steps);
        result.put("resources", resources);
        result.put("stepTotal", total);
        result.put("stepCompleted", done);
        result.put("progress", progress);
        return AjaxResult.success(result);
    }
 
    @PostMapping("/add")
    @ApiOperation("新增实验管理表")
    public AjaxResult add(@RequestBody Experiment experiment) {
        return AjaxResult.success(experimentservice.save(experiment));
    }
 
    @PostMapping("/update")
    @ApiOperation("修改实验管理表")
    public AjaxResult update(@RequestBody Experiment experiment) {
        return AjaxResult.success(experimentservice.updateById(experiment));
    }
 
    @DeleteMapping("/delete")
    @ApiOperation("删除实验管理表")
    public AjaxResult delete(@RequestBody List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) return AjaxResult.error("请传入要删除的ID");
        boolean ok = experimentservice.removeBatchByIds(ids);
        if (ok && !CollectionUtils.isEmpty(ids)) {
            // 连带清掉步骤与资源,避免孤儿数据
            QueryWrapper<ExperimentStep> sw = new QueryWrapper<>();
            sw.in("experiment_id", ids);
            stepService.remove(sw);
            QueryWrapper<ExperimentResource> rw = new QueryWrapper<>();
            rw.in("experiment_id", ids);
            resourceService.remove(rw);
        }
        return AjaxResult.success(ok);
    }
 
    /* ==================== 流程节点(SOP 步骤) ==================== */
 
    /**
     * 批量保存步骤:传全量列表,先删后插,保证顺序和内容一致
     */
    @PostMapping("/step/saveBatch")
    @ApiOperation("批量保存实验流程节点")
    public AjaxResult saveSteps(@RequestBody Map<String, Object> body) {
        Long experimentId = toLong(body.get("experimentId"));
        if (experimentId == null) {
            return AjaxResult.error("experimentId 不能为空");
        }
        Experiment exp = experimentservice.getById(experimentId);
        if (exp == null) {
            return AjaxResult.error("实验不存在");
        }
        Object rawList = body.get("steps");
        if (!(rawList instanceof List)) {
            return AjaxResult.error("steps 必须是数组");
        }
 
        QueryWrapper<ExperimentStep> dw = new QueryWrapper<>();
        dw.eq("experiment_id", experimentId);
        stepService.remove(dw);
 
        List<?> list = (List<?>) rawList;
        int idx = 0;
        for (Object o : list) {
            if (!(o instanceof Map)) continue;
            Map<?, ?> m = (Map<?, ?>) o;
            ExperimentStep step = new ExperimentStep();
            step.setExperimentId(experimentId);
            step.setExperimentCode(exp.getExperimentCode());
            step.setStepNo(toInt(m.get("stepNo")) == null ? (idx + 1) : toInt(m.get("stepNo")));
            step.setStepName(str(m.get("stepName")));
            step.setStepContent(str(m.get("stepContent")));
            step.setExpectedDuration(toInt(m.get("expectedDuration")));
            step.setExecutor(str(m.get("executor")));
            step.setStepStatus(str(m.get("stepStatus")) == null ? "pending" : str(m.get("stepStatus")));
            step.setRemark(str(m.get("remark")));
            stepService.save(step);
            idx++;
        }
 
        return AjaxResult.success("已保存 " + idx + " 个步骤");
    }
 
    /**
     * 完成/推进单个步骤
     */
    @PostMapping("/step/complete")
    @ApiOperation("完成实验步骤")
    public AjaxResult completeStep(@RequestBody Map<String, Object> body) {
        Long stepId = toLong(body.get("stepId"));
        if (stepId == null) {
            return AjaxResult.error("stepId 不能为空");
        }
        ExperimentStep step = stepService.getById(stepId);
        if (step == null) {
            return AjaxResult.error("步骤不存在");
        }
        if ("completed".equals(step.getStepStatus())) {
            return AjaxResult.error("该步骤已完成");
        }
 
        String operator = currentUser();
        LocalDateTime now = LocalDateTime.now();
 
        ExperimentStep upd = new ExperimentStep();
        upd.setId(stepId);
        upd.setStepStatus(str(body.get("stepStatus")) == null ? "completed" : str(body.get("stepStatus")));
        upd.setStepResult(str(body.get("stepResult")));
        upd.setExecutor(str(body.get("executor")) == null ? operator : str(body.get("executor")));
        if (step.getActualStartTime() == null) {
            upd.setActualStartTime(now);
        }
        upd.setActualEndTime(now);
        stepService.updateById(upd);
 
        // 全部步骤完成 -> 实验状态置为已完成
        Long expId = step.getExperimentId();
        if (expId != null) {
            QueryWrapper<ExperimentStep> cw = new QueryWrapper<>();
            cw.eq("experiment_id", expId).ne("step_status", "completed");
            long remain = stepService.count(cw);
            if (remain == 0) {
                Experiment eu = new Experiment();
                eu.setId(expId);
                eu.setExperimentStatus("completed");
                experimentservice.updateById(eu);
            } else {
                Experiment eu = new Experiment();
                eu.setId(expId);
                eu.setExperimentStatus("inProgress");
                experimentservice.updateById(eu);
            }
        }
 
        return AjaxResult.success("步骤已完成");
    }
 
    /* ==================== 资源分配 ==================== */
 
    /**
     * 分配资源:仪器/人员只记录;试剂会实际扣减库存并写出入库流水
     */
    @PostMapping("/assignResource")
    @ApiOperation("为实验分配资源")
    public AjaxResult assignResource(@RequestBody Map<String, Object> body) {
        Long experimentId = toLong(body.get("experimentId"));
        if (experimentId == null) {
            return AjaxResult.error("experimentId 不能为空");
        }
        Experiment exp = experimentservice.getById(experimentId);
        if (exp == null) {
            return AjaxResult.error("实验不存在");
        }
        String resourceType = str(body.get("resourceType"));
        if (resourceType == null) {
            return AjaxResult.error("resourceType 不能为空");
        }
 
        ExperimentResource res = new ExperimentResource();
        res.setExperimentId(experimentId);
        res.setExperimentCode(exp.getExperimentCode());
        res.setResourceType(resourceType);
        res.setResourceId(toLong(body.get("resourceId")));
        res.setResourceCode(str(body.get("resourceCode")));
        res.setResourceName(str(body.get("resourceName")));
        res.setQuantity(toDecimal(body.get("quantity")));
        res.setUnit(str(body.get("unit")));
        res.setUsageTime(str(body.get("usageTime")));
        res.setStatus(str(body.get("status")) == null ? "planned" : str(body.get("status")));
        res.setRemark(str(body.get("remark")));
 
        // 试剂/耗材:真实扣库存 + 写流水
        if ("reagent".equals(resourceType) && res.getResourceId() != null) {
            Reagent re = reagentService.getById(res.getResourceId());
            if (re == null) {
                return AjaxResult.error("试剂/耗材不存在");
            }
            BigDecimal useQty = res.getQuantity() == null ? BigDecimal.ZERO : res.getQuantity();
            BigDecimal stock = re.getCurrentStock() == null ? BigDecimal.ZERO : re.getCurrentStock();
            if (useQty.compareTo(BigDecimal.ZERO) > 0 && useQty.compareTo(stock) > 0) {
                return AjaxResult.error("试剂库存不足(现有 " + stock.stripTrailingZeros().toPlainString()
                        + (re.getUnit() == null ? "" : re.getUnit()) + ")");
            }
            res.setResourceCode(re.getReagentCode());
            res.setResourceName(re.getReagentName());
            if (res.getUnit() == null) res.setUnit(re.getUnit());
 
            if (useQty.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal after = stock.subtract(useQty);
                ReagentRecord rec = new ReagentRecord();
                rec.setReagentId(re.getId());
                rec.setReagentCode(re.getReagentCode());
                rec.setReagentName(re.getReagentName());
                rec.setRecordType("out");
                rec.setQuantity(useQty);
                rec.setBeforeStock(stock);
                rec.setAfterStock(after);
                rec.setOperator(currentUser());
                rec.setOperateTime(LocalDateTime.now());
                rec.setPurpose("实验领用");
                rec.setRelatedExperiment(exp.getExperimentCode());
                reagentRecordService.save(rec);
 
                Reagent ru = new Reagent();
                ru.setId(re.getId());
                ru.setCurrentStock(after);
                reagentService.updateById(ru);
            }
        }
 
        resourceService.save(res);
        return AjaxResult.success("资源已分配");
    }
 
    @DeleteMapping("/resource/{id}")
    @ApiOperation("移除实验资源分配")
    public AjaxResult removeResource(@PathVariable Long id) {
        return AjaxResult.success(resourceService.removeById(id));
    }
 
    /* ==================== 流程模板 ==================== */
 
    /**
     * 常用实验类型的 SOP 模板,前端「套用模板」时按类型拉取
     */
    @GetMapping("/stepTemplate")
    @ApiOperation("获取流程模板")
    public AjaxResult stepTemplate(@RequestParam(required = false) String type) {
        Map<String, List<Map<String, Object>>> templates = new LinkedHashMap<>();
 
        templates.put("chemicalAnalysis", buildSteps(
                new String[][]{
                        {"样品前处理", "按标准称取样品,定容至刻度,摇匀静置 10 分钟"},
                        {"试剂配制", "按方法要求配制标准溶液与显色剂,现配现用"},
                        {"仪器预热", "开启分析仪器预热 30 分钟,待基线稳定"},
                        {"标准曲线绘制", "依次测定标准系列,绘制曲线,相关系数应 ≥0.999"},
                        {"样品测定", "按顺序测定样品,每 10 个样品插入一次质控样"},
                        {"数据处理", "计算浓度结果,做平行样偏差检查"}
                }));
        templates.put("physicalTest", buildSteps(
                new String[][]{
                        {"试样制备", "按标准裁切/加工试样,记录尺寸与外观"},
                        {"设备调试", "校准试验机零点,设置试验速度"},
                        {"装夹定位", "将试样装夹于夹具中心,确保受力轴线一致"},
                        {"加载试验", "按设定速度加载直至破坏,记录最大力值"},
                        {"结果计算", "计算强度/伸长率,取 3 个有效试样的平均值"}
                }));
        templates.put("microbialTest", buildSteps(
                new String[][]{
                        {"培养基配制", "按配方配制培养基,121℃ 灭菌 15 分钟"},
                        {"样品稀释", "无菌操作梯度稀释样品,制备 10^-1 ~ 10^-3 稀释液"},
                        {"接种", "取 1mL 稀释液注入平皿,倾注培养基混匀"},
                        {"培养", "36±1℃ 培养 48±2 小时"},
                        {"菌落计数", "选取 30~300 个菌落的平皿计数,换算 CFU/mL"}
                }));
 
        if (type != null && templates.containsKey(type)) {
            return AjaxResult.success(templates.get(type));
        }
        return AjaxResult.success(templates);
    }
 
    private List<Map<String, Object>> buildSteps(String[][] arr) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            Map<String, Object> m = new LinkedHashMap<>();
            m.put("stepNo", i + 1);
            m.put("stepName", arr[i][0]);
            m.put("stepContent", arr[i][1]);
            m.put("stepStatus", "pending");
            list.add(m);
        }
        return list;
    }
 
    /* ---------------- helpers ---------------- */
 
    private String currentUser() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            return "system";
        }
    }
 
    private static String str(Object v) {
        if (v == null) return null;
        String s = String.valueOf(v).trim();
        return s.isEmpty() ? null : s;
    }
 
    private static Long toLong(Object v) {
        if (v == null) return null;
        try {
            return Long.valueOf(String.valueOf(v).trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private static Integer toInt(Object v) {
        if (v == null) return null;
        try {
            return Integer.valueOf(String.valueOf(v).trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private static BigDecimal toDecimal(Object v) {
        if (v == null) return null;
        try {
            return new BigDecimal(String.valueOf(v).trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
}