Merge remote-tracking branch 'origin/dev' into sub_laptop_4
This commit is contained in:
@@ -9,6 +9,7 @@ import { currentLanguageIndex } from "@ui/ui_template_locale";
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
import { fetchLogics } from "../../M01_MasterData/M01_MasterData_UI_Logic_Api";
|
||||
import type { CfAnswer, CfQuery } from "./M02_DF_Api";
|
||||
import { fillTemplate } from "./M02_DF_InputPanel_Build";
|
||||
import type { CfBreak, CfValues } from "./M02_DF_Eval";
|
||||
import type { CfElementRef, CfLogic, CfPort } from "./M02_DF_Model";
|
||||
|
||||
@@ -190,7 +191,12 @@ export function queriesOf(
|
||||
unit: e.unit,
|
||||
slot: { ...e, field: e.rule?.field, op: e.rule?.op },
|
||||
};
|
||||
if (e.mode === "rule" && e.rule) q.value = pill(e.rule.from);
|
||||
// 조건 찾기 — 「검색어」 면 틀에 알약 값을 채운 글 · 그 밖은 이어진 알약 값
|
||||
if (e.mode === "rule" && e.rule)
|
||||
q.value =
|
||||
e.rule.field === "검색어"
|
||||
? fillTemplate(e.rule.template ?? "", e.rule.slots ?? [], pill).text
|
||||
: pill(e.rule.from);
|
||||
return { q, box: b.id, port };
|
||||
});
|
||||
const els = inp.elements
|
||||
|
||||
@@ -231,6 +231,16 @@ export function materialElement(
|
||||
export function checkMaterial(el: CfElementRef, others: CfElementRef[]): string | null {
|
||||
if (!el.name) return "자리 이름을 적어 주세요";
|
||||
if (others.some((o) => o.name === el.name)) return "같은 이름의 알약이 이미 있음";
|
||||
if (el.mode === "rule" && el.rule?.field === "검색어") {
|
||||
if (!el.rule.template?.trim() || !templateSlots(el.rule.template).length)
|
||||
return "검색어 틀에 자리 {이름} 이 하나는 있어야 함";
|
||||
if (
|
||||
(el.rule.slots ?? []).length < templateSlots(el.rule.template).length ||
|
||||
(el.rule.slots ?? []).some((x) => !x.from.name)
|
||||
)
|
||||
return "틀의 자리마다 변수 알약을 골라 주세요";
|
||||
return null;
|
||||
}
|
||||
if (el.mode === "rule" && !el.rule?.from.name) return "규칙에 쓸 변수 알약을 골라 주세요";
|
||||
if (
|
||||
el.mode !== "fixed" &&
|
||||
@@ -626,3 +636,46 @@ export function checkGroupRule(el: CfElementRef, others: CfElementRef[]): string
|
||||
if (!el.rule?.from.name) return "규칙에 쓸 변수 알약을 골라 주세요";
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ── 재료 조건 찾기 field 「검색어」 — 틀(「레미콘 {굵은골재최대치수}-{강도}-{슬럼프}」) 의 자리마다 변수 알약 값을 끼운 글로 찾음 ── */
|
||||
|
||||
/** 틀 안 자리 이름들 — 나온 차례 · 겹침 없이 */
|
||||
export function templateSlots(template: string): string[] {
|
||||
return [
|
||||
...new Set([...template.matchAll(/\{([^{}]+)\}/g)].map((m) => m[1].trim()).filter(Boolean)),
|
||||
];
|
||||
}
|
||||
|
||||
/** 틀을 채운 글 — valueOf 가 알약 값을 줌 · 값이 빈 자리는 missing 에 모음(그 자리는 그대로 둠) */
|
||||
export function fillTemplate(
|
||||
template: string,
|
||||
slots: { name: string; from: CfPort }[],
|
||||
valueOf: (port: CfPort) => unknown,
|
||||
): { text: string; missing: string[] } {
|
||||
const missing: string[] = [];
|
||||
const text = template.replace(/\{([^{}]+)\}/g, (all, raw: string) => {
|
||||
const name = raw.trim();
|
||||
const slot = slots.find((x) => x.name === name);
|
||||
const v = slot ? valueOf(slot.from) : undefined;
|
||||
if (v === null || v === undefined || v === "") {
|
||||
if (!missing.includes(name)) missing.push(name);
|
||||
return all;
|
||||
}
|
||||
return String(v);
|
||||
});
|
||||
return { text, missing };
|
||||
}
|
||||
|
||||
/** 검색어 틀 규칙 — 첫 자리의 알약이 from(옛 Model 호환) */
|
||||
export function templateRule(
|
||||
template: string,
|
||||
slots: { name: string; from: CfPort }[],
|
||||
): CfMaterialRule {
|
||||
return {
|
||||
field: "검색어",
|
||||
op: "포함",
|
||||
from: slots[0]?.from ?? { box: "", name: "" },
|
||||
template,
|
||||
slots,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -15,9 +15,12 @@ import {
|
||||
} from "@ui/ui_template_elements";
|
||||
import { fetchFiles, fetchSubs, type SubInfo } from "../../M01_MasterData/M01_MasterData_Api_Fetch";
|
||||
import { cfMaterials, cfValues } from "./M02_DF_Api";
|
||||
import { templateBox } from "./M02_DF_InputPanel_Template";
|
||||
import type { CfElementRef, CfLogic, CfMaterialMode, CfMaterialRule } from "./M02_DF_Model";
|
||||
import {
|
||||
catchNote,
|
||||
fillTemplate,
|
||||
templateRule,
|
||||
checkMaterial,
|
||||
elementOf,
|
||||
matches,
|
||||
@@ -59,6 +62,11 @@ const TEXT = {
|
||||
Default: ["기본 품목", "Default item"],
|
||||
DefaultNone: ["아직 안 고름 — 아래 목록에서 눌러 고름", "Not chosen — pick one below"],
|
||||
DefaultClear: ["기본 품목 비움", "Clear"],
|
||||
RuleHow: ["찾는 방식", "How to find"],
|
||||
HowPlain: ["규격 · 이름에 알약 값", "Spec / name vs a pill"],
|
||||
HowTemplate: ["검색어 틀", "Search template"],
|
||||
TemplateLine: ["검색어 틀 「{t}」", "template “{t}”"],
|
||||
Missing: ["자리 「{n}」 알약 값이 비어 있음", "Slot “{n}” has no value"],
|
||||
RuleField: ["찾는 칸", "Field"],
|
||||
FieldSpec: ["규격", "Spec"],
|
||||
FieldName: ["이름", "Name"],
|
||||
@@ -251,9 +259,35 @@ function itemList(
|
||||
export async function previewOf(
|
||||
el1: CfElementRef,
|
||||
lg: CfLogic,
|
||||
): Promise<{ found: number; names: string[]; cheapest: MatItem | null; unit: string }> {
|
||||
): Promise<{
|
||||
found: number;
|
||||
names: string[];
|
||||
cheapest: MatItem | null;
|
||||
unit: string;
|
||||
missing?: string[];
|
||||
}> {
|
||||
const scope = el1.scope ?? {};
|
||||
const word = scope.찾는말 ?? "";
|
||||
if (el1.mode === "rule" && el1.rule?.field === "검색어") {
|
||||
// 틀의 자리마다 알약 값을 끼운 글로 찾음(띄어쓴 말은 모두 들어간 것)
|
||||
const valueOf = (port: { box: string; name: string }): unknown =>
|
||||
variablePills(lg).find((p) => p.port.box === port.box && p.port.name === port.name)?.example;
|
||||
const { text, missing } = fillTemplate(el1.rule.template ?? "", el1.rule.slots ?? [], valueOf);
|
||||
if (missing.length) return { found: 0, names: [], cheapest: null, unit: "", missing };
|
||||
const r = await searchMaterials({
|
||||
q: `${word} ${text}`.trim(),
|
||||
sub: scope.구분,
|
||||
detail: scope.상세구분,
|
||||
page: 1,
|
||||
size: 200,
|
||||
});
|
||||
return {
|
||||
found: r.total,
|
||||
names: r.items.slice(0, 3).map((i) => `${i.name} ${i.spec}`.trim()),
|
||||
cheapest: cheapestOf(r.items),
|
||||
unit: commonUnit(r.items),
|
||||
};
|
||||
}
|
||||
if (el1.mode === "rule" && el1.rule) {
|
||||
const pill = variablePills(lg).find(
|
||||
(p) => p.port.box === el1.rule!.from.box && p.port.name === el1.rule!.from.name,
|
||||
@@ -300,6 +334,16 @@ const cheapestOf = (items: MatItem[]): MatItem | null =>
|
||||
.filter((i) => i.price !== null)
|
||||
.sort((a, b) => (a.price as number) - (b.price as number))[0] ?? null;
|
||||
|
||||
/** 미리 보기 글 — 틀 자리 값이 비면 그 까닭 · 아니면 잡힌 수에 따른 알림 */
|
||||
const noteOf = (p: {
|
||||
found: number;
|
||||
names: string[];
|
||||
missing?: string[];
|
||||
}): ReturnType<typeof catchNote> =>
|
||||
p.missing?.length
|
||||
? { kind: "none", text: t("Missing", { n: p.missing.join(" · ") }) }
|
||||
: catchNote(p.found, p.names[0]);
|
||||
|
||||
/** 요소 한 줄 요약 — 방식 · 범위 · 규칙 */
|
||||
function summaryOf(e: CfElementRef, lg: CfLogic): string {
|
||||
const parts: string[] = [];
|
||||
@@ -307,7 +351,8 @@ function summaryOf(e: CfElementRef, lg: CfLogic): string {
|
||||
.map(([, v]) => v)
|
||||
.join(" / ");
|
||||
if (scope) parts.push(t("ScopeLine", { s: scope }));
|
||||
if (e.rule) {
|
||||
if (e.rule?.field === "검색어") parts.push(t("TemplateLine", { t: e.rule.template ?? "" }));
|
||||
else if (e.rule) {
|
||||
const p = variablePills(lg).find(
|
||||
(x) => x.port.box === e.rule!.from.box && x.port.name === e.rule!.from.name,
|
||||
);
|
||||
@@ -336,6 +381,7 @@ export function renderMaterial(
|
||||
const chosen = el("div", { className: "m02-dfip__chosen" });
|
||||
const body = el("div", { className: "m02-dfip__stack" });
|
||||
let mode: CfMaterialMode = "fixed";
|
||||
let how: "plain" | "template" = "plain";
|
||||
|
||||
const drawChosen = (): void => {
|
||||
chosen.replaceChildren(
|
||||
@@ -380,7 +426,7 @@ export function renderMaterial(
|
||||
if (e.mode && e.mode !== "fixed")
|
||||
void previewOf(e, lg).then(
|
||||
(p) => {
|
||||
const n = catchNote(p.found, p.names[0]);
|
||||
const n = noteOf(p);
|
||||
note.textContent = `${t("Preview")}: ${n.text}`;
|
||||
note.classList.toggle("is-bad", n.kind !== "one");
|
||||
if (p.cheapest?.price != null && !ref) val.textContent = fmt(p.cheapest.price);
|
||||
@@ -463,9 +509,30 @@ export function renderMaterial(
|
||||
compact: true,
|
||||
onChange: () => void refresh(),
|
||||
});
|
||||
const howBox = createSelectField({
|
||||
label: t("RuleHow"),
|
||||
options: [
|
||||
{ value: "plain", text: t("HowPlain") },
|
||||
{ value: "template", text: t("HowTemplate") },
|
||||
],
|
||||
value: how,
|
||||
compact: true,
|
||||
onChange: (v) => ((how = v as "plain" | "template"), drawBody()),
|
||||
});
|
||||
const tpl = templateBox(lg, () => void refresh());
|
||||
const defNote = el("p", { className: "m02-dfip__muted" });
|
||||
const build = (): CfElementRef => {
|
||||
const sc = scope.get();
|
||||
if (mode === "rule" && howBox.select.value === "template") {
|
||||
const g = tpl.get();
|
||||
const sc2 = scope.get();
|
||||
return materialElement(
|
||||
mode,
|
||||
name.input.value,
|
||||
{ 구분: sc2.sub, 상세구분: sc2.detail, 찾는말: word.input.value.trim() },
|
||||
{ rule: templateRule(g.template, g.slots) },
|
||||
);
|
||||
}
|
||||
const rule: CfMaterialRule | undefined =
|
||||
mode === "rule" && pills[Number(pillBox.select.value)]
|
||||
? {
|
||||
@@ -490,7 +557,7 @@ export function renderMaterial(
|
||||
try {
|
||||
const p = await previewOf(cand, lg);
|
||||
if (mine !== seq) return;
|
||||
const n = catchNote(p.found, p.names[0]);
|
||||
const n = noteOf(p);
|
||||
note.textContent = `${t("Preview")}: ${n.text}${p.cheapest?.price != null ? ` · ${t("Price", { p: fmt(p.cheapest.price), u: p.cheapest.unit })}` : ""}`;
|
||||
note.className = `m02-dfip__note${n.kind === "one" ? "" : " is-bad"}`;
|
||||
} catch {
|
||||
@@ -530,9 +597,14 @@ export function renderMaterial(
|
||||
scope.root,
|
||||
word.root,
|
||||
...(mode === "rule"
|
||||
? pills.length
|
||||
? [fieldBox.root, opBox.root, pillBox.root]
|
||||
: [el("p", { className: "m02-dfip__muted is-bad", text: t("NoPill") })]
|
||||
? [
|
||||
howBox.root,
|
||||
...(howBox.select.value === "template"
|
||||
? [tpl.root]
|
||||
: pills.length
|
||||
? [fieldBox.root, opBox.root, pillBox.root]
|
||||
: [el("p", { className: "m02-dfip__muted is-bad", text: t("NoPill") })]),
|
||||
]
|
||||
: [
|
||||
el("h5", { text: t("Default") }),
|
||||
defNote,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/* =============================================================================
|
||||
* M02_DF_InputPanel_Template.ts
|
||||
* 입력 판 — 재료 조건 찾기 「검색어 틀」: 틀(예: 「레미콘 {굵은골재최대치수}-{강도}-{슬럼프}」) 입력 · 틀 자리 {이름} 마다
|
||||
* 값을 줄 변수 알약 고르기 · 글 [한, 영] 짝은 아래 · 재료 판(`M02_DF_InputPanel_Material.ts`)이 부름
|
||||
* ========================================================================== */
|
||||
|
||||
import { currentLanguageIndex } from "@ui/ui_template_locale";
|
||||
import { createInputField, createSelectField, el } from "@ui/ui_template_elements";
|
||||
import type { CfLogic, CfPort } from "./M02_DF_Model";
|
||||
import { templateSlots, variablePills } from "./M02_DF_InputPanel_Build";
|
||||
|
||||
const TEXT = {
|
||||
Template: ["검색어 틀 — 자리는 {이름} 으로", "Search template — slots as {name}"],
|
||||
Placeholder: ["예: 레미콘 {굵은골재최대치수}-{강도}-{슬럼프}", "e.g. Ready-mix {a}-{b}-{c}"],
|
||||
Help: [
|
||||
"틀의 자리마다 변수 알약을 고르면 그 값이 끼워진 글로 재료를 찾음(띄어쓴 말은 모두 들어간 것)",
|
||||
"Each slot takes a variable pill's value; words must all match",
|
||||
],
|
||||
Slot: ["자리 「{n}」 ← 알약", "Slot “{n}” ← pill"],
|
||||
NoSlot: ["틀에 자리 {이름} 을 넣어 주세요", "Add a {slot} to the template"],
|
||||
NoPill: ["변수 알약이 없음 — 변수 입력 상자를 먼저 만듦", "No variable pill yet"],
|
||||
} as const;
|
||||
|
||||
type TKey = keyof typeof TEXT;
|
||||
const t = (key: TKey, v: Record<string, string> = {}): string =>
|
||||
Object.entries(v).reduce(
|
||||
(s, [k, x]) => s.replace(`{${k}}`, x),
|
||||
TEXT[key][currentLanguageIndex] as string,
|
||||
);
|
||||
|
||||
export interface TemplateBox {
|
||||
root: HTMLElement;
|
||||
/** 지금 틀 · 자리별 알약 — 틀이 비었으면 null */
|
||||
get(): { template: string; slots: { name: string; from: CfPort }[] };
|
||||
}
|
||||
|
||||
/** 틀 칸 + 자리 고르기 칸 — 바뀌면 onChange */
|
||||
export function templateBox(lg: CfLogic, onChange: () => void): TemplateBox {
|
||||
const pills = variablePills(lg);
|
||||
const tpl = createInputField({
|
||||
type: "text",
|
||||
label: t("Template"),
|
||||
compact: true,
|
||||
placeholder: t("Placeholder"),
|
||||
});
|
||||
const slotBox = el("div", { className: "m02-dfip__stack" });
|
||||
const picks = new Map<string, HTMLSelectElement>();
|
||||
const draw = (): void => {
|
||||
const names = templateSlots(tpl.input.value);
|
||||
const before = new Map([...picks].map(([k, s]) => [k, s.value]));
|
||||
picks.clear();
|
||||
slotBox.replaceChildren(
|
||||
...(names.length
|
||||
? pills.length
|
||||
? names.map((n) => {
|
||||
// 자리 이름과 같은 알약이 있으면 먼저 고름
|
||||
const same = pills.findIndex((p) => p.port.name === n);
|
||||
const sel = createSelectField({
|
||||
label: t("Slot", { n }),
|
||||
options: pills.map((p, i) => ({
|
||||
value: String(i),
|
||||
text: `${p.port.name}${p.example !== null ? ` = ${p.example}` : ""}`,
|
||||
})),
|
||||
value: before.get(n) ?? String(same >= 0 ? same : 0),
|
||||
compact: true,
|
||||
onChange: () => onChange(),
|
||||
});
|
||||
picks.set(n, sel.select);
|
||||
return sel.root;
|
||||
})
|
||||
: [el("p", { className: "m02-dfip__muted is-bad", text: t("NoPill") })]
|
||||
: [el("p", { className: "m02-dfip__muted", text: t("NoSlot") })]),
|
||||
);
|
||||
};
|
||||
tpl.input.addEventListener("input", () => (draw(), onChange()));
|
||||
draw();
|
||||
return {
|
||||
root: el("div", {
|
||||
className: "m02-dfip__stack",
|
||||
children: [el("p", { className: "m02-dfip__muted", text: t("Help") }), tpl.root, slotBox],
|
||||
}),
|
||||
get: () => ({
|
||||
template: tpl.input.value.trim(),
|
||||
slots: templateSlots(tpl.input.value).flatMap((n) => {
|
||||
const p = pills[Number(picks.get(n)?.value)];
|
||||
return p ? [{ name: n, from: p.port }] : [];
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -31,6 +31,9 @@ const m = box.exports;
|
||||
if (j.name === "wouldCycle") {
|
||||
const graph = j.args[2];
|
||||
out.push(await m.wouldCycle(j.args[0], j.args[1], async (k) => graph[k] ?? null));
|
||||
} else if (j.name === "fillTemplate") {
|
||||
const vals = j.args[2];
|
||||
out.push(m.fillTemplate(j.args[0], j.args[1], (p) => vals[`${p.box}.${p.name}`]));
|
||||
} else out.push(await m[j.name](...j.args));
|
||||
}
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
@@ -266,3 +269,38 @@ def test_옛_줄_입력과_자동값으로_다른_로직_입력을_읽음():
|
||||
{"name": "쌓기", "unit": "-"},
|
||||
]
|
||||
assert ref["examples"] == {"뒷길이": 25, "돌": "깬잡석"} # 빈 글 · 입력에 없는 이름은 뺌
|
||||
|
||||
|
||||
def test_검색어_틀_자리와_채움():
|
||||
tpl = "레미콘 {굵은골재최대치수}-{강도}-{슬럼프}"
|
||||
assert call("templateSlots", tpl) == ["굵은골재최대치수", "강도", "슬럼프"]
|
||||
assert call("templateSlots", "{a} {a} {b}") == ["a", "b"] # 겹친 자리는 한 번
|
||||
slots = [
|
||||
{"name": "굵은골재최대치수", "from": {"box": "b2", "name": "굵은"}},
|
||||
{"name": "강도", "from": {"box": "b2", "name": "강도"}},
|
||||
{"name": "슬럼프", "from": {"box": "b2", "name": "슬럼프"}},
|
||||
]
|
||||
values = {"b2.굵은": 25, "b2.강도": 18, "b2.슬럼프": 120}
|
||||
got = call("fillTemplate", tpl, slots, values)
|
||||
assert got == {"text": "레미콘 25-18-120", "missing": []}
|
||||
part = call("fillTemplate", tpl, slots, {"b2.굵은": 25, "b2.강도": ""})
|
||||
assert part["missing"] == ["강도", "슬럼프"]
|
||||
assert part["text"] == "레미콘 25-{강도}-{슬럼프}" # 빈 자리는 그대로 둠
|
||||
|
||||
|
||||
def test_검색어_틀_규칙과_검사():
|
||||
slots = [{"name": "a", "from": {"box": "b2", "name": "굵은"}}]
|
||||
rule = call("templateRule", "레미콘 {a}", slots)
|
||||
assert (
|
||||
rule["field"] == "검색어"
|
||||
and rule["template"] == "레미콘 {a}"
|
||||
and rule["from"] == slots[0]["from"]
|
||||
)
|
||||
el = call("materialElement", "rule", "콘크리트", {"구분": "레미콘"}, {"rule": rule})
|
||||
assert call("checkMaterial", el, []) is None
|
||||
no_slot = call("templateRule", "레미콘", [])
|
||||
bad = call("materialElement", "rule", "콘크리트", {"구분": "레미콘"}, {"rule": no_slot})
|
||||
assert "자리" in call("checkMaterial", bad, [])
|
||||
short = call("templateRule", "레미콘 {a}-{b}", slots) # 자리 둘인데 알약은 하나
|
||||
two = call("materialElement", "rule", "콘크리트", {}, {"rule": short})
|
||||
assert "알약" in call("checkMaterial", two, [])
|
||||
|
||||
Reference in New Issue
Block a user