도메인별 스키마(company·place·fact·local·site·job)를 걷어내고 public 한 벌로 폈다.
스키마 한정자가 붙은 순간부터 ORM·raw SQL·테스트 픽스처가 각자 그 이름을 들고 다녀야 했다.
- 공용 콘텐츠를 한 테이블로 되돌린다. spots·region_stories 를 따로 파 놓고 보니
같은 성격이 세 곳으로 갈라져 있었다 — `area_contents` 가 처음부터 content_type 으로
종류를 가르는 설계였고 그걸 쓰면 됐다. 관계(거리·숨김)만 `place_area_refs` 로 남긴다.
- migrations/ + scripts/migrate.py: `init.sql` 은 **DB 를 처음 만들 때만** 돈다. 파일에
컬럼을 더해도 이미 데이터가 든 DB 에는 반영되지 않는다 — 실제로 TourAPI 가 주변 정보를
받아 와도 저장할 곳이 없어 축제·맛집이 0건이었고, 화면에는 "그냥 안 나오는 것" 으로만 보였다.
DECISIONS.md 가 예고한 그대로다("운영 DB 가 생기는 순간 다시 필요해진다").
Alembic 을 쓰지 않는 이유는 스키마 정의가 이미 두 곳(ORM·init.sql)이라 세 번째를
더하면 어긋날 자리가 하나 더 생기기 때문이다.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
276 lines
10 KiB
TypeScript
276 lines
10 KiB
TypeScript
/**
|
|
* 붙여넣기 아이템의 **직접 입력** 폼.
|
|
*
|
|
* ★ 왜 만들었나
|
|
* 입구가 JSON 붙여넣기 하나뿐이었다. 한 글자만 고치려 해도 사장님이 중괄호와 쉼표를
|
|
* 헤집어야 했고, 쉼표 하나 잘못 지우면 섹션이 통째로 사라졌다. ChatGPT 를 안 쓰는
|
|
* 사장님은 아예 채울 수가 없었다.
|
|
*
|
|
* ★ 폼과 JSON 은 한 값의 두 얼굴이다
|
|
* 진실은 `section.data` **문자열 하나**뿐이고 이 폼은 그걸 비춘다. 그래서
|
|
* JSON 을 붙여넣으면 폼이 따라 바뀌고, 폼을 고치면 JSON 이 다시 쓰인다 —
|
|
* 어느 쪽이 최신인지 물을 일이 없다. 폼 상태를 따로 들고 있으면 그 순간
|
|
* "화면은 새 값, 저장은 옛 값"이 생긴다.
|
|
*
|
|
* ★ 깨진 JSON 은 폼으로 못 편다. 그때는 폼을 감추고 오류만 남긴다 —
|
|
* 반쯤 읽힌 값으로 폼을 그리면 사장님이 쓴 걸 덮어쓴다.
|
|
*/
|
|
import {Plus, Trash2} from 'lucide-react';
|
|
import {parseSectionData} from '@o2o/shared';
|
|
import {Button} from '@/components/ui/button';
|
|
import {Input} from '@/components/ui/input';
|
|
import {cn} from '@/lib/utils';
|
|
import type {ItemField, SectionDataSpec} from './canvas/dataSpec';
|
|
|
|
type Row = Record<string, unknown>;
|
|
|
|
/** 'source.name' 처럼 점이 있는 키를 읽는다. */
|
|
function readAt(row: Row, key: string): unknown {
|
|
return key.split('.').reduce<unknown>((node, part) => {
|
|
if (node === null || typeof node !== 'object') return undefined;
|
|
return (node as Row)[part];
|
|
}, row);
|
|
}
|
|
|
|
/** 값을 쓴다. 빈 값이면 **키를 지운다** — 빈 문자열을 남기면 "확인 안 된 값"이 발행본에 나간다. */
|
|
function writeAt(row: Row, key: string, value: unknown): Row {
|
|
const [head, ...rest] = key.split('.');
|
|
const next = {...row};
|
|
if (rest.length === 0) {
|
|
if (value === undefined || value === '' || (Array.isArray(value) && value.length === 0)) {
|
|
delete next[head];
|
|
} else {
|
|
next[head] = value;
|
|
}
|
|
return next;
|
|
}
|
|
const child = (typeof next[head] === 'object' && next[head] !== null ? next[head] : {}) as Row;
|
|
const written = writeAt(child, rest.join('.'), value);
|
|
if (Object.keys(written).length === 0) delete next[head];
|
|
else next[head] = written;
|
|
return next;
|
|
}
|
|
|
|
function toInput(field: ItemField, value: unknown): string {
|
|
if (value === undefined || value === null) return '';
|
|
if (field.type === 'tags') return Array.isArray(value) ? value.join(', ') : String(value);
|
|
if (field.key === 'turning') return value === true ? '예' : value === false ? '아니오' : '';
|
|
return String(value);
|
|
}
|
|
|
|
function fromInput(field: ItemField, text: string): unknown {
|
|
const trimmed = text.trim();
|
|
if (trimmed === '') return undefined;
|
|
if (field.type === 'tags') return trimmed.split(',').map((t) => t.trim()).filter(Boolean);
|
|
if (field.type === 'number') {
|
|
const n = Number(trimmed.replace(/[^0-9.-]/g, ''));
|
|
return Number.isFinite(n) ? n : undefined;
|
|
}
|
|
if (field.key === 'turning') return trimmed === '예' ? true : trimmed === '아니오' ? false : undefined;
|
|
return text;
|
|
}
|
|
|
|
function Field({
|
|
field,
|
|
row,
|
|
onChange,
|
|
}: {
|
|
field: ItemField;
|
|
row: Row;
|
|
onChange: (key: string, value: unknown) => void;
|
|
}) {
|
|
const value = toInput(field, readAt(row, field.key));
|
|
const set = (text: string) => onChange(field.key, fromInput(field, text));
|
|
|
|
return (
|
|
<label className={cn('block space-y-1', field.half ? 'sm:col-span-1' : 'col-span-2')}>
|
|
<span className="text-[10px] font-semibold text-muted-foreground">{field.label}</span>
|
|
{field.options ? (
|
|
<select
|
|
value={value}
|
|
onChange={(event) => set(event.target.value)}
|
|
className="h-8 w-full rounded-md border border-input bg-background px-2 text-[11px] outline-none focus:border-ring"
|
|
>
|
|
<option value="">—</option>
|
|
{field.options.map((option) => (
|
|
<option key={option} value={option}>
|
|
{option}
|
|
</option>
|
|
))}
|
|
</select>
|
|
) : field.type === 'area' ? (
|
|
<textarea
|
|
value={value}
|
|
onChange={(event) => set(event.target.value)}
|
|
rows={2}
|
|
className="w-full resize-y rounded-md border border-input bg-background px-2 py-1.5 text-[11px] leading-relaxed outline-none focus:border-ring"
|
|
/>
|
|
) : field.type === 'color' ? (
|
|
<span className="flex items-center gap-1.5">
|
|
<input
|
|
type="color"
|
|
value={/^#[0-9a-f]{6}$/i.test(value) ? value : '#888888'}
|
|
onChange={(event) => set(event.target.value)}
|
|
className="h-8 w-9 shrink-0 cursor-pointer rounded border border-input bg-background"
|
|
aria-label={field.label}
|
|
/>
|
|
<Input value={value} onChange={(event) => set(event.target.value)} className="h-8 text-[11px]" />
|
|
</span>
|
|
) : (
|
|
<Input
|
|
value={value}
|
|
inputMode={field.type === 'number' ? 'numeric' : undefined}
|
|
onChange={(event) => set(event.target.value)}
|
|
className="h-8 text-[11px]"
|
|
/>
|
|
)}
|
|
{field.hint && <span className="block text-[10px] text-muted-foreground">{field.hint}</span>}
|
|
</label>
|
|
);
|
|
}
|
|
|
|
export function ItemFormEditor({
|
|
spec,
|
|
raw,
|
|
onChange,
|
|
}: {
|
|
spec: SectionDataSpec;
|
|
raw: string;
|
|
onChange: (next: string) => void;
|
|
}) {
|
|
const parsed = parseSectionData<Row>(spec.kind, raw);
|
|
|
|
// 깨진 JSON 위에 폼을 그리지 않는다 — 반쯤 읽힌 값으로 덮어쓰면 사장님이 쓴 걸 잃는다.
|
|
if (parsed.error) return null;
|
|
|
|
const envelope = (() => {
|
|
try {
|
|
const value = JSON.parse(raw || '{}') as Record<string, unknown>;
|
|
return typeof value === 'object' && value !== null ? value : {};
|
|
} catch {
|
|
return {};
|
|
}
|
|
})();
|
|
|
|
const items = Array.isArray(envelope.items) ? (envelope.items as Row[]) : [];
|
|
|
|
/** 항목 배열을 다시 JSON 문자열로. 봉투(kind·title·subtitle)는 그대로 둔다. */
|
|
const commit = (next: Row[]) =>
|
|
onChange(JSON.stringify({...envelope, kind: spec.kind, items: next}, null, 2));
|
|
|
|
const patch = (index: number, key: string, value: unknown) =>
|
|
commit(items.map((row, i) => (i === index ? writeAt(row, key, value) : row)));
|
|
|
|
const patchChild = (index: number, childIndex: number, key: string, value: unknown) => {
|
|
const childKey = spec.child!.key;
|
|
commit(
|
|
items.map((row, i) => {
|
|
if (i !== index) return row;
|
|
const list = Array.isArray(row[childKey]) ? ([...(row[childKey] as Row[])]) : [];
|
|
list[childIndex] = writeAt(list[childIndex] ?? {}, key, value);
|
|
return {...row, [childKey]: list};
|
|
}),
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-2">
|
|
{items.map((row, index) => (
|
|
<div key={index} className="space-y-2 rounded-md border border-border bg-background p-2.5">
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-[10px] font-bold text-muted-foreground">
|
|
{spec.label} {index + 1}
|
|
</span>
|
|
<button
|
|
type="button"
|
|
onClick={() => commit(items.filter((_, i) => i !== index))}
|
|
className="flex size-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-destructive"
|
|
aria-label={`${index + 1}번째 지우기`}
|
|
>
|
|
<Trash2 className="size-3" />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-2">
|
|
{spec.fields.map((field) => (
|
|
<Field
|
|
key={field.key}
|
|
field={field}
|
|
row={row}
|
|
onChange={(key, value) => patch(index, key, value)}
|
|
/>
|
|
))}
|
|
</div>
|
|
|
|
{spec.child && (
|
|
<div className="space-y-1.5 border-t border-border pt-2">
|
|
<span className="text-[10px] font-bold text-muted-foreground">
|
|
{spec.child.label}
|
|
</span>
|
|
{(Array.isArray(row[spec.child.key]) ? (row[spec.child.key] as Row[]) : []).map(
|
|
(child, childIndex) => (
|
|
<div key={childIndex} className="rounded border border-border/70 bg-muted/30 p-2">
|
|
<div className="mb-1 flex items-center justify-between">
|
|
<span className="text-[10px] text-muted-foreground">{childIndex + 1}</span>
|
|
<button
|
|
type="button"
|
|
onClick={() =>
|
|
patch(
|
|
index,
|
|
spec.child!.key,
|
|
(row[spec.child!.key] as Row[]).filter((_, i) => i !== childIndex),
|
|
)
|
|
}
|
|
className="flex size-5 items-center justify-center rounded text-muted-foreground hover:text-destructive"
|
|
aria-label={`${spec.child!.label} ${childIndex + 1} 지우기`}
|
|
>
|
|
<Trash2 className="size-3" />
|
|
</button>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-2">
|
|
{spec.child!.fields.map((field) => (
|
|
<Field
|
|
key={field.key}
|
|
field={field}
|
|
row={child}
|
|
onChange={(key, value) => patchChild(index, childIndex, key, value)}
|
|
/>
|
|
))}
|
|
</div>
|
|
</div>
|
|
),
|
|
)}
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
variant="outline"
|
|
className="h-7 w-full gap-1 text-[10px]"
|
|
onClick={() =>
|
|
patch(index, spec.child!.key, [
|
|
...(Array.isArray(row[spec.child!.key]) ? (row[spec.child!.key] as Row[]) : []),
|
|
{},
|
|
])
|
|
}
|
|
>
|
|
<Plus className="size-3" />
|
|
{spec.child.label} 추가
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
))}
|
|
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
variant="outline"
|
|
className="h-8 w-full gap-1 text-[11px]"
|
|
onClick={() => commit([...items, {}])}
|
|
>
|
|
<Plus className="size-3.5" />
|
|
{spec.label} 추가
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|