191 lines
6.9 KiB
TypeScript
191 lines
6.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { errorToResponse } from "@kri/common/http";
|
|
import { createNotiHubApi } from "@/lib/http-server";
|
|
import type { RouteContext } from "@/types/common";
|
|
import {
|
|
BulkSendResponse,
|
|
EmailDestInfo, SaveTemplateRequest,
|
|
SendEmailBulkRequest,
|
|
SendSmsBulkRequest,
|
|
SmsDestInfo,
|
|
Template, TMPLAT_PURPOSE,
|
|
} from "@/types/notification";
|
|
|
|
const apiPath = (slug: string[]) => `${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
|
|
const toResponse = (result: unknown) =>
|
|
result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result);
|
|
|
|
type BulkChannel = "sms" | "email";
|
|
type BulkRequest = SendSmsBulkRequest | SendEmailBulkRequest;
|
|
type Destination = SmsDestInfo | EmailDestInfo;
|
|
|
|
function containsBlankString(value: unknown): boolean {
|
|
if (typeof value === "string") return value.trim().length === 0;
|
|
if (Array.isArray(value)) return value.some(containsBlankString);
|
|
if (value && typeof value === "object") return Object.values(value).some(containsBlankString);
|
|
return false;
|
|
}
|
|
|
|
function isValidDestination(destination: unknown, channel: BulkChannel): destination is Destination {
|
|
if (!destination || typeof destination !== "object" || Array.isArray(destination) || containsBlankString(destination)) {
|
|
return false;
|
|
}
|
|
|
|
const address = channel === "sms" ? "destTel" : "destEml";
|
|
return typeof (destination as Record<string, unknown>)[address] === "string";
|
|
}
|
|
|
|
function isValidBulkRequest(body: unknown, channel: BulkChannel): body is BulkRequest {
|
|
if (!body || typeof body !== "object" || Array.isArray(body)) return false;
|
|
|
|
const request = body as Record<string, unknown>;
|
|
return (
|
|
typeof request.templateIdx === "number" &&
|
|
Number.isInteger(request.templateIdx) &&
|
|
request.templateIdx > 0 &&
|
|
typeof request.reqstCmpn === "string" &&
|
|
request.reqstCmpn.trim().length > 0 &&
|
|
typeof request.reqstUser === "string" &&
|
|
request.reqstUser.trim().length > 0 &&
|
|
typeof request.reqstSvc === "string" &&
|
|
request.reqstSvc.trim().length > 0 &&
|
|
Array.isArray(request.destinations) &&
|
|
request.destinations.length > 0 &&
|
|
request.destinations.every((destination) => isValidDestination(destination, channel))
|
|
);
|
|
}
|
|
|
|
async function sendBulk(body: BulkRequest, channel: BulkChannel) {
|
|
const notiHubApi = await createNotiHubApi();
|
|
const template = await notiHubApi.get<Template>(`/template/${body.templateIdx}`);
|
|
|
|
const bulkSendKey = await notiHubApi.put<string>(`/send-${channel}/create/bulk`, {
|
|
reqstCmpn: body.reqstCmpn,
|
|
reqstUser: body.reqstUser,
|
|
reqstSvc: body.reqstSvc,
|
|
prjctCd: template.itrntPrjctCd,
|
|
tmplatIdx: template.tmplatIdx,
|
|
resve: false,
|
|
trgtCnt: body.destinations.length,
|
|
});
|
|
|
|
return notiHubApi.post<BulkSendResponse>(`/send-${channel}/bulk`, {
|
|
...(channel === "sms" ? { sendTel: template.sendTel } : { sendEml: template.sendEml }),
|
|
sendNm: template.sendNm,
|
|
bulkSendKey,
|
|
destInfoList: body.destinations,
|
|
});
|
|
}
|
|
|
|
export async function GET(request: NextRequest, context: RouteContext) {
|
|
try {
|
|
const { slug = [] } = await context.params;
|
|
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
|
|
const notiHubApi = await createNotiHubApi();
|
|
if (slug.length === 3 && slug[0] === "template" && slug[2] === "attachment") {
|
|
const buffer = await notiHubApi.get<ArrayBuffer>(apiPath(slug), {query, expectBinary: true});
|
|
return new NextResponse(buffer, {headers: {"Content-Type": "application/octet-stream"}});
|
|
}
|
|
return toResponse(await notiHubApi.get<unknown>(apiPath(slug), { query }));
|
|
} catch (error: unknown) {
|
|
return errorToResponse(error);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest, context: RouteContext) {
|
|
try {
|
|
const { slug = [] } = await context.params;
|
|
const channel: BulkChannel | undefined =
|
|
slug.length === 1 && slug[0] === "sms-bulk"
|
|
? "sms"
|
|
: slug.length === 1 && slug[0] === "email-bulk"
|
|
? "email"
|
|
: undefined;
|
|
|
|
if (channel) {
|
|
const body: unknown = await request.json().catch(() => undefined);
|
|
if (!isValidBulkRequest(body, channel)) {
|
|
const label = channel === "sms" ? "SMS" : "Email";
|
|
return NextResponse.json({ message: `${label} request body is invalid.` }, { status: 400 });
|
|
}
|
|
|
|
return toResponse(await sendBulk(body, channel));
|
|
}
|
|
|
|
const notiHubApi = await createNotiHubApi();
|
|
const body = await request.json().catch(() => undefined);
|
|
return toResponse(await notiHubApi.post<unknown>(apiPath(slug), body));
|
|
} catch (error: unknown) {
|
|
return errorToResponse(error);
|
|
}
|
|
}
|
|
|
|
export async function PUT(request: NextRequest, context: RouteContext) {
|
|
try {
|
|
const { slug = [] } = await context.params;
|
|
const notiHubApi = await createNotiHubApi();
|
|
const contentType = request.headers.get("content-type") ?? "";
|
|
|
|
if (contentType.includes("multipart/form-data")) {
|
|
return toResponse(await notiHubApi.putForm<unknown>(apiPath(slug), await request.formData()));
|
|
}
|
|
|
|
const body = await request.json().catch(() => undefined);
|
|
return toResponse(await notiHubApi.put<unknown>(apiPath(slug), body));
|
|
} catch (error: unknown) {
|
|
return errorToResponse(error);
|
|
}
|
|
}
|
|
|
|
export async function PATCH(request: NextRequest, context: RouteContext) {
|
|
try {
|
|
const { slug = [] } = await context.params;
|
|
const [action] = slug;
|
|
|
|
if (action !== "template") {
|
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
|
}
|
|
|
|
const formData = await request.formData();
|
|
const templatePart = formData.get("template");
|
|
const body = templatePart instanceof Blob
|
|
? JSON.parse(await templatePart.text()) as SaveTemplateRequest
|
|
: null;
|
|
|
|
if (!body || !body.tmplatIdx) {
|
|
return NextResponse.json({ message: "Template request body is invalid." }, { status: 400 });
|
|
}
|
|
|
|
const notiHubApi = await createNotiHubApi();
|
|
const current = await notiHubApi.get<Template>(`/template/${body.tmplatIdx}`);
|
|
if (!current) {
|
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
|
}
|
|
|
|
const next: Template = {
|
|
...current,
|
|
tmplatNm: body.tmplatNm,
|
|
tmplatTitle: body.tmplatTitle,
|
|
tmplatBody: body.tmplatBody,
|
|
};
|
|
|
|
const backendForm = new FormData();
|
|
backendForm.append(
|
|
"template",
|
|
new Blob([JSON.stringify(next)], {type: "application/json"})
|
|
);
|
|
for (const [key, value] of formData.entries()) {
|
|
if (key === "template") continue;
|
|
backendForm.append(key, value);
|
|
}
|
|
|
|
const query = new URLSearchParams();
|
|
request.nextUrl.searchParams.getAll("deleteFileNames").forEach((name) => query.append("deleteFileNames", name));
|
|
const path = query.size ? `${apiPath(slug)}?${query}` : apiPath(slug);
|
|
|
|
return toResponse(await notiHubApi.patchForm<unknown>(path, backendForm));
|
|
} catch (error: unknown) {
|
|
return errorToResponse(error);
|
|
}
|
|
}
|