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
289 lines
12 KiB
TypeScript
289 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState, type FormEvent } from "react";
|
|
import { CheckCircle2, Loader2, Upload } from "lucide-react";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import type { Translate } from "@/app/lib/i18n/t";
|
|
import { resizeToJpegBase64 } from "@/app/lib/kyc/resizeImage";
|
|
import { submitKycForMember, uploadKycDocForMember } from "@/app/lib/services/adminKyc";
|
|
import { getMember } from "@/app/lib/services/members";
|
|
import type { AdminKycPhotoType, AdminMember } from "@/app/lib/types";
|
|
import { KycDrawer } from "./KycDrawer";
|
|
|
|
const DOCS: { key: AdminKycPhotoType; label: string }[] = [
|
|
{ key: "ID_FRONT", label: "KycDocFront" },
|
|
{ key: "ID_BACK", label: "KycDocBack" },
|
|
];
|
|
|
|
type IdType = "MYKAD" | "PASSPORT";
|
|
interface DocState {
|
|
status: "idle" | "uploading" | "uploaded" | "error";
|
|
preview: string | null;
|
|
ref: string | null;
|
|
error: string | null;
|
|
}
|
|
const EMPTY: DocState = { status: "idle", preview: null, ref: null, error: null };
|
|
|
|
/** Admin-facing copy for the services' KYC error codes (member wording is in the customer portal). */
|
|
const CODE_COPY: Record<string, string> = {
|
|
KYC_ALREADY_PENDING: "KycSubErrAlreadyPending",
|
|
KYC_ALREADY_VERIFIED: "KycSubErrAlreadyVerified",
|
|
KYC_ID_IN_USE: "KycSubErrIdInUse",
|
|
KYC_INVALID: "KycSubErrInvalid",
|
|
KYC_DOC_NOT_OWNED: "KycSubErrDocNotOwned",
|
|
KYC_UNSUPPORTED_TYPE: "KycSubErrUnsupportedType",
|
|
KYC_TOO_LARGE: "KycSubErrTooLarge",
|
|
KYC_COMMIT_FAILED: "KycSubErrCommitFailed",
|
|
KYC_UPLOAD_FAILED: "KycSubErrUploadFailed",
|
|
};
|
|
|
|
function copyFor(err: unknown, fallback: string, t: Translate): string {
|
|
const msg = err instanceof Error ? err.message : "";
|
|
return Object.hasOwn(CODE_COPY, msg) ? t(CODE_COPY[msg]) : fallback;
|
|
}
|
|
|
|
interface Errors {
|
|
memberCode?: string;
|
|
submitName?: string;
|
|
identityNo?: string;
|
|
docs: Partial<Record<AdminKycPhotoType, string>>;
|
|
}
|
|
|
|
/**
|
|
* Submit a KYC on a member's behalf (mockup "Admin · Submit on behalf"). Same rules as the member flow:
|
|
* photos upload to the member's private folder as they are picked (TWO-STEP — committed only when the
|
|
* submit succeeds), and the result is a PENDING record that still needs approval.
|
|
*/
|
|
export function KycSubmitDrawer({ onClose, onSubmitted }: { onClose: () => void; onSubmitted: () => void }) {
|
|
const t = useT();
|
|
const [memberCode, setMemberCode] = useState("");
|
|
const [member, setMember] = useState<AdminMember | null>(null);
|
|
const [memberError, setMemberError] = useState<string | null>(null);
|
|
const [submitName, setSubmitName] = useState("");
|
|
const [identityType, setIdentityType] = useState<IdType>("MYKAD");
|
|
const [identityNo, setIdentityNo] = useState("");
|
|
const [docs, setDocs] = useState<Record<AdminKycPhotoType, DocState>>({ ID_FRONT: EMPTY, ID_BACK: EMPTY });
|
|
const [errors, setErrors] = useState<Errors | null>(null);
|
|
const [submitError, setSubmitError] = useState<string | null>(null);
|
|
const [submitting, setSubmitting] = useState(false);
|
|
const previews = useRef<Partial<Record<AdminKycPhotoType, string>>>({});
|
|
// Per-slot pick counter: an upload that finishes after the slot was re-picked is ignored, so a
|
|
// slow earlier upload can never overwrite the newer photo's reference.
|
|
const picks = useRef<Partial<Record<AdminKycPhotoType, number>>>({});
|
|
|
|
useEffect(() => {
|
|
const current = previews.current;
|
|
return () => Object.values(current).forEach(u => u && URL.revokeObjectURL(u));
|
|
}, []);
|
|
|
|
const code = memberCode.trim().toUpperCase();
|
|
|
|
const lookup = async () => {
|
|
setMember(null);
|
|
setMemberError(null);
|
|
if (!code) return;
|
|
try {
|
|
setMember(await getMember(code));
|
|
} catch {
|
|
setMemberError(t("KycMemberLookupFailed"));
|
|
}
|
|
};
|
|
|
|
const setDoc = (key: AdminKycPhotoType, next: DocState) => setDocs(prev => ({ ...prev, [key]: next }));
|
|
|
|
const pick = async (key: AdminKycPhotoType, file: File) => {
|
|
if (!code) {
|
|
setErrors({ memberCode: t("KycMemberLookupFailed"), docs: {} });
|
|
return;
|
|
}
|
|
const old = previews.current[key];
|
|
if (old) URL.revokeObjectURL(old);
|
|
const preview = URL.createObjectURL(file);
|
|
previews.current[key] = preview;
|
|
const pickId = (picks.current[key] ?? 0) + 1;
|
|
picks.current[key] = pickId;
|
|
setDoc(key, { status: "uploading", preview, ref: null, error: null });
|
|
try {
|
|
const { base, fileType } = await resizeToJpegBase64(file);
|
|
const { reference } = await uploadKycDocForMember(code, key, fileType, base);
|
|
if (picks.current[key] !== pickId) return;
|
|
setDoc(key, { status: "uploaded", preview, ref: reference, error: null });
|
|
} catch (err) {
|
|
if (picks.current[key] !== pickId) return;
|
|
setDoc(key, { status: "error", preview, ref: null, error: copyFor(err, t("KycActionFailed"), t) });
|
|
}
|
|
};
|
|
|
|
const validate = (): Errors => {
|
|
const e: Errors = { docs: {} };
|
|
if (!code) e.memberCode = t("KycMemberLookupFailed");
|
|
const name = submitName.trim();
|
|
if (name.length < 2 || name.length > 200) e.submitName = t("KycSubNameRequired");
|
|
const no = identityNo.trim();
|
|
if (!no) e.identityNo = t("KycSubIdNoRequired");
|
|
else if (identityType === "MYKAD" && !/^\d{12}$/.test(no.replace(/[-\s]/g, ""))) e.identityNo = t("KycSubMykadInvalid");
|
|
else if (identityType === "PASSPORT" && !/^[A-Za-z0-9]{6,20}$/.test(no.replace(/\s/g, ""))) e.identityNo = t("KycSubPassportInvalid");
|
|
for (const d of DOCS) if (docs[d.key].status !== "uploaded") e.docs[d.key] = t("KycSubDocRequired", { doc: t(d.label) });
|
|
return e;
|
|
};
|
|
|
|
const onSubmit = async (ev: FormEvent<HTMLFormElement>) => {
|
|
ev.preventDefault();
|
|
setSubmitError(null);
|
|
const found = validate();
|
|
if (found.memberCode || found.submitName || found.identityNo || Object.keys(found.docs).length) {
|
|
setErrors(found);
|
|
return;
|
|
}
|
|
setErrors(null);
|
|
setSubmitting(true);
|
|
try {
|
|
await submitKycForMember({
|
|
memberCode: code,
|
|
submitName: submitName.trim(),
|
|
identityType,
|
|
identityNo: identityNo.trim(),
|
|
docs: { ID_FRONT: docs.ID_FRONT.ref!, ID_BACK: docs.ID_BACK.ref! },
|
|
});
|
|
onSubmitted();
|
|
} catch (err) {
|
|
setSubmitError(err instanceof ApiError ? copyFor(err, err.message, t) : t("KycActionFailed"));
|
|
} finally {
|
|
setSubmitting(false);
|
|
}
|
|
};
|
|
|
|
const uploading = DOCS.some(d => docs[d.key].status === "uploading");
|
|
|
|
return (
|
|
<KycDrawer
|
|
title={t("KycOnBehalfTitle")}
|
|
description={t("KycOnBehalfSubtitle")}
|
|
onClose={onClose}
|
|
footer={
|
|
<div className="flex justify-end gap-2">
|
|
<Button variant="outline" onClick={onClose}>{t("KycCancel")}</Button>
|
|
<Button type="submit" form="kyc-on-behalf" disabled={submitting || uploading}>
|
|
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
|
{t("KycSubmitForReview")}
|
|
</Button>
|
|
</div>
|
|
}
|
|
>
|
|
<form id="kyc-on-behalf" noValidate onSubmit={onSubmit} className="space-y-5">
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="kyc-member">{t("KycMember")}</Label>
|
|
<Input
|
|
id="kyc-member"
|
|
value={memberCode}
|
|
onChange={e => setMemberCode(e.target.value)}
|
|
onBlur={lookup}
|
|
placeholder={t("KycSubMemberCodePlaceholder")}
|
|
aria-invalid={Boolean(errors?.memberCode || memberError)}
|
|
/>
|
|
{member && (
|
|
<div className="flex items-center gap-2.5 rounded-lg bg-muted px-3 py-2.5 text-sm" data-testid="kyc-member-card">
|
|
<span className="flex-1">
|
|
<strong>{[member.name, member.surname].filter(Boolean).join(" ") || code}</strong>
|
|
{member.email ? ` · ${member.email}` : ""}
|
|
</span>
|
|
<span className="text-muted-foreground">
|
|
{member.kycFlag === "Y" ? t("KycVerifiedMember") : t("KycNotVerifiedMember")}
|
|
</span>
|
|
</div>
|
|
)}
|
|
{(memberError || errors?.memberCode) && (
|
|
<p className="text-sm text-destructive">{memberError ?? errors?.memberCode}</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="kyc-name">{t("KycNameOnId")}</Label>
|
|
<Input id="kyc-name" value={submitName} onChange={e => setSubmitName(e.target.value)}
|
|
aria-invalid={Boolean(errors?.submitName)} />
|
|
{errors?.submitName && <p className="text-sm text-destructive">{errors.submitName}</p>}
|
|
</div>
|
|
|
|
<div className="grid gap-3 sm:grid-cols-[auto_1fr]">
|
|
<fieldset className="space-y-1.5">
|
|
<legend className="mb-1.5 text-sm font-medium">{t("KycIdType")}</legend>
|
|
<div className="flex h-9 overflow-hidden rounded-md border">
|
|
{(["MYKAD", "PASSPORT"] as const).map(type => (
|
|
<label
|
|
key={type}
|
|
className={
|
|
"flex cursor-pointer items-center px-3.5 text-sm " +
|
|
(identityType === type ? "bg-primary font-semibold text-primary-foreground" : "hover:bg-muted")
|
|
}
|
|
>
|
|
<input type="radio" name="kyc-id-type" className="sr-only" checked={identityType === type}
|
|
onChange={() => setIdentityType(type)} />
|
|
{type === "MYKAD" ? t("KycSubIdTypeMykad") : t("KycSubIdTypePassport")}
|
|
</label>
|
|
))}
|
|
</div>
|
|
</fieldset>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="kyc-idno">{t("KycIdNumber")}</Label>
|
|
<Input id="kyc-idno" value={identityNo} onChange={e => setIdentityNo(e.target.value)}
|
|
inputMode={identityType === "MYKAD" ? "numeric" : "text"}
|
|
placeholder={identityType === "MYKAD" ? "900101-14-5678" : "A1234567"}
|
|
aria-invalid={Boolean(errors?.identityNo)} />
|
|
{errors?.identityNo && <p className="text-sm text-destructive">{errors.identityNo}</p>}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<p className="text-sm font-medium">{t("KycDocuments")}</p>
|
|
<div className="grid grid-cols-2 gap-2.5">
|
|
{DOCS.map(d => {
|
|
const state = docs[d.key];
|
|
const err = state.error ?? errors?.docs[d.key];
|
|
return (
|
|
<div key={d.key} className="space-y-1">
|
|
<label
|
|
className={
|
|
"flex h-28 cursor-pointer flex-col items-center justify-center gap-1.5 overflow-hidden rounded-lg border-2 border-dashed text-center text-sm " +
|
|
(err ? "border-destructive" : "border-primary/30 hover:bg-muted")
|
|
}
|
|
>
|
|
{state.preview ? (
|
|
// eslint-disable-next-line @next/next/no-img-element -- local blob preview
|
|
<img src={state.preview} alt="" className="h-16 w-full object-cover" />
|
|
) : (
|
|
<Upload aria-hidden="true" className="size-5 text-primary" />
|
|
)}
|
|
<span className="flex items-center gap-1 px-1 font-medium">
|
|
{state.status === "uploading" && <Loader2 aria-hidden="true" className="size-3.5 animate-spin" />}
|
|
{state.status === "uploaded" && <CheckCircle2 aria-hidden="true" className="size-3.5 text-positive" />}
|
|
{t(d.label)}
|
|
</span>
|
|
<input
|
|
type="file"
|
|
accept="image/jpeg,image/png"
|
|
className="sr-only"
|
|
aria-label={t(d.label)}
|
|
onChange={e => {
|
|
const file = e.target.files?.[0];
|
|
e.target.value = "";
|
|
if (file) void pick(d.key, file);
|
|
}}
|
|
/>
|
|
</label>
|
|
{err && <p className="text-xs text-destructive">{err}</p>}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
{submitError && <p role="alert" className="text-sm text-destructive">{submitError}</p>}
|
|
</form>
|
|
</KycDrawer>
|
|
);
|
|
}
|