云
2 天以前 251be431ad12399fe4ebce599c353d05dcec7888
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
package cn.iocoder.yudao.module.mes.framework.qrcode;
 
import cn.hutool.core.util.StrUtil;
import org.springframework.web.util.UriComponentsBuilder;
 
/**
 * 追溯码提取工具。
 *
 * <p>现场标签印的是追溯二维码,内容为 {@code {追溯网址}?code={追溯码}};
 * 扫码枪也可能把整段网址直接提交。所有接收码值的接口都应先经过本类规范化,
 * 避免把网址当作码值查询。前端 {@code src/utils/traceCode.ts} 保持同一口径。
 */
public final class MesTraceCodeUtils {
 
    private static final int MAX_CODE_LENGTH = 64;
 
    private MesTraceCodeUtils() {
    }
 
    /**
     * 从扫描原文中提取追溯码:网址取 {@code code} 参数,其余原样使用。
     */
    public static String extractCode(String raw) {
        String value = StrUtil.trim(raw);
        if (StrUtil.isEmpty(value)) {
            throw new IllegalArgumentException("请扫描或输入追溯码");
        }
        if (value.regionMatches(true, 0, "http://", 0, 7) || value.regionMatches(true, 0, "https://", 0, 8)) {
            String code;
            try {
                code = UriComponentsBuilder.fromUriString(value).build().getQueryParams().getFirst("code");
            } catch (Exception ex) {
                throw new IllegalArgumentException("追溯网址格式不正确");
            }
            if (StrUtil.isBlank(code)) {
                throw new IllegalArgumentException("该追溯网址不包含追溯码");
            }
            value = code.trim();
        }
        if (value.length() > MAX_CODE_LENGTH || value.chars().anyMatch(Character::isWhitespace)) {
            throw new IllegalArgumentException("追溯码格式不正确");
        }
        return value;
    }
 
}