Files
co-lite/solvway-admin-portal/app/messages/MessageEditSheet.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

209 lines
7.8 KiB
TypeScript

"use client";
import { useState, type FormEvent } from "react";
import { Copy } from "lucide-react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/app/components/ui/sheet";
import { Textarea } from "@/app/components/ui/textarea";
import { ErrorState } from "@/app/components/ui/states";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { useLocales } from "@/app/lib/i18n/LocalesProvider";
import { AREA_OPTIONS, areaLabel, createMessage, updateMessage } from "@/app/lib/services/messages";
import { buildContentBlob } from "@/app/lib/messageContent";
import { placeholderMismatch } from "@/app/lib/messagePlaceholders";
import type { MessageArea } from "@/app/lib/types";
export interface FormState {
id?: number;
code: string;
description: string;
area: MessageArea;
perLocale: Record<string, string>;
}
const list = (xs: string[]) => (xs.length ? xs.join(", ") : "—");
export function MessageEditSheet({
mode,
initial,
onClose,
onSaved,
}: {
mode: "add" | "edit";
initial: FormState;
onClose: () => void;
onSaved: () => void;
}) {
const t = useT();
const locales = useLocales();
const [form, setForm] = useState<FormState>(initial);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const ordered = [...locales].sort((a, b) => Number(b.code === "en_US") - Number(a.code === "en_US"));
const dirty = JSON.stringify(form) !== JSON.stringify(initial);
// Per non-English locale: mismatch vs English now, and whether it was already mismatched on open.
const checks = ordered
.filter((l) => l.code !== "en_US" && (form.perLocale[l.code] ?? "").trim())
.map((l) => {
const now = placeholderMismatch(form.perLocale.en_US ?? "", form.perLocale[l.code] ?? "");
const before = placeholderMismatch(initial.perLocale.en_US ?? "", initial.perLocale[l.code] ?? "");
return {
locale: l,
now,
wasMismatched: before.missing.length + before.extra.length > 0,
mismatched: now.missing.length + now.extra.length > 0,
};
});
const blocked = checks.some((c) => c.mismatched && !c.wasMismatched);
function requestClose() {
if (dirty) setConfirmOpen(true);
else onClose();
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSaving(true);
setError(null);
try {
const payload = {
// Edit mode: code/area are locked server-side and live rows can carry stray whitespace, so send them as stored.
code: mode === "edit" ? initial.code : form.code.trim(),
description: form.description.trim() || undefined,
area: mode === "edit" ? initial.area : form.area,
content: buildContentBlob(form.perLocale, locales),
};
if (form.id != null) await updateMessage(form.id, payload);
else await createMessage(payload);
onSaved();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : "MsgsSaveFailed");
} finally {
setSaving(false);
}
}
return (
<>
<Sheet open onOpenChange={(open) => !open && requestClose()}>
<SheetContent side="right">
<SheetHeader>
<SheetTitle>{mode === "add" ? t("AddMessage") : t("EditMessage")}</SheetTitle>
</SheetHeader>
{error && <ErrorState message={t(error)} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{mode === "edit" ? (
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline">{areaLabel(form.area, t)}</Badge>
<code className="font-mono text-sm">{form.code}</code>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t("MsgsCopyCode")}
onClick={() => navigator.clipboard.writeText(form.code)}
>
<Copy aria-hidden="true" className="size-4" />
</Button>
</div>
) : (
<>
<div className="space-y-1.5">
<Label htmlFor="message-code">{t("Code")}</Label>
<Input
id="message-code"
value={form.code}
onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))}
disabled={saving}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="message-area">{t("Area")}</Label>
<Select
value={form.area}
onValueChange={(value) => setForm((f) => ({ ...f, area: value as MessageArea }))}
>
<SelectTrigger id="message-area" aria-label={t("Area")} className="h-9 w-[180px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{AREA_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label && t(opt.label)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</>
)}
<div className="space-y-1.5">
<Label htmlFor="message-description">{t("MsgsNote")}</Label>
<Input
id="message-description"
value={form.description}
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
disabled={saving}
/>
</div>
{ordered.map((locale) => {
const check = checks.find((c) => c.locale.code === locale.code);
return (
<div key={locale.code} className="space-y-1.5">
<Label htmlFor={`message-locale-${locale.code}`}>{locale.label}</Label>
<Textarea
id={`message-locale-${locale.code}`}
value={form.perLocale[locale.code] ?? ""}
onChange={(e) =>
setForm((f) => ({ ...f, perLocale: { ...f.perLocale, [locale.code]: e.target.value } }))
}
disabled={saving}
/>
{check?.mismatched && (
<p className="text-sm text-warning" role="alert">
{t(check.wasMismatched ? "MsgsPlaceholderAlreadyDifferent" : "MsgsPlaceholderMismatch", {
missing: list(check.now.missing),
extra: list(check.now.extra),
})}
</p>
)}
</div>
);
})}
<div className="flex gap-2">
<Button type="submit" disabled={saving || blocked || (mode === "add" && !form.code.trim())}>
{t("Save")}
</Button>
<Button type="button" variant="outline" onClick={requestClose}>
{t("Cancel")}
</Button>
</div>
</form>
</SheetContent>
</Sheet>
<ConfirmDialog
open={confirmOpen}
onOpenChange={setConfirmOpen}
title={t("MsgsDiscardTitle")}
description={t("MsgsDiscardBody")}
confirmLabel={t("MsgsDiscardConfirm")}
onConfirm={onClose}
/>
</>
);
}