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
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.Sample;
import com.ruoyi.lims.pojo.SampleStatusLog;
import com.ruoyi.lims.pojo.SampleStockRecord;
import com.ruoyi.lims.service.SampleService;
import com.ruoyi.lims.service.SampleStatusLogService;
import com.ruoyi.lims.service.SampleStockRecordService;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
@RestController
@AllArgsConstructor
@RequestMapping("/lims/sample")
@Api(value = "Sample", tags = "样品管理表")
public class SampleController {
 
    private SampleService sampleservice;
    private SampleStockRecordService stockRecordService;
    private SampleStatusLogService statusLogService;
 
    private static final String ST_IN_STOCK = "inStock";
    private static final String ST_OUT_STOCK = "outStock";
    private static final String ST_TESTING = "testing";
    private static final String ST_DESTROYED = "destroyed";
 
    @GetMapping("/listPage")
    @ApiOperation("分页查询所有样品管理表")
    public AjaxResult listPage(Page<Sample> page, Sample sample) {
        IPage<Sample> listPage = sampleservice.listPage(page, sample);
        return AjaxResult.success(listPage);
    }
 
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询样品管理表")
    public AjaxResult getSample(@PathVariable Long id) {
        return AjaxResult.success(sampleservice.getById(id));
    }
 
    /**
     * 样品详情:样品本体 + 出入库流水 + 状态变更历史
     */
    @GetMapping("/detail/{id}")
    @ApiOperation("样品详情(含出入库流水与状态变更历史)")
    public AjaxResult detail(@PathVariable Long id) {
        Sample sample = sampleservice.getById(id);
        if (sample == null) {
            return AjaxResult.error("样品不存在");
        }
 
        QueryWrapper<SampleStockRecord> rw = new QueryWrapper<>();
        rw.eq("sample_id", id).orderByDesc("operate_time").orderByDesc("id");
        List<SampleStockRecord> records = stockRecordService.list(rw);
 
        QueryWrapper<SampleStatusLog> sw = new QueryWrapper<>();
        sw.eq("sample_id", id).orderByDesc("operate_time").orderByDesc("id");
        List<SampleStatusLog> logs = statusLogService.list(sw);
 
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("sample", sample);
        result.put("stockRecords", records);
        result.put("statusLogs", logs);
        return AjaxResult.success(result);
    }
 
    @PostMapping("/add")
    @ApiOperation("新增样品管理表")
    public AjaxResult add(@RequestBody Sample sample) {
        boolean ok = sampleservice.save(sample);
        // 新建样品默认视为一次入库,补一条流水,方便追溯
        if (ok && sample.getId() != null) {
            SampleStockRecord rec = new SampleStockRecord();
            rec.setSampleId(sample.getId());
            rec.setSampleCode(sample.getSampleCode());
            rec.setSampleName(sample.getSampleName());
            rec.setRecordType("in");
            rec.setQuantity(sample.getQuantity());
            rec.setUnit(sample.getUnit());
            rec.setAfterStatus(sample.getSampleStatus());
            rec.setToLocation(sample.getStorageLocation());
            rec.setOperator(currentUser());
            rec.setOperateTime(LocalDateTime.now());
            rec.setPurpose("样品登记入库");
            stockRecordService.save(rec);
        }
        return AjaxResult.success(ok);
    }
 
    @PostMapping("/update")
    @ApiOperation("修改样品管理表")
    public AjaxResult update(@RequestBody Sample sample) {
        Sample old = sampleservice.getById(sample.getId());
        boolean ok = sampleservice.updateById(sample);
 
        // 状态被手工改动时留痕
        if (ok && old != null && sample.getSampleStatus() != null
                && !sample.getSampleStatus().equals(old.getSampleStatus())) {
            SampleStatusLog log = new SampleStatusLog();
            log.setSampleId(sample.getId());
            log.setSampleCode(old.getSampleCode());
            log.setFromStatus(old.getSampleStatus());
            log.setToStatus(sample.getSampleStatus());
            log.setChangeReason("表单修改");
            log.setOperator(currentUser());
            log.setOperateTime(LocalDateTime.now());
            statusLogService.save(log);
        }
        return AjaxResult.success(ok);
    }
 
    @DeleteMapping("/delete")
    @ApiOperation("删除样品管理表")
    public AjaxResult delete(@RequestBody List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) return AjaxResult.error("请传入要删除的ID");
        return AjaxResult.success(sampleservice.removeBatchByIds(ids));
    }
 
    /**
     * 样品出库:校验状态与数量 -> 写流水 -> 写状态历史 -> 更新样品状态
     */
    @PostMapping("/outStock")
    @ApiOperation("样品出库")
    public AjaxResult outStock(@RequestBody Map<String, Object> body) {
        Long sampleId = toLong(body.get("sampleId"));
        if (sampleId == null) {
            return AjaxResult.error("sampleId 不能为空");
        }
        Sample sample = sampleservice.getById(sampleId);
        if (sample == null) {
            return AjaxResult.error("样品不存在");
        }
        if (ST_DESTROYED.equals(sample.getSampleStatus())) {
            return AjaxResult.error("样品已销毁,不能出库");
        }
        if (ST_OUT_STOCK.equals(sample.getSampleStatus())) {
            return AjaxResult.error("样品已是出库状态,无需重复出库");
        }
 
        BigDecimal qty = toDecimal(body.get("quantity"));
        if (qty == null || qty.compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("出库数量必须大于 0");
        }
        BigDecimal stock = sample.getQuantity() == null ? BigDecimal.ZERO : sample.getQuantity();
        if (qty.compareTo(stock) > 0) {
            return AjaxResult.error("出库数量超过当前库存(现有 " + stock.stripTrailingZeros().toPlainString()
                    + (sample.getUnit() == null ? "" : sample.getUnit()) + ")");
        }
 
        String beforeStatus = sample.getSampleStatus();
        BigDecimal afterQty = stock.subtract(qty);
        // 全部出库则置为出库状态,部分出库保持原状态
        String afterStatus = afterQty.compareTo(BigDecimal.ZERO) == 0 ? ST_OUT_STOCK : beforeStatus;
 
        SampleStockRecord rec = new SampleStockRecord();
        rec.setSampleId(sample.getId());
        rec.setSampleCode(sample.getSampleCode());
        rec.setSampleName(sample.getSampleName());
        rec.setRecordType("out");
        rec.setQuantity(qty);
        rec.setUnit(sample.getUnit());
        rec.setBeforeStatus(beforeStatus);
        rec.setAfterStatus(afterStatus);
        rec.setFromLocation(sample.getStorageLocation());
        rec.setToLocation(str(body.get("toLocation")));
        rec.setRecipient(str(body.get("recipient")));
        rec.setPurpose(str(body.get("purpose")));
        rec.setRelatedExperiment(str(body.get("relatedExperiment")));
        rec.setRemark(str(body.get("remark")));
        rec.setOperator(currentUser());
        rec.setOperateTime(LocalDateTime.now());
        stockRecordService.save(rec);
 
        if (!eq(beforeStatus, afterStatus)) {
            SampleStatusLog log = new SampleStatusLog();
            log.setSampleId(sample.getId());
            log.setSampleCode(sample.getSampleCode());
            log.setFromStatus(beforeStatus);
            log.setToStatus(afterStatus);
            log.setChangeReason("出库" + (str(body.get("purpose")) == null ? "" : ":" + str(body.get("purpose"))));
            log.setOperator(currentUser());
            log.setOperateTime(LocalDateTime.now());
            statusLogService.save(log);
        }
 
        Sample upd = new Sample();
        upd.setId(sample.getId());
        upd.setQuantity(afterQty);
        upd.setSampleStatus(afterStatus);
        if (str(body.get("toLocation")) != null) {
            upd.setStorageLocation(str(body.get("toLocation")));
        }
        sampleservice.updateById(upd);
 
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("sampleId", sample.getId());
        ret.put("beforeQuantity", stock);
        ret.put("afterQuantity", afterQty);
        ret.put("beforeStatus", beforeStatus);
        ret.put("afterStatus", afterStatus);
        return AjaxResult.success("出库成功", ret);
    }
 
    /**
     * 样品入库(追加数量或新建后补录)
     */
    @PostMapping("/inStock")
    @ApiOperation("样品入库")
    public AjaxResult inStock(@RequestBody Map<String, Object> body) {
        Long sampleId = toLong(body.get("sampleId"));
        if (sampleId == null) {
            return AjaxResult.error("sampleId 不能为空");
        }
        Sample sample = sampleservice.getById(sampleId);
        if (sample == null) {
            return AjaxResult.error("样品不存在");
        }
        BigDecimal qty = toDecimal(body.get("quantity"));
        if (qty == null || qty.compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("入库数量必须大于 0");
        }
 
        String beforeStatus = sample.getSampleStatus();
        BigDecimal stock = sample.getQuantity() == null ? BigDecimal.ZERO : sample.getQuantity();
        BigDecimal afterQty = stock.add(qty);
        String afterStatus = ST_OUT_STOCK.equals(beforeStatus) ? ST_IN_STOCK : beforeStatus;
 
        SampleStockRecord rec = new SampleStockRecord();
        rec.setSampleId(sample.getId());
        rec.setSampleCode(sample.getSampleCode());
        rec.setSampleName(sample.getSampleName());
        rec.setRecordType("in");
        rec.setQuantity(qty);
        rec.setUnit(sample.getUnit());
        rec.setBeforeStatus(beforeStatus);
        rec.setAfterStatus(afterStatus);
        rec.setToLocation(str(body.get("toLocation")) == null ? sample.getStorageLocation() : str(body.get("toLocation")));
        rec.setRecipient(str(body.get("recipient")));
        rec.setPurpose(str(body.get("purpose")) == null ? "样品入库" : str(body.get("purpose")));
        rec.setRemark(str(body.get("remark")));
        rec.setOperator(currentUser());
        rec.setOperateTime(LocalDateTime.now());
        stockRecordService.save(rec);
 
        if (!eq(beforeStatus, afterStatus)) {
            SampleStatusLog log = new SampleStatusLog();
            log.setSampleId(sample.getId());
            log.setSampleCode(sample.getSampleCode());
            log.setFromStatus(beforeStatus);
            log.setToStatus(afterStatus);
            log.setChangeReason("入库");
            log.setOperator(currentUser());
            log.setOperateTime(LocalDateTime.now());
            statusLogService.save(log);
        }
 
        Sample upd = new Sample();
        upd.setId(sample.getId());
        upd.setQuantity(afterQty);
        upd.setSampleStatus(afterStatus);
        if (str(body.get("toLocation")) != null) {
            upd.setStorageLocation(str(body.get("toLocation")));
        }
        sampleservice.updateById(upd);
 
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("sampleId", sample.getId());
        ret.put("beforeQuantity", stock);
        ret.put("afterQuantity", afterQty);
        ret.put("beforeStatus", beforeStatus);
        ret.put("afterStatus", afterStatus);
        return AjaxResult.success("入库成功", ret);
    }
 
    /**
     * 样品状态流转(在库/检测中/出库/销毁)
     */
    @PostMapping("/changeStatus")
    @ApiOperation("样品状态流转")
    public AjaxResult changeStatus(@RequestBody Map<String, Object> body) {
        Long sampleId = toLong(body.get("sampleId"));
        String toStatus = str(body.get("toStatus"));
        if (sampleId == null || toStatus == null) {
            return AjaxResult.error("sampleId 和 toStatus 不能为空");
        }
        Sample sample = sampleservice.getById(sampleId);
        if (sample == null) {
            return AjaxResult.error("样品不存在");
        }
        String fromStatus = sample.getSampleStatus();
        if (eq(fromStatus, toStatus)) {
            return AjaxResult.error("样品已处于该状态");
        }
 
        SampleStatusLog log = new SampleStatusLog();
        log.setSampleId(sample.getId());
        log.setSampleCode(sample.getSampleCode());
        log.setFromStatus(fromStatus);
        log.setToStatus(toStatus);
        log.setChangeReason(str(body.get("changeReason")));
        log.setOperator(currentUser());
        log.setOperateTime(LocalDateTime.now());
        statusLogService.save(log);
 
        Sample upd = new Sample();
        upd.setId(sample.getId());
        upd.setSampleStatus(toStatus);
        sampleservice.updateById(upd);
 
        return AjaxResult.success("状态已更新");
    }
 
    /* ---------------- 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 BigDecimal toDecimal(Object v) {
        if (v == null) return null;
        try {
            return new BigDecimal(String.valueOf(v).trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private static boolean eq(String a, String b) {
        return a == null ? b == null : a.equals(b);
    }
}