216 lines
7.4 KiB
TypeScript
216 lines
7.4 KiB
TypeScript
import { isRecord } from "@/types/kart";
|
|
|
|
export type DerivedType = "single" | "multi" | "scale" | "num";
|
|
export const DERIVED_TYPES: { value: DerivedType; label: string }[] = [
|
|
{ value: "single", label: "Single" },
|
|
{ value: "multi", label: "Multi" },
|
|
{ value: "scale", label: "Scale" },
|
|
{ value: "num", label: "Numeric" },
|
|
];
|
|
const isDerivedType = (value: unknown): value is DerivedType =>
|
|
value === "single" || value === "multi" || value === "scale" || value === "num";
|
|
|
|
/** Server `derived/list` row reduced to what Create Variable needs. */
|
|
export type DerivedVariable = {
|
|
/** Stored DERIVED_VARIABLE.QID used for update/delete. */
|
|
id: string;
|
|
title: string;
|
|
type: DerivedType;
|
|
/** Legacy DERIVEDJSON: `{"1":{…},"2":{…},"ELSE":{…}}`. */
|
|
derivedJson: string;
|
|
};
|
|
|
|
/**
|
|
* Stored id for update/delete: the server's `variableId` (DERIVED_VARIABLE.QID). Older servers
|
|
* omit it and expand numeric (open) variables to `QID_1`, so fall back to dropping that suffix.
|
|
*/
|
|
export function storedDerivedId(
|
|
qid: string,
|
|
type: DerivedType,
|
|
variableId?: string | null,
|
|
): string {
|
|
if (variableId) return variableId;
|
|
return type === "num" && qid.endsWith("_1") ? qid.slice(0, -2) : qid;
|
|
}
|
|
|
|
const optionalText = (value: unknown): value is string | null | undefined =>
|
|
value === null || value === undefined || typeof value === "string";
|
|
|
|
export function readDerivedVariables(value: unknown): DerivedVariable[] {
|
|
if (!Array.isArray(value)) throw new Error("서버 응답 형식을 확인해 주세요.");
|
|
return value.map((row) => {
|
|
if (
|
|
!isRecord(row) ||
|
|
typeof row.qid !== "string" ||
|
|
row.qid === "" ||
|
|
!optionalText(row.variableId) ||
|
|
!optionalText(row.title) ||
|
|
!optionalText(row.derivedJson) ||
|
|
!isDerivedType(row.qtype)
|
|
)
|
|
throw new Error("서버 응답 형식을 확인해 주세요.");
|
|
return {
|
|
id: storedDerivedId(row.qid, row.qtype, row.variableId),
|
|
title: row.title ?? "",
|
|
type: row.qtype,
|
|
derivedJson: row.derivedJson ?? "",
|
|
};
|
|
});
|
|
}
|
|
|
|
/** One legacy value rule (states/Format.js valueJsonFormat) plus any other stored keys. */
|
|
export type DerivedValue = {
|
|
id: string;
|
|
label: string;
|
|
value: string;
|
|
realCondition: string;
|
|
condition: string;
|
|
format: string;
|
|
/** FILTER_ARRAY text of the rule's condition. */
|
|
array: string;
|
|
rest: Record<string, unknown>;
|
|
};
|
|
export type DerivedElse = { isMissing: boolean; value: string; label: string };
|
|
|
|
const RULE_KEYS = ["label", "value", "realCondition", "condition", "format", "array"] as const;
|
|
|
|
export const newDerivedValue = (id: string): DerivedValue => ({
|
|
id,
|
|
label: "",
|
|
value: "",
|
|
realCondition: "",
|
|
condition: "",
|
|
format: "",
|
|
array: "",
|
|
rest: {},
|
|
});
|
|
|
|
/** Legacy selectVariable: numbered rules become rows, ELSE fills the Else box (else Missing). */
|
|
export function readDerivedJson(json: string): { values: DerivedValue[]; otherwise: DerivedElse } {
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(json);
|
|
} catch {
|
|
throw new Error("파생변수 설정을 읽을 수 없습니다.");
|
|
}
|
|
if (!isRecord(parsed)) throw new Error("파생변수 설정을 읽을 수 없습니다.");
|
|
const text = (value: unknown) =>
|
|
typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
const values: DerivedValue[] = [];
|
|
let otherwise: DerivedElse = { isMissing: true, value: "", label: "" };
|
|
for (const [key, rule] of Object.entries(parsed)) {
|
|
if (!isRecord(rule)) throw new Error("파생변수 설정을 읽을 수 없습니다.");
|
|
if (key === "ELSE") {
|
|
otherwise = { isMissing: false, value: text(rule.value), label: text(rule.label) };
|
|
continue;
|
|
}
|
|
const rest = Object.fromEntries(
|
|
Object.entries(rule).filter(([name]) => !(RULE_KEYS as readonly string[]).includes(name)),
|
|
);
|
|
values.push({
|
|
id: "derived_value_" + values.length,
|
|
label: text(rule.label),
|
|
value: text(rule.value),
|
|
realCondition: text(rule.realCondition),
|
|
condition: text(rule.condition),
|
|
format: text(rule.format),
|
|
array: text(rule.array),
|
|
rest,
|
|
});
|
|
}
|
|
return { values, otherwise };
|
|
}
|
|
|
|
/** Legacy saveVariable body: rules keyed "1".."n" in row order, then ELSE unless Missing. */
|
|
export function writeVariableInfo(
|
|
values: DerivedValue[],
|
|
otherwise: DerivedElse,
|
|
): Record<string, Record<string, unknown>> {
|
|
const info: Record<string, Record<string, unknown>> = {};
|
|
values.forEach((row, index) => {
|
|
info[String(index + 1)] = {
|
|
label: row.label.trim(),
|
|
value: row.value.trim(),
|
|
realCondition: row.realCondition.trim(),
|
|
condition: row.condition.trim(),
|
|
format: row.format,
|
|
array: row.array,
|
|
...row.rest,
|
|
};
|
|
});
|
|
if (!otherwise.isMissing)
|
|
info.ELSE = {
|
|
label: otherwise.label.trim(),
|
|
value: otherwise.value.trim(),
|
|
realCondition: "ELSE",
|
|
condition: "ELSE",
|
|
array: "ELSE",
|
|
};
|
|
return info;
|
|
}
|
|
|
|
/** Legacy saveVariable checks and messages, in the same order. Null when the form can be saved. */
|
|
export function derivedFormError(form: {
|
|
variableId: string;
|
|
title: string;
|
|
type: DerivedType;
|
|
info: Record<string, Record<string, unknown>>;
|
|
}): string | null {
|
|
if (form.variableId.trim() === "") return "ID는 필수 입니다.";
|
|
if (form.title.trim() === "") return "Title은 필수 입니다.";
|
|
const rules = Object.values(form.info);
|
|
if (rules.length === 0) return "1개 이상의 값을 지정해 주세요";
|
|
const values: unknown[] = [];
|
|
const labels: unknown[] = [];
|
|
for (const rule of rules) {
|
|
if (rule.condition === "") return "Condition은 필수 입니다.";
|
|
if (rule.value === "") return "Value는 필수 입니다.";
|
|
// Numeric variables have no label input, so only labelled types require one.
|
|
if (form.type !== "num" && rule.label === "") return "Label은 필수 입니다.";
|
|
if (values.includes(rule.value)) return "Value에 중복이 있습니다.";
|
|
if (form.type !== "num" && labels.includes(rule.label)) return "Label에 중복이 있습니다.";
|
|
values.push(rule.value);
|
|
labels.push(rule.label);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Body of `POST .../derived` and `PUT .../derived/{variableId}`. */
|
|
export type DerivedSaveRequest = {
|
|
variableId: string;
|
|
variableTitle: string;
|
|
variableType: DerivedType;
|
|
variableInfo: Record<string, Record<string, unknown>>;
|
|
};
|
|
|
|
export const DERIVED_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,127}$/;
|
|
|
|
/** Mirrors the server DTO constraints so the BFF forwards only well-formed requests. */
|
|
export function readDerivedSaveRequest(value: unknown): DerivedSaveRequest {
|
|
const invalid = () => new Error("파생변수 저장 내용을 확인해 주세요.");
|
|
if (
|
|
!isRecord(value) ||
|
|
typeof value.variableId !== "string" ||
|
|
!DERIVED_ID_PATTERN.test(value.variableId) ||
|
|
typeof value.variableTitle !== "string" ||
|
|
value.variableTitle.trim() === "" ||
|
|
value.variableTitle.length > 4000 ||
|
|
!isDerivedType(value.variableType) ||
|
|
!isRecord(value.variableInfo)
|
|
)
|
|
throw invalid();
|
|
const entries = Object.entries(value.variableInfo);
|
|
if (entries.length === 0 || entries.length > 1000) throw invalid();
|
|
const variableInfo: Record<string, Record<string, unknown>> = {};
|
|
for (const [key, rule] of entries) {
|
|
if (!(key === "ELSE" || /^\d+$/.test(key)) || !isRecord(rule)) throw invalid();
|
|
variableInfo[key] = rule;
|
|
}
|
|
return {
|
|
variableId: value.variableId,
|
|
variableTitle: value.variableTitle,
|
|
variableType: value.variableType,
|
|
variableInfo,
|
|
};
|
|
}
|