205 lines
7.7 KiB
TypeScript
205 lines
7.7 KiB
TypeScript
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
|
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
|
import { useEffect, useState } from "react";
|
|
import { Trans, useTranslation } from "react-i18next";
|
|
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
|
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import NotificationTemplatesTable from "~/modules/notifications/components/NotificationTemplatesTable";
|
|
import { NotificationChannelDto, NotificationChannels } from "~/modules/notifications/services/NotificationChannels";
|
|
import NotificationService, { IGetTemplatesData } from "~/modules/notifications/services/.server/NotificationService";
|
|
import { getUser } from "~/utils/db/users.db.server";
|
|
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import { toast } from "sonner";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { appendCSRFToken } from "~/utils/csrf";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
|
|
|
const logger = createScopedLogger("admin.notification-channels");
|
|
|
|
type LoaderData = {
|
|
items: IGetTemplatesData | null;
|
|
};
|
|
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
|
await verifyUserHasPermission(request, "admin.notifications.view");
|
|
const urlSearchParams = new URL(request.url).searchParams;
|
|
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
|
const items = await NotificationService.getNotificationTemplates({
|
|
limit: 100,
|
|
page: currentPagination.page - 1,
|
|
});
|
|
const data: LoaderData = {
|
|
items,
|
|
};
|
|
return data;
|
|
};
|
|
type ActionData = {
|
|
error?: string;
|
|
success?: string;
|
|
};
|
|
export const action: ActionFunction = async ({ request }) => {
|
|
await verifyUserHasPermission(request, "admin.notifications.manage");
|
|
const { t } = await getTranslations(request);
|
|
const userInfo = await getUserInfo(request);
|
|
await validateCSRFToken(request);
|
|
const form = await request.formData();
|
|
const user = await getUser(userInfo.userId);
|
|
const action = form.get("action");
|
|
if (action === "delete") {
|
|
const id = form.get("id")?.toString() ?? "";
|
|
try {
|
|
await NotificationService.deleteNotificationTemplate(id.toString());
|
|
return Response.json({
|
|
success: t("notifications.admin.templates.deleted"),
|
|
});
|
|
} catch (error: unknown) {
|
|
logger.error({ event: "admin.notification_template.delete_failed", ...toSafeErrorLog(error) }, "Notification template deletion failed");
|
|
return Response.json({ error: t("notifications.admin.templates.errors.deleteFailed") }, { status: 500 });
|
|
}
|
|
} else if (action === "create") {
|
|
// const name = form.get("name")?.toString() ?? "";
|
|
// const description = form.get("description")?.toString() ?? "";
|
|
try {
|
|
// await NotificationService.createNotificationTemplate({
|
|
// notificationGroupId: "",
|
|
// name,
|
|
// description,
|
|
// steps: [],
|
|
// active: true,
|
|
// draft: false,
|
|
// critical: false,
|
|
// });
|
|
return Response.json({ success: t("shared.created") });
|
|
} catch (error: unknown) {
|
|
logger.error({ event: "admin.notification_template.create_failed", ...toSafeErrorLog(error) }, "Notification template creation failed");
|
|
return Response.json({ error: t("notifications.admin.templates.errors.createFailed") }, { status: 500 });
|
|
}
|
|
} else if (action === "send-preview") {
|
|
const channel = form.get("channel")?.toString() ?? "";
|
|
try {
|
|
await NotificationService.send({
|
|
channel,
|
|
to: user!,
|
|
notification: {
|
|
message: t("notifications.admin.templates.previewMessage", { channel }),
|
|
},
|
|
required: true,
|
|
});
|
|
return Response.json({ success: t("notifications.admin.templates.previewSent", { channel }) });
|
|
} catch (error: unknown) {
|
|
logger.error({ event: "admin.notification_template.preview_failed", ...toSafeErrorLog(error) }, "Notification template preview failed");
|
|
return Response.json({ error: t("notifications.admin.templates.errors.previewFailed") }, { status: 500 });
|
|
}
|
|
}
|
|
return Response.json({ error: t("notifications.errors.invalidAction") }, { status: 400 });
|
|
};
|
|
|
|
export default function () {
|
|
const { t } = useTranslation();
|
|
const data = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const submit = useSubmit();
|
|
|
|
const [showSetup, setShowSetup] = useState(false);
|
|
|
|
useEffect(() => {
|
|
let missingTemplate = false;
|
|
NotificationChannels.forEach((i) => {
|
|
if (!data.items?.data?.find((t) => t.name === i.name)) {
|
|
missingTemplate = true;
|
|
}
|
|
});
|
|
if (missingTemplate) {
|
|
setShowSetup(true);
|
|
}
|
|
}, [data.items?.data]);
|
|
|
|
useEffect(() => {
|
|
if (actionData?.error) {
|
|
toast.error(actionData?.error);
|
|
} else if (actionData?.success) {
|
|
toast.success(actionData?.success);
|
|
}
|
|
}, [actionData]);
|
|
|
|
// function onCreate({ name, description }: { name: string; description: string }) {
|
|
// const form = new FormData();
|
|
// form.append("action", "create");
|
|
// form.append("name", name);
|
|
// form.append("description", description);
|
|
// submit(form, {
|
|
// method: "post",
|
|
// });
|
|
// }
|
|
function onDelete(id: string) {
|
|
const form = new FormData();
|
|
appendCSRFToken(form);
|
|
form.append("action", "delete");
|
|
form.append("id", id);
|
|
submit(form, {
|
|
method: "post",
|
|
});
|
|
}
|
|
function onSendPreview(item: NotificationChannelDto) {
|
|
const form = new FormData();
|
|
appendCSRFToken(form);
|
|
form.append("action", "send-preview");
|
|
form.append("channel", item.name);
|
|
submit(form, {
|
|
method: "post",
|
|
});
|
|
}
|
|
return (
|
|
<>
|
|
<div className="w-full space-y-3 px-6 py-2 pb-6 mobile:px-4 sm:pt-3">
|
|
<div className="md:border-border md:border-b md:py-2">
|
|
<div className="flex items-center justify-between">
|
|
<h3 className="text-foreground text-lg font-medium leading-6">{t("notifications.admin.channels.title")}</h3>
|
|
{!showSetup && <ButtonSecondary onClick={() => setShowSetup(true)}>{t("notifications.admin.channels.actions.showSetupInstructions")}</ButtonSecondary>}
|
|
</div>
|
|
</div>
|
|
|
|
{showSetup && <SetUpInstructions />}
|
|
|
|
<NotificationTemplatesTable items={data.items} onDelete={onDelete} onSendPreview={onSendPreview} />
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
function SetUpInstructions() {
|
|
const { t } = useTranslation();
|
|
return (
|
|
<InfoBanner title={t("notifications.admin.channels.setup.title")} text="">
|
|
<div className="space-y-2">
|
|
<div>
|
|
<Trans
|
|
i18nKey="notifications.admin.channels.setup.instructions"
|
|
components={{
|
|
step: <i className="border-border border-b" />,
|
|
type: <i className="border-border border-b" />,
|
|
}}
|
|
/>
|
|
<ul>
|
|
<li>
|
|
◉ <b>{t("notifications.admin.channels.setup.fields.content")}</b> <span className="text-red-500">*</span>:{" "}
|
|
<span className="select-all">{"{{message}}"}</span>
|
|
</li>
|
|
<li>
|
|
◉ <b>{t("notifications.admin.channels.setup.fields.redirectUrl")}</b>{" "}
|
|
<i>{t("notifications.admin.channels.setup.fields.optional")}</i>: <span className="select-all">{"{{action.url}}"}</span>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</InfoBanner>
|
|
);
|
|
}
|