Files
co-lite/solvway-admin-portal/app/notifications/page.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

405 lines
15 KiB
TypeScript

"use client";
import { useCallback, useState, type FormEvent, type KeyboardEvent } from "react";
import { CheckCircle2, X } from "lucide-react";
import { Alert, AlertDescription } from "@/app/components/ui/alert";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/app/components/ui/radio-group";
import { Label } from "@/app/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/app/components/ui/select";
import { PageHeader } from "@/app/components/ui/page-header";
import { ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { broadcast } from "@/app/lib/services/notifications";
import { listAdminUsers } from "@/app/lib/services/adminUsers";
import type {
BroadcastRequest,
NotificationTarget,
NotificationTargetKind,
} from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { isSitePath } from "@/app/lib/siteLink";
// `/notifications` compose page (Spec B §7.1): title, body, category, optional
// deep-link, and a target picker (Members / Admins / All Members / All Admins)
// with a pre-send recipient confirmation and a post-send result summary.
// Wrapped in RequireModule: without the BO_NOTIFICATIONS grant the page shows
// the not-authorised state. An empty message and an empty specific target are
// blocked client-side; the button is disabled while a send is pending.
const TYPE_OPTIONS: { value: string; label: string }[] = [
{ value: "points", label: "NotifTypePoints" },
{ value: "promo", label: "NotifTypePromo" },
{ value: "system", label: "NotifTypeSystem" },
];
const TARGET_TABS: { kind: NotificationTargetKind; label: string; hint: string }[] = [
{ kind: "MEMBERS", label: "NotifTargetMembers", hint: "NotifTargetMembersHint" },
{ kind: "ADMINS", label: "NotifTargetAdmins", hint: "NotifTargetAdminsHint" },
{ kind: "ALL_MEMBERS", label: "NotifTargetAllMembers", hint: "NotifTargetAllMembersHint" },
{ kind: "ALL_ADMINS", label: "NotifTargetAllAdmins", hint: "NotifTargetAllAdminsHint" },
];
type Stage = "form" | "confirm" | "done";
function NotificationsCompose() {
const t = useT();
const [title, setTitle] = useState("");
const [message, setMessage] = useState("");
const [type, setType] = useState("promo");
const [link, setLink] = useState("");
const [tab, setTab] = useState<NotificationTargetKind>("ALL_MEMBERS");
const [memberCodes, setMemberCodes] = useState<string[]>([]);
const [memberDraft, setMemberDraft] = useState("");
const [adminUsernames, setAdminUsernames] = useState<string[]>([]);
const [adminSearch, setAdminSearch] = useState("");
const [adminResults, setAdminResults] = useState<{ username: string }[]>([]);
const [stage, setStage] = useState<Stage>("form");
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
const [sentCount, setSentCount] = useState(0);
const [skippedCount, setSkippedCount] = useState(0);
const targetSummary = useCallback((): string => {
switch (tab) {
case "MEMBERS": {
const n = memberCodes.length;
return n === 1 ? t("NotifRecipientOne") : t("NotifRecipientMany", { count: n });
}
case "ADMINS": {
const n = adminUsernames.length;
return n === 1 ? t("NotifRecipientOne") : t("NotifRecipientMany", { count: n });
}
case "ALL_MEMBERS":
return t("NotifTargetAllMembers");
case "ALL_ADMINS":
return t("NotifTargetAllAdmins");
}
}, [t, tab, memberCodes.length, adminUsernames.length]);
function addMemberCode(raw: string) {
const value = raw.trim();
if (!value) return;
setMemberCodes((codes) => (codes.includes(value) ? codes : [...codes, value]));
setMemberDraft("");
}
function removeMemberCode(value: string) {
setMemberCodes((codes) => codes.filter((c) => c !== value));
}
function handleMemberKeyDown(event: KeyboardEvent<HTMLInputElement>) {
if (event.key === "Enter") {
event.preventDefault();
addMemberCode(memberDraft);
}
}
async function searchAdmins(search: string) {
setAdminSearch(search);
if (!search.trim()) {
setAdminResults([]);
return;
}
try {
const result = await listAdminUsers({ searchKey: search.trim(), page: 1, pageSize: 10 });
setAdminResults(result.items.map((u) => ({ username: u.username })));
} catch {
setAdminResults([]);
}
}
function toggleAdmin(username: string) {
setAdminUsernames((names) =>
names.includes(username) ? names.filter((n) => n !== username) : [...names, username],
);
}
function validate(): string | null {
if (!message.trim()) return "NotifMessageRequired";
if (tab === "MEMBERS" && memberCodes.length === 0) return "NotifRecipientRequired";
if (tab === "ADMINS" && adminUsernames.length === 0) return "NotifRecipientRequired";
if (link.trim() && !isSitePath(link.trim())) return "NotifDeepLinkSitePath";
return null;
}
function handleReview(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
const problem = validate();
if (problem) {
setError(problem);
return;
}
setStage("confirm");
}
function handleBack() {
setStage("form");
}
async function handleSend() {
setSending(true);
setError(null);
const target: NotificationTarget =
tab === "MEMBERS"
? { kind: tab, ids: memberCodes }
: tab === "ADMINS"
? { kind: tab, ids: adminUsernames }
: { kind: tab };
const payload: BroadcastRequest = {
title: title.trim() || undefined,
message: message.trim(),
type,
link: link.trim() || undefined,
target,
};
try {
const result = await broadcast(payload);
setSentCount(result.sent);
setSkippedCount(result.skipped ?? 0);
setStage("done");
} catch (err) {
setError(err instanceof Error ? err.message : "NotifSendFailed");
setStage("form");
} finally {
setSending(false);
}
}
function handleReset() {
setTitle("");
setMessage("");
setType("promo");
setLink("");
setMemberCodes([]);
setMemberDraft("");
setAdminUsernames([]);
setAdminSearch("");
setAdminResults([]);
setStage("form");
setError(null);
}
return (
<div className="space-y-4">
<PageHeader title={t("BO_NOTIFICATIONS")} />
{error && <ErrorState message={t(error)} />}
{stage === "done" ? (
<Alert>
<AlertDescription className="flex items-center gap-2">
<CheckCircle2 aria-hidden="true" className="size-4" />
{t("NotifSentTo", {
recipients: sentCount === 1 ? t("NotifRecipientOne") : t("NotifRecipientMany", { count: sentCount }),
})}
{skippedCount > 0 ? ` ${t("NotifSkipped", { count: skippedCount })}` : null}
</AlertDescription>
</Alert>
) : null}
{stage === "confirm" ? (
<div className="space-y-4 rounded-md border p-4" data-testid="confirmation">
<h2 className="text-sm font-semibold">{t("NotifReviewTitle")}</h2>
<dl className="space-y-1 text-sm">
<div className="flex gap-2">
<dt className="w-24 shrink-0 text-muted-foreground">{t("NotifMessage")}</dt>
<dd>{message}</dd>
</div>
<div className="flex gap-2">
<dt className="w-24 shrink-0 text-muted-foreground">{t("Category")}</dt>
<dd className="capitalize">{t(TYPE_OPTIONS.find((o) => o.value === type)?.label ?? type)}</dd>
</div>
<div className="flex gap-2">
<dt className="w-24 shrink-0 text-muted-foreground">{t("NotifAudience")}</dt>
<dd>{targetSummary()}</dd>
</div>
</dl>
<div className="flex gap-2">
<Button type="button" variant="outline" onClick={handleBack} disabled={sending}>
{t("Back")}
</Button>
<Button type="button" onClick={handleSend} disabled={sending}>
{sending ? t("NotifSending") : t("Send")}
</Button>
</div>
</div>
) : (
<form onSubmit={handleReview} className="max-w-xl space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="notification-title">{t("Title")}</Label>
<Input
id="notification-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder={t("NotifTitlePlaceholder")}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="notification-message">{t("NotifMessage")}</Label>
<Input
id="notification-message"
required
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder={t("NotifMessagePlaceholder")}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="notification-type">{t("Category")}</Label>
<Select value={type} onValueChange={setType}>
<SelectTrigger id="notification-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TYPE_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{t(opt.label)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="notification-link">{t("NotifDeepLink")}</Label>
<Input
id="notification-link"
value={link}
onChange={(e) => setLink(e.target.value)}
placeholder={t("NotifDeepLinkPlaceholder")}
/>
</div>
</div>
<fieldset className="space-y-3">
<legend className="text-sm font-medium">{t("NotifAudience")}</legend>
<RadioGroup
aria-label={t("NotifAudience")}
value={tab}
onValueChange={(v) => setTab(v as typeof tab)}
className="flex flex-wrap gap-4"
>
{TARGET_TABS.map((tabOpt) => (
<div key={tabOpt.kind} className="flex items-center gap-2">
<RadioGroupItem id={`notification-audience-${tabOpt.kind}`} value={tabOpt.kind} />
<Label htmlFor={`notification-audience-${tabOpt.kind}`}>{t(tabOpt.label)}</Label>
</div>
))}
</RadioGroup>
<p className="text-xs text-muted-foreground">
{t(TARGET_TABS.find((tabOpt) => tabOpt.kind === tab)?.hint ?? "")}
</p>
{tab === "MEMBERS" ? (
<div className="space-y-1.5">
<Label htmlFor="notification-member-codes">{t("NotifMemberCodes")}</Label>
{memberCodes.length > 0 && (
<div className="flex flex-wrap gap-2">
{memberCodes.map((code) => (
<span
key={code}
className="inline-flex items-center gap-1 rounded-full bg-primary px-3 py-1 text-xs font-medium text-primary-foreground"
>
{code}
<button
type="button"
aria-label={t("NotifRemove", { code })}
onClick={() => removeMemberCode(code)}
className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X aria-hidden="true" className="size-3" />
</button>
</span>
))}
</div>
)}
<Input
id="notification-member-codes"
placeholder={t("NotifMemberCodePlaceholder")}
value={memberDraft}
onChange={(e) => setMemberDraft(e.target.value)}
onKeyDown={handleMemberKeyDown}
/>
</div>
) : null}
{tab === "ADMINS" ? (
<div className="space-y-1.5">
<Label htmlFor="notification-admin-search">{t("NotifSearchAdmins")}</Label>
<Input
id="notification-admin-search"
placeholder={t("NotifSearchAdminsPlaceholder")}
value={adminSearch}
onChange={(e) => void searchAdmins(e.target.value)}
/>
{adminResults.length > 0 && (
<ul className="max-h-40 overflow-y-auto rounded-md border">
{adminResults.map((admin) => {
const selected = adminUsernames.includes(admin.username);
return (
<li key={admin.username}>
<Button
type="button"
variant="ghost"
aria-pressed={selected}
onClick={() => toggleAdmin(admin.username)}
className="w-full justify-between rounded-none px-3 font-normal"
>
<span>{admin.username}</span>
{selected ? <span className="text-xs">{t("NotifSelected")}</span> : null}
</Button>
</li>
);
})}
</ul>
)}
{adminUsernames.length > 0 && (
<div className="flex flex-wrap gap-2">
{adminUsernames.map((username) => (
<span
key={username}
className="inline-flex items-center gap-1 rounded-full bg-primary px-3 py-1 text-xs font-medium text-primary-foreground"
>
{username}
<button
type="button"
aria-label={t("NotifRemove", { code: username })}
onClick={() => toggleAdmin(username)}
className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X aria-hidden="true" className="size-3" />
</button>
</span>
))}
</div>
)}
</div>
) : null}
</fieldset>
<Button type="submit">{t("NotifReviewSend")}</Button>
</form>
)}
</div>
);
}
export default function NotificationsPage() {
return (
<RequireModule pathname="/notifications">
<NotificationsCompose />
</RequireModule>
);
}