feat(P19IM1-3,P19IM1-4): 接入业务事件与通知渠道后台

这个提交包含在:
2026-03-08 13:14:22 +08:00
父节点 f6d9f23553
当前提交 faff86c947
共修改 9 个文件,包含 1268 行新增和 135 行删除
+91
查看文件
@@ -0,0 +1,91 @@
import { apiRequestData } from "./http";
export type NotificationChannelType = "wecom" | "wechat_work";
export type NotificationChannelMode = "mock" | "wecom_webhook";
export type NotificationDomainScope =
| "workflow"
| "reimbursement"
| "leave"
| "procurement"
| "asset"
| "inventory";
export type NotificationChannelRouting = {
roleCodes: string[];
domainScopes: NotificationDomainScope[];
allowedTypes: string[];
};
export type NotificationChannelConfig = {
mode: NotificationChannelMode;
webhookUrl: string | null;
secret: string | null;
timeoutMs: number;
routing: NotificationChannelRouting;
};
export type NotificationChannelTemplate = {
title: string;
body: string;
footer: string;
deepLinkLabel: string;
};
export type NotificationChannel = {
id: string;
channelType: NotificationChannelType;
name: string;
enabled: boolean;
configJson: NotificationChannelConfig;
templateJson: NotificationChannelTemplate;
createdAt: string | null;
updatedAt: string | null;
};
export type NotificationChannelListResponse = {
items: NotificationChannel[];
};
export type NotificationChannelPayload = {
channelType: "wecom";
name: string;
enabled: boolean;
configJson: NotificationChannelConfig;
templateJson: NotificationChannelTemplate;
};
export type NotificationChannelTestResponse = {
channel: NotificationChannel;
testResult: {
ok: boolean;
code: string;
previewMessage: string | null;
response: unknown;
skipped: boolean;
};
};
export async function fetchNotificationChannels() {
return apiRequestData<NotificationChannelListResponse>("/api/notifications/channels");
}
export async function createNotificationChannel(payload: NotificationChannelPayload) {
return apiRequestData<{ channel: NotificationChannel }>("/api/notifications/channels", {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function updateNotificationChannel(id: string, payload: Omit<NotificationChannelPayload, "channelType">) {
return apiRequestData<{ channel: NotificationChannel }>(`/api/notifications/channels/${id}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export async function testNotificationChannel(id: string) {
return apiRequestData<NotificationChannelTestResponse>(`/api/notifications/channels/${id}/test`, {
method: "POST",
body: JSON.stringify({}),
});
}
@@ -102,6 +102,12 @@ export const NAV_ITEMS: NavItem[] = [
icon: "dataset",
anyOf: ["masterdata.view", "masterdata.manage"],
},
{
to: "/system/notification-channels",
label: "通知渠道",
icon: "notifications_active",
anyOf: ["notification.channel.manage"],
},
{
to: "/system/approval-rules",
label: "审批规则",
@@ -0,0 +1,641 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { mapApiErrorMessage } from "../api/errorMessages";
import {
createNotificationChannel,
fetchNotificationChannels,
testNotificationChannel,
updateNotificationChannel,
type NotificationChannel,
type NotificationChannelConfig,
type NotificationChannelPayload,
type NotificationChannelTemplate,
} from "../api/notificationChannels";
import { isApiError } from "../api/types";
import { PageHeader } from "../components/common/PageHeader";
import { TableSkeleton } from "../components/common/TableSkeleton";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/table";
import { Textarea } from "../components/ui/textarea";
type ChannelFormState = {
channelType: "wecom";
name: string;
enabled: boolean;
mode: NotificationChannelConfig["mode"];
webhookUrl: string;
secret: string;
timeoutMs: string;
roleCodes: string[];
domainScopes: NotificationChannelConfig["routing"]["domainScopes"];
allowedTypes: string[];
title: string;
body: string;
footer: string;
deepLinkLabel: string;
};
type TestResultState = {
channelId: string;
channelName: string;
ok: boolean;
code: string;
skipped: boolean;
previewMessage: string | null;
response: unknown;
};
const ROLE_OPTIONS = [
{ value: "employee", label: "employee" },
{ value: "manager", label: "manager" },
{ value: "ceo", label: "ceo" },
{ value: "finance", label: "finance" },
{ value: "finance_mgr", label: "finance_mgr" },
{ value: "administration", label: "administration" },
{ value: "hr", label: "hr" },
{ value: "admin", label: "admin" },
] as const;
const DOMAIN_SCOPE_OPTIONS = [
{ value: "workflow", label: "审批待办" },
{ value: "reimbursement", label: "报销" },
{ value: "leave", label: "请假" },
{ value: "procurement", label: "采购" },
{ value: "asset", label: "资产" },
{ value: "inventory", label: "盘点" },
] as const;
const NOTIFICATION_TYPE_OPTIONS = [
{ value: "workflow.task_assigned", label: "workflow.task_assigned" },
{ value: "reimbursement.approved", label: "reimbursement.approved" },
{ value: "reimbursement.rejected", label: "reimbursement.rejected" },
{ value: "reimbursement.returned", label: "reimbursement.returned" },
{ value: "reimbursement.paid", label: "reimbursement.paid" },
{ value: "leave.approved", label: "leave.approved" },
{ value: "leave.rejected", label: "leave.rejected" },
{ value: "purchase_request.approved", label: "purchase_request.approved" },
{ value: "purchase_request.rejected", label: "purchase_request.rejected" },
{ value: "asset.assigned", label: "asset.assigned" },
{ value: "asset.returned", label: "asset.returned" },
{ value: "asset.transferred", label: "asset.transferred" },
{ value: "inventory_check.completed", label: "inventory_check.completed" },
] as const;
function resolveError(error: unknown) {
if (isApiError(error)) {
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
}
if (error instanceof Error) {
return error.message;
}
return "请求失败,请稍后重试。";
}
function buildInitialForm(): ChannelFormState {
return {
channelType: "wecom",
name: "",
enabled: true,
mode: "mock",
webhookUrl: "",
secret: "",
timeoutMs: "5000",
roleCodes: [],
domainScopes: [],
allowedTypes: [],
title: "{{title}}",
body: "{{body}}\n\n查看详情:{{detailUrl}}",
footer: "来自海音达工作台",
deepLinkLabel: "查看详情",
};
}
function mapChannelToForm(channel: NotificationChannel): ChannelFormState {
return {
channelType: "wecom",
name: channel.name,
enabled: channel.enabled,
mode: channel.configJson.mode,
webhookUrl: channel.configJson.webhookUrl ?? "",
secret: channel.configJson.secret ?? "",
timeoutMs: String(channel.configJson.timeoutMs ?? 5000),
roleCodes: channel.configJson.routing.roleCodes ?? [],
domainScopes: channel.configJson.routing.domainScopes ?? [],
allowedTypes: channel.configJson.routing.allowedTypes ?? [],
title: channel.templateJson.title,
body: channel.templateJson.body,
footer: channel.templateJson.footer,
deepLinkLabel: channel.templateJson.deepLinkLabel,
};
}
function toggleSelection(values: string[], value: string) {
return values.includes(value) ? values.filter((item) => item !== value) : [...values, value];
}
function formatDateTime(value: string | null) {
if (!value) return "-";
return value.slice(0, 19).replace("T", " ");
}
function formatChannelType(channelType: string) {
return channelType === "wechat_work" ? "企微(兼容别名)" : "企微";
}
function formatMode(mode: string) {
return mode === "wecom_webhook" ? "Webhook" : "Mock";
}
function formatSummary(values: string[], labelMap: Record<string, string>, emptyLabel: string) {
if (!values.length) return emptyLabel;
return values.map((value) => labelMap[value] ?? value).join("、");
}
function buildPayload(form: ChannelFormState): NotificationChannelPayload {
const templateJson: NotificationChannelTemplate = {
title: form.title.trim() || "{{title}}",
body: form.body.trim() || "{{body}}\n\n查看详情:{{detailUrl}}",
footer: form.footer.trim() || "来自海音达工作台",
deepLinkLabel: form.deepLinkLabel.trim() || "查看详情",
};
return {
channelType: form.channelType,
name: form.name.trim(),
enabled: form.enabled,
configJson: {
mode: form.mode,
webhookUrl: form.webhookUrl.trim() || null,
secret: form.secret.trim() || null,
timeoutMs: Math.max(100, Number(form.timeoutMs || 5000)),
routing: {
roleCodes: form.roleCodes,
domainScopes: form.domainScopes,
allowedTypes: form.allowedTypes,
},
},
templateJson,
};
}
const roleLabelMap = Object.fromEntries(ROLE_OPTIONS.map((item) => [item.value, item.label]));
const domainLabelMap = Object.fromEntries(DOMAIN_SCOPE_OPTIONS.map((item) => [item.value, item.label]));
export function NotificationChannelsPage() {
const queryClient = useQueryClient();
const [error, setError] = useState("");
const [editingId, setEditingId] = useState<string | null>(null);
const [form, setForm] = useState<ChannelFormState>(buildInitialForm);
const [lastTestResult, setLastTestResult] = useState<TestResultState | null>(null);
const channelsQuery = useQuery({
queryKey: ["notification-channels"],
queryFn: () => fetchNotificationChannels(),
});
const saveMutation = useMutation({
mutationFn: async () => {
if (editingId) {
const payload = buildPayload(form);
return updateNotificationChannel(editingId, {
name: payload.name,
enabled: payload.enabled,
configJson: payload.configJson,
templateJson: payload.templateJson,
});
}
return createNotificationChannel(buildPayload(form));
},
onSuccess: async ({ channel }) => {
await queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
setEditingId(channel.id);
setForm(mapChannelToForm(channel));
setError("");
toast.success(editingId ? "通知渠道已更新" : "通知渠道已创建");
},
onError: (mutationError) => {
const message = resolveError(mutationError);
setError(message);
toast.error(message);
},
});
const testMutation = useMutation({
mutationFn: async (channel: NotificationChannel) => {
const result = await testNotificationChannel(channel.id);
return {
channelName: channel.name,
...result,
};
},
onSuccess: (result) => {
setLastTestResult({
channelId: result.channel.id,
channelName: result.channelName,
ok: result.testResult.ok,
code: result.testResult.code,
skipped: result.testResult.skipped,
previewMessage: result.testResult.previewMessage,
response: result.testResult.response,
});
if (result.testResult.ok) {
toast.success("测试发送成功");
} else {
toast.error(`测试发送失败:${result.testResult.code}`);
}
},
onError: (mutationError) => {
const message = resolveError(mutationError);
setError(message);
toast.error(message);
},
});
function startCreate() {
setEditingId(null);
setForm(buildInitialForm());
setLastTestResult(null);
setError("");
}
function startEdit(channel: NotificationChannel) {
setEditingId(channel.id);
setForm(mapChannelToForm(channel));
setError("");
}
const channels = channelsQuery.data?.items ?? [];
return (
<div className="space-y-6">
<PageHeader
title="通知渠道"
subtitle="维护企微群机器人渠道、业务域路由与测试发送。IM 继续通过 Outbox 异步派发。"
actions={
<Button type="button" variant="secondary" onClick={startCreate} data-testid="notification-channels-create">
新建渠道
</Button>
}
/>
{error ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>
) : null}
<div className="card-std space-y-4 p-6">
<div className="flex items-center justify-between gap-3">
<h3 className="text-base font-semibold text-zinc-900">渠道列表</h3>
<p className="text-sm text-zinc-500">当前共 {channels.length} 条渠道配置</p>
</div>
{channelsQuery.isLoading ? <TableSkeleton columns={8} rows={4} /> : null}
{channelsQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{resolveError(channelsQuery.error)}
</p>
) : null}
{!channelsQuery.isLoading && !channelsQuery.isError ? (
<div className="rounded-lg border border-zinc-200">
<Table data-testid="notification-channels-table">
<TableHeader>
<tr>
<TableHead>名称</TableHead>
<TableHead>类型</TableHead>
<TableHead>模式</TableHead>
<TableHead>启用状态</TableHead>
<TableHead>业务域</TableHead>
<TableHead>通知类型数</TableHead>
<TableHead>角色范围</TableHead>
<TableHead>最近更新时间</TableHead>
<TableHead className="w-40">操作</TableHead>
</tr>
</TableHeader>
<TableBody>
{channels.length ? (
channels.map((channel) => (
<TableRow key={channel.id} data-testid="notification-channel-row">
<TableCell className="font-medium text-zinc-900">{channel.name}</TableCell>
<TableCell>{formatChannelType(channel.channelType)}</TableCell>
<TableCell>{formatMode(channel.configJson.mode)}</TableCell>
<TableCell>{channel.enabled ? "启用" : "停用"}</TableCell>
<TableCell className="max-w-xs text-xs text-zinc-600">
{formatSummary(channel.configJson.routing.domainScopes, domainLabelMap, "全部业务域")}
</TableCell>
<TableCell>{channel.configJson.routing.allowedTypes.length || "全部"}</TableCell>
<TableCell className="max-w-xs text-xs text-zinc-600">
{formatSummary(channel.configJson.routing.roleCodes, roleLabelMap, "全部角色")}
</TableCell>
<TableCell className="text-xs text-zinc-600">{formatDateTime(channel.updatedAt)}</TableCell>
<TableCell>
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => startEdit(channel)}
data-testid="notification-channel-edit"
>
编辑
</Button>
<Button
type="button"
size="sm"
variant="secondary"
disabled={testMutation.isPending}
onClick={() => testMutation.mutate(channel)}
data-testid="notification-channel-test"
>
测试
</Button>
</div>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={9} className="py-4 text-center text-sm text-zinc-500">
暂无通知渠道,请先创建企微渠道。
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
) : null}
</div>
<div className="grid gap-6 xl:grid-cols-[minmax(0,2fr)_minmax(320px,1fr)]">
<div className="card-std space-y-4 p-6">
<div className="flex items-center justify-between gap-3">
<div>
<h3 className="text-base font-semibold text-zinc-900">
{editingId ? "编辑通知渠道" : "新建通知渠道"}
</h3>
<p className="text-sm text-zinc-500">
通过角色 / 业务域 / 通知类型三维控制 IM 群路由,避免默认全量广播。
</p>
</div>
{editingId ? (
<Button type="button" variant="outline" onClick={startCreate}>
切换到新建
</Button>
) : null}
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="channelType">渠道类型</Label>
<select
id="channelType"
className="select-std"
value={form.channelType}
disabled={Boolean(editingId)}
onChange={(event) => setForm((prev) => ({ ...prev, channelType: event.target.value as "wecom" }))}
>
<option value="wecom">企微群机器人</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="channelName">渠道名称</Label>
<Input
id="channelName"
value={form.name}
placeholder="采购经理群"
onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label htmlFor="channelMode">模式</Label>
<select
id="channelMode"
className="select-std"
value={form.mode}
onChange={(event) =>
setForm((prev) => ({
...prev,
mode: event.target.value as NotificationChannelConfig["mode"],
}))
}
>
<option value="mock">Mock</option>
<option value="wecom_webhook">企微 Webhook</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="timeoutMs">超时(毫秒)</Label>
<Input
id="timeoutMs"
type="number"
min={100}
value={form.timeoutMs}
onChange={(event) => setForm((prev) => ({ ...prev, timeoutMs: event.target.value }))}
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="webhookUrl">Webhook URL</Label>
<Input
id="webhookUrl"
value={form.webhookUrl}
placeholder={form.mode === "mock" ? "Mock 模式可留空" : "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?..."}
onChange={(event) => setForm((prev) => ({ ...prev, webhookUrl: event.target.value }))}
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="webhookSecret">Webhook Secret(可空)</Label>
<Input
id="webhookSecret"
value={form.secret}
placeholder="可选,配置后将参与签名"
onChange={(event) => setForm((prev) => ({ ...prev, secret: event.target.value }))}
/>
</div>
</div>
<label className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.enabled}
onChange={(event) => setForm((prev) => ({ ...prev, enabled: event.target.checked }))}
/>
启用该渠道
</label>
<div className="grid gap-4 lg:grid-cols-3">
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">角色范围</h4>
<p className="text-xs text-zinc-500">留空表示不限角色。</p>
</div>
<div className="space-y-2">
{ROLE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.roleCodes.includes(option.value)}
onChange={() =>
setForm((prev) => ({
...prev,
roleCodes: toggleSelection(prev.roleCodes, option.value),
}))
}
/>
{option.label}
</label>
))}
</div>
</div>
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">业务域</h4>
<p className="text-xs text-zinc-500">留空表示不限业务域。</p>
</div>
<div className="space-y-2">
{DOMAIN_SCOPE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.domainScopes.includes(option.value)}
onChange={() =>
setForm((prev) => ({
...prev,
domainScopes: toggleSelection(prev.domainScopes, option.value) as ChannelFormState["domainScopes"],
}))
}
/>
{option.label}
</label>
))}
</div>
</div>
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">通知类型</h4>
<p className="text-xs text-zinc-500">留空表示消费所有 IM 一期支持类型。</p>
</div>
<div className="max-h-72 space-y-2 overflow-auto pr-1">
{NOTIFICATION_TYPE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center gap-2 text-sm text-zinc-700">
<input
type="checkbox"
checked={form.allowedTypes.includes(option.value)}
onChange={() =>
setForm((prev) => ({
...prev,
allowedTypes: toggleSelection(prev.allowedTypes, option.value),
}))
}
/>
{option.label}
</label>
))}
</div>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="templateTitle">标题模板</Label>
<Input
id="templateTitle"
value={form.title}
onChange={(event) => setForm((prev) => ({ ...prev, title: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label htmlFor="templateFooter">页脚模板</Label>
<Input
id="templateFooter"
value={form.footer}
onChange={(event) => setForm((prev) => ({ ...prev, footer: event.target.value }))}
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="templateBody">正文模板</Label>
<Textarea
id="templateBody"
value={form.body}
onChange={(event) => setForm((prev) => ({ ...prev, body: event.target.value }))}
/>
<p className="text-xs text-zinc-500">一期支持变量:title、body、detailUrl、targetType、targetId、footer。</p>
</div>
</div>
<div className="flex flex-wrap gap-3">
<Button
type="button"
onClick={() => saveMutation.mutate()}
disabled={saveMutation.isPending}
data-testid="notification-channel-save"
>
{editingId ? "保存更新" : "创建渠道"}
</Button>
<Button type="button" variant="secondary" onClick={startCreate} disabled={saveMutation.isPending}>
重置表单
</Button>
</div>
</div>
<div className="card-std space-y-4 p-6">
<div>
<h3 className="text-base font-semibold text-zinc-900">测试发送</h3>
<p className="text-sm text-zinc-500">仅对已保存渠道执行同步测试,不写业务 Outbox。</p>
</div>
{lastTestResult ? (
<div className="space-y-3 rounded-lg border border-zinc-200 bg-zinc-50 p-4 text-sm">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-zinc-900">渠道:</span>
<span>{lastTestResult.channelName}</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-zinc-900">结果:</span>
<span className={lastTestResult.ok ? "text-emerald-600" : "text-red-600"}>
{lastTestResult.ok ? "成功" : "失败"}
</span>
<span className="text-zinc-500">code={lastTestResult.code}</span>
{lastTestResult.skipped ? <span className="text-amber-600">(已跳过)</span> : null}
</div>
<div>
<p className="mb-1 font-medium text-zinc-900">预览消息</p>
<pre className="whitespace-pre-wrap rounded-lg bg-white p-3 text-xs text-zinc-700">
{lastTestResult.previewMessage ?? "<empty>"}
</pre>
</div>
<div>
<p className="mb-1 font-medium text-zinc-900">Provider 响应</p>
<pre className="overflow-auto rounded-lg bg-white p-3 text-xs text-zinc-700">
{JSON.stringify(lastTestResult.response ?? null, null, 2)}
</pre>
</div>
</div>
) : (
<p className="rounded-lg border border-dashed border-zinc-200 px-3 py-4 text-sm text-zinc-500">
从列表中选择一条渠道并点击“测试”,即可查看发送结果与消息预览。
</p>
)}
</div>
</div>
</div>
);
}
+10
查看文件
@@ -17,6 +17,7 @@ import { InvoicePoolPage } from "../pages/InvoicePoolPage";
import { LoginPage } from "../pages/LoginPage";
import { LeaveRequestPage } from "../pages/LeaveRequestPage";
import { NotificationsPage } from "../pages/NotificationsPage";
import { NotificationChannelsPage } from "../pages/NotificationChannelsPage";
import { PurchaseRequestsPage } from "../pages/PurchaseRequestsPage";
import { AssetRegistryPage } from "../pages/AssetRegistryPage";
import { InventoryChecksPage } from "../pages/InventoryChecksPage";
@@ -220,6 +221,15 @@ export function AppRouter() {
}
/>
<Route
path="system/notification-channels"
element={
<RequirePermission anyOf={["notification.channel.manage"]}>
<NotificationChannelsPage />
</RequirePermission>
}
/>
<Route
path="system/approval-rules"
element={
+143
查看文件
@@ -3,6 +3,10 @@ const { z } = require("zod");
const { AppError } = require("../utils/AppError");
const { buildAuditLogData } = require("../utils/audit");
const { sendData } = require("../utils/reply");
const { createNotifications } = require("../services/notifications");
const { enqueueImNotifications } = require("../services/notifications/imEnqueue");
const { sendNotificationEmailSafe } = require("../services/email");
const { NOTIFICATION_TYPES } = require("../constants/notificationTypes");
const UUID_SCHEMA = z.string().uuid();
const NOTE_SCHEMA = z.string().trim().max(500).nullable().optional();
@@ -72,6 +76,10 @@ function normalizeLocation(value) {
return trimmed ? trimmed : null;
}
function uniq(values) {
return Array.from(new Set((values ?? []).filter(Boolean)));
}
function ensureMovementAllowed(asset) {
if (BLOCKED_MOVEMENT_STATUSES.has(asset.status)) {
throw buildValidationError({ status: "movement_not_allowed" }, 409);
@@ -195,6 +203,7 @@ async function assetMovementsRoutes(fastify) {
const assetId = parseUuid("id", request.params?.id);
const body = parseBody(ASSIGN_BODY_SCHEMA, request.body);
const note = normalizeNote(body.note);
const emailTasks = [];
const result = await fastify.prisma.$transaction(async (tx) => {
const asset = await ensureAssetExists(tx, assetId);
@@ -249,9 +258,52 @@ async function assetMovementsRoutes(fastify) {
}),
});
const recipients = uniq([employee.id]);
const title = `【资产领用】资产卡片 ${asset.asset_no}`;
const bodyText = `资产卡片 ${asset.asset_no} 已分配给你,请在资产台账中查看。`;
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.assetAssigned,
title,
body: bodyText,
targetType: "asset_card",
targetId: asset.id,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.assetAssigned,
title,
body: bodyText,
targetType: "asset_card",
targetId: asset.id,
targetPath: "/assets",
entityType: "asset_card",
entityId: asset.id,
actorId: request.employee.id,
});
emailTasks.push({
type: NOTIFICATION_TYPES.assetAssigned,
recipientEmployeeIds: recipients,
subject: title,
body: bodyText,
targetPath: "/assets",
});
return { updatedAsset, assignmentId: assignment.id };
});
for (const task of emailTasks) {
void sendNotificationEmailSafe({
prisma: fastify.prisma,
config: fastify.config,
logger: fastify.log,
requestId: request.id,
...task,
});
}
return sendData(reply, request, {
assetId: result.updatedAsset.id,
assetNo: result.updatedAsset.asset_no,
@@ -273,6 +325,7 @@ async function assetMovementsRoutes(fastify) {
const assetId = parseUuid("id", request.params?.id);
const body = parseBody(RETURN_BODY_SCHEMA, request.body);
const note = normalizeNote(body.note);
const emailTasks = [];
const result = await fastify.prisma.$transaction(async (tx) => {
const asset = await ensureAssetExists(tx, assetId);
@@ -312,9 +365,52 @@ async function assetMovementsRoutes(fastify) {
}),
});
const recipients = uniq([asset.assignee_employee_id]);
const title = `【资产归还】资产卡片 ${asset.asset_no}`;
const bodyText = `资产卡片 ${asset.asset_no} 已完成归还。`;
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.assetReturned,
title,
body: bodyText,
targetType: "asset_card",
targetId: asset.id,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.assetReturned,
title,
body: bodyText,
targetType: "asset_card",
targetId: asset.id,
targetPath: "/assets",
entityType: "asset_card",
entityId: asset.id,
actorId: request.employee.id,
});
emailTasks.push({
type: NOTIFICATION_TYPES.assetReturned,
recipientEmployeeIds: recipients,
subject: title,
body: bodyText,
targetPath: "/assets",
});
return { updatedAsset, assignmentId: closedAssignment?.id ?? null };
});
for (const task of emailTasks) {
void sendNotificationEmailSafe({
prisma: fastify.prisma,
config: fastify.config,
logger: fastify.log,
requestId: request.id,
...task,
});
}
return sendData(reply, request, {
assetId: result.updatedAsset.id,
assetNo: result.updatedAsset.asset_no,
@@ -339,6 +435,7 @@ async function assetMovementsRoutes(fastify) {
const hasEmployeeField = Object.prototype.hasOwnProperty.call(body, "toEmployeeId");
const hasLocationField = Object.prototype.hasOwnProperty.call(body, "toLocation");
const nextLocation = hasLocationField ? normalizeLocation(body.toLocation) : undefined;
const emailTasks = [];
const result = await fastify.prisma.$transaction(async (tx) => {
const asset = await ensureAssetExists(tx, assetId);
@@ -428,9 +525,55 @@ async function assetMovementsRoutes(fastify) {
}),
});
const recipients = uniq([
currentEmployeeId,
employeeChange ? requestedEmployeeId : currentEmployeeId,
]);
const title = `【资产调拨】资产卡片 ${asset.asset_no}`;
const bodyText = `资产卡片 ${asset.asset_no} 已完成调拨,请在资产台账中查看最新归属与位置。`;
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.assetTransferred,
title,
body: bodyText,
targetType: "asset_card",
targetId: asset.id,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.assetTransferred,
title,
body: bodyText,
targetType: "asset_card",
targetId: asset.id,
targetPath: "/assets",
entityType: "asset_card",
entityId: asset.id,
actorId: request.employee.id,
});
emailTasks.push({
type: NOTIFICATION_TYPES.assetTransferred,
recipientEmployeeIds: recipients,
subject: title,
body: bodyText,
targetPath: "/assets",
});
return { updatedAsset, transferId: transfer.id, assignmentId };
});
for (const task of emailTasks) {
void sendNotificationEmailSafe({
prisma: fastify.prisma,
config: fastify.config,
logger: fastify.log,
requestId: request.id,
...task,
});
}
return sendData(reply, request, {
assetId: result.updatedAsset.id,
assetNo: result.updatedAsset.asset_no,
+60
查看文件
@@ -3,6 +3,10 @@ const { z } = require("zod");
const { AppError } = require("../utils/AppError");
const { buildAuditLogData } = require("../utils/audit");
const { issueDocumentNumber } = require("../services/documentSequence");
const { createNotifications, resolveRecipientsForAssignee } = require("../services/notifications");
const { enqueueImNotifications } = require("../services/notifications/imEnqueue");
const { sendNotificationEmailSafe } = require("../services/email");
const { NOTIFICATION_TYPES } = require("../constants/notificationTypes");
const { sendData } = require("../utils/reply");
const UUID_SCHEMA = z.string().uuid();
@@ -79,6 +83,10 @@ function normalizeOptionalText(value) {
return trimmed ? trimmed : null;
}
function uniq(values) {
return Array.from(new Set((values ?? []).filter(Boolean)));
}
async function ensureScopeReference(tx, scopeType, scopeRefId) {
if (scopeType === "all") {
return null;
@@ -161,6 +169,7 @@ async function ensureInventoryCheck(tx, inventoryCheckId) {
completed_at: true,
created_at: true,
updated_at: true,
created_by: true,
items: {
orderBy: [{ asset: { asset_no: "asc" } }],
select: {
@@ -302,6 +311,7 @@ async function inventoryChecksRoutes(fastify) {
completed_at: true,
created_at: true,
updated_at: true,
created_by: true,
items: {
select: {
id: true,
@@ -375,6 +385,7 @@ async function inventoryChecksRoutes(fastify) {
completed_at: true,
created_at: true,
updated_at: true,
created_by: true,
items: {
orderBy: [{ asset: { asset_no: "asc" } }],
select: {
@@ -505,6 +516,7 @@ async function inventoryChecksRoutes(fastify) {
},
async (request, reply) => {
const inventoryCheckId = parseUuid("id", request.params?.id);
const emailTasks = [];
const inventoryCheck = await fastify.prisma.$transaction(async (tx) => {
const current = await ensureInventoryCheck(tx, inventoryCheckId);
ensureCheckStatus(current, "counting");
@@ -526,6 +538,7 @@ async function inventoryChecksRoutes(fastify) {
completed_at: true,
created_at: true,
updated_at: true,
created_by: true,
items: {
orderBy: [{ asset: { asset_no: "asc" } }],
select: {
@@ -563,9 +576,56 @@ async function inventoryChecksRoutes(fastify) {
}),
});
const financeMgrRecipients = await resolveRecipientsForAssignee(tx, { assigneeRole: "finance_mgr" });
const recipients = uniq([updated.created_by, ...financeMgrRecipients]);
const title = `【盘点完成】盘点单 ${updated.check_no}`;
const bodyText = `盘点单 ${updated.check_no} 已完成,请在资产盘点中查看结果。`;
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.inventoryCheckCompleted,
title,
body: bodyText,
targetType: "inventory_check",
targetId: updated.id,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.inventoryCheckCompleted,
title,
body: bodyText,
targetType: "inventory_check",
targetId: updated.id,
targetPath: "/inventory-checks",
entityType: "inventory_check",
entityId: updated.id,
actorId: request.employee.id,
});
emailTasks.push({
type: NOTIFICATION_TYPES.inventoryCheckCompleted,
recipientEmployeeIds: recipients,
subject: title,
body: bodyText,
targetPath: "/inventory-checks",
});
return updated;
});
for (const task of emailTasks) {
void sendNotificationEmailSafe({
prisma: fastify.prisma,
config: fastify.config,
logger: fastify.log,
requestId: request.id,
...task,
});
}
return sendData(reply, request, { inventoryCheck: mapInventoryCheck(inventoryCheck) });
},
);
+19 -2
查看文件
@@ -14,6 +14,8 @@ const { issueDocumentNumber } = require("../services/documentSequence");
const { reserveBudgetForEntity, releaseReservedBudgetIfAny } = require("../services/purchaseBudget");
const { sendNotificationEmailSafe } = require("../services/email");
const { createNotifications, resolveRecipientsForAssignee } = require("../services/notifications");
const { enqueueImNotifications } = require("../services/notifications/imEnqueue");
const { NOTIFICATION_TYPES } = require("../constants/notificationTypes");
const { openReadStream, StorageNotFoundError, writeBuffer } = require("../services/storage");
const UUID_SCHEMA = z.string().uuid();
@@ -1294,15 +1296,30 @@ async function purchaseRequestRoutes(fastify) {
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: "workflow.task_assigned",
type: NOTIFICATION_TYPES.workflowTaskAssigned,
title,
body,
targetType: "workflow_task",
targetId: workflowTask.id,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.workflowTaskAssigned,
title,
body,
targetType: "workflow_task",
targetId: workflowTask.id,
targetPath: `/workflow/tasks/${workflowTask.id}`,
entityType: "purchase_request",
entityId: purchaseRequestId,
actorId: request.employee.id,
});
emailTasks.push({
type: "workflow.task_assigned",
type: NOTIFICATION_TYPES.workflowTaskAssigned,
recipientEmployeeIds: recipients,
subject: title,
body,
+36 -4
查看文件
@@ -8,6 +8,8 @@ const {
createNotifications,
resolveRecipientsForAssignee,
} = require("../services/notifications");
const { enqueueImNotifications } = require("../services/notifications/imEnqueue");
const { NOTIFICATION_TYPES } = require("../constants/notificationTypes");
const { sendNotificationEmailSafe } = require("../services/email");
const { enqueueIntegrationEvent } = require("../services/integrations/outbox");
const { buildErpPayload } = require("../services/integrations/erp");
@@ -1458,15 +1460,30 @@ async function reimbursementRoutes(fastify) {
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: "workflow.task_assigned",
type: NOTIFICATION_TYPES.workflowTaskAssigned,
title: `【待办】报销单 ${formNumber} 待审批`,
body: `报销单 ${formNumber} 已提交,请及时处理。`,
targetType: "workflow_task",
targetId: workflowTask.id,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.workflowTaskAssigned,
title: `【待办】报销单 ${formNumber} 待审批`,
body: `报销单 ${formNumber} 已提交,请及时处理。`,
targetType: "workflow_task",
targetId: workflowTask.id,
targetPath: `/workflow/tasks/${workflowTask.id}`,
entityType: "reimbursement",
entityId: reimbursementId,
actorId: request.employee.id,
});
emailTasks.push({
type: "workflow.task_assigned",
type: NOTIFICATION_TYPES.workflowTaskAssigned,
recipientEmployeeIds: recipients,
subject: `【待办】报销单 ${formNumber} 待审批`,
body: `报销单 ${formNumber} 已提交,请及时处理。`,
@@ -1799,15 +1816,30 @@ async function reimbursementRoutes(fastify) {
);
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: "reimbursement.paid",
type: NOTIFICATION_TYPES.reimbursementPaid,
title: `【已付款】报销单 ${reimbursement.form_number ?? reimbursementId}`,
body: `报销单 ${reimbursement.form_number ?? reimbursementId} 已完成付款。`,
targetType: "reimbursement_form",
targetId: reimbursementId,
});
await enqueueImNotifications(tx, {
config: fastify.config,
logger: fastify.log,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.reimbursementPaid,
title: `【已付款】报销单 ${reimbursement.form_number ?? reimbursementId}`,
body: `报销单 ${reimbursement.form_number ?? reimbursementId} 已完成付款。`,
targetType: "reimbursement_form",
targetId: reimbursementId,
targetPath: `/reimbursements/${reimbursementId}`,
entityType: "reimbursement",
entityId: reimbursementId,
actorId: request.employee.id,
});
emailTasks.push({
type: "reimbursement.paid",
type: NOTIFICATION_TYPES.reimbursementPaid,
recipientEmployeeIds: recipients,
subject: `【已付款】报销单 ${reimbursement.form_number ?? reimbursementId}`,
body: `报销单 ${reimbursement.form_number ?? reimbursementId} 已完成付款。`,
+262 -129
查看文件
@@ -9,7 +9,9 @@ const {
createNotifications,
resolveRecipientsForAssignee,
} = require("../services/notifications");
const { enqueueImNotifications } = require("../services/notifications/imEnqueue");
const { sendNotificationEmailSafe } = require("../services/email");
const { NOTIFICATION_TYPES } = require("../constants/notificationTypes");
const {
findActiveDelegationForDelegate,
listActiveDelegationPrincipals,
@@ -407,6 +409,201 @@ function buildReturnedCopy(entityMeta, comment) {
};
}
function uniq(values) {
return Array.from(new Set((values ?? []).filter(Boolean)));
}
async function loadLeaveNotifyContext(tx, leaveRequestId) {
return tx.leaveRequest.findUnique({
where: { id: leaveRequestId },
select: {
id: true,
owner_id: true,
},
});
}
async function loadPurchaseNotifyContext(tx, purchaseRequestId) {
return tx.purchaseRequest.findUnique({
where: { id: purchaseRequestId },
select: {
id: true,
request_no: true,
applicant_id: true,
submitter_id: true,
},
});
}
async function loadWorkflowNotifyContext(tx, entityType, entityId) {
const normalizedEntityType = entityType === 'procurement' ? 'purchase_request' : entityType;
if (normalizedEntityType === 'reimbursement') {
const record = await loadReimbursementNotifyContext(tx, entityId);
return {
record,
recipientEmployeeIds: uniq([record?.owner_id, record?.submitter_id]),
};
}
if (normalizedEntityType === 'leave') {
const record = await loadLeaveNotifyContext(tx, entityId);
return {
record,
recipientEmployeeIds: uniq([record?.owner_id]),
};
}
if (normalizedEntityType === 'purchase_request') {
const record = await loadPurchaseNotifyContext(tx, entityId);
return {
record,
recipientEmployeeIds: uniq([record?.applicant_id, record?.submitter_id]),
};
}
return {
record: null,
recipientEmployeeIds: [],
};
}
function resolveWorkflowOutcomeNotificationType(entityType, outcome) {
const normalizedEntityType = entityType === 'procurement' ? 'purchase_request' : entityType;
if (outcome === 'approved') {
if (normalizedEntityType === 'reimbursement') return NOTIFICATION_TYPES.reimbursementApproved;
if (normalizedEntityType === 'leave') return NOTIFICATION_TYPES.leaveApproved;
if (normalizedEntityType === 'purchase_request') return NOTIFICATION_TYPES.purchaseRequestApproved;
}
if (outcome === 'rejected') {
if (normalizedEntityType === 'reimbursement') return NOTIFICATION_TYPES.reimbursementRejected;
if (normalizedEntityType === 'leave') return NOTIFICATION_TYPES.leaveRejected;
if (normalizedEntityType === 'purchase_request') return NOTIFICATION_TYPES.purchaseRequestRejected;
}
if (outcome === 'returned') {
if (normalizedEntityType === 'reimbursement') return NOTIFICATION_TYPES.reimbursementReturned;
}
return null;
}
async function queueTaskAssignedNotifications({
tx,
config,
logger,
actorId,
emailTasks,
recipientEmployeeIds,
title,
body,
taskId,
entityType,
entityId,
}) {
const recipients = uniq(recipientEmployeeIds);
if (!recipients.length) {
return;
}
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.workflowTaskAssigned,
title,
body,
targetType: 'workflow_task',
targetId: taskId,
});
await enqueueImNotifications(tx, {
config,
logger,
recipientEmployeeIds: recipients,
type: NOTIFICATION_TYPES.workflowTaskAssigned,
title,
body,
targetType: 'workflow_task',
targetId: taskId,
targetPath: `/workflow/tasks/${taskId}`,
entityType,
entityId,
actorId,
});
emailTasks.push({
type: NOTIFICATION_TYPES.workflowTaskAssigned,
recipientEmployeeIds: recipients,
subject: title,
body,
targetPath: `/workflow/tasks/${taskId}`,
});
}
async function queueWorkflowOutcomeNotifications({
tx,
config,
logger,
actorId,
emailTasks,
workflowInstance,
outcome,
comment = null,
}) {
const normalizedEntityType = workflowInstance.entity_type === 'procurement' ? 'purchase_request' : workflowInstance.entity_type;
const notificationType = resolveWorkflowOutcomeNotificationType(normalizedEntityType, outcome);
if (!notificationType) {
return;
}
const context = await loadWorkflowNotifyContext(tx, normalizedEntityType, workflowInstance.entity_id);
const recipients = uniq(context.recipientEmployeeIds);
if (!recipients.length) {
return;
}
const entityMeta = getWorkflowEntityMeta(normalizedEntityType, context.record, workflowInstance.entity_id);
const copy =
outcome === 'approved'
? buildApprovedCopy(entityMeta)
: outcome === 'rejected'
? buildRejectedCopy(entityMeta, comment)
: buildReturnedCopy(entityMeta, comment);
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: notificationType,
title: copy.title,
body: copy.body,
targetType: entityMeta.targetType,
targetId: workflowInstance.entity_id,
});
await enqueueImNotifications(tx, {
config,
logger,
recipientEmployeeIds: recipients,
type: notificationType,
title: copy.title,
body: copy.body,
targetType: entityMeta.targetType,
targetId: workflowInstance.entity_id,
targetPath: entityMeta.detailPath,
entityType: normalizedEntityType,
entityId: workflowInstance.entity_id,
actorId,
});
emailTasks.push({
type: notificationType,
recipientEmployeeIds: recipients,
subject: copy.title,
body: copy.body,
targetPath: entityMeta.detailPath,
});
}
async function createSkipHistoryRecords(tx, workflowInstanceId, actorId, ownerId, skippedSteps) {
for (const skipped of skippedSteps) {
await tx.workflowHistory.create({
@@ -1069,21 +1266,18 @@ async function workflowRoutes(fastify) {
assigneeRole: actionable.assigneeRole,
});
await createNotifications(tx, {
await queueTaskAssignedNotifications({
tx,
config: fastify.config,
logger: fastify.log,
actorId: request.employee.id,
emailTasks,
recipientEmployeeIds: recipients,
type: "workflow.task_assigned",
title: pendingCopy.title,
body: pendingCopy.body,
targetType: "workflow_task",
targetId: nextTask.id,
});
emailTasks.push({
type: "workflow.task_assigned",
recipientEmployeeIds: recipients,
subject: pendingCopy.title,
body: pendingCopy.body,
targetPath: `/workflow/tasks/${nextTask.id}`,
taskId: nextTask.id,
entityType: workflowInstance.entity_type,
entityId: workflowInstance.entity_id,
});
} catch (error) {
fastify.log.error(
@@ -1197,41 +1391,21 @@ async function workflowRoutes(fastify) {
},
});
if (workflowInstance.entity_type === "reimbursement") {
try {
const reimbursement = await loadReimbursementNotifyContext(tx, workflowInstance.entity_id);
const entityMeta = getWorkflowEntityMeta(
workflowInstance.entity_type,
reimbursement,
workflowInstance.entity_id,
);
const approvedCopy = buildApprovedCopy(entityMeta);
const recipients = Array.from(
new Set([reimbursement?.owner_id, reimbursement?.submitter_id].filter(Boolean)),
);
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: "reimbursement.approved",
title: approvedCopy.title,
body: approvedCopy.body,
targetType: entityMeta.targetType,
targetId: workflowInstance.entity_id,
});
emailTasks.push({
type: "reimbursement.approved",
recipientEmployeeIds: recipients,
subject: approvedCopy.title,
body: approvedCopy.body,
targetPath: entityMeta.detailPath,
});
} catch (error) {
fastify.log.error(
{ err: error, taskId, reimbursementId: workflowInstance.entity_id },
"Failed to create reimbursement approved notifications",
);
}
try {
await queueWorkflowOutcomeNotifications({
tx,
config: fastify.config,
logger: fastify.log,
actorId: request.employee.id,
emailTasks,
workflowInstance,
outcome: 'approved',
});
} catch (error) {
fastify.log.error(
{ err: error, taskId, entityType: workflowInstance.entity_type, entityId: workflowInstance.entity_id },
"Failed to create approval outcome notifications",
);
}
result = {
@@ -1385,41 +1559,22 @@ async function workflowRoutes(fastify) {
},
});
if (workflowInstance.entity_type === "reimbursement") {
try {
const reimbursement = await loadReimbursementNotifyContext(tx, workflowInstance.entity_id);
const entityMeta = getWorkflowEntityMeta(
workflowInstance.entity_type,
reimbursement,
workflowInstance.entity_id,
);
const rejectedCopy = buildRejectedCopy(entityMeta, comment);
const recipients = Array.from(
new Set([reimbursement?.owner_id, reimbursement?.submitter_id].filter(Boolean)),
);
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: "reimbursement.rejected",
title: rejectedCopy.title,
body: rejectedCopy.body,
targetType: entityMeta.targetType,
targetId: workflowInstance.entity_id,
});
emailTasks.push({
type: "reimbursement.rejected",
recipientEmployeeIds: recipients,
subject: rejectedCopy.title,
body: rejectedCopy.body,
targetPath: entityMeta.detailPath,
});
} catch (error) {
fastify.log.error(
{ err: error, taskId, reimbursementId: workflowInstance.entity_id },
"Failed to create reimbursement rejected notifications",
);
}
try {
await queueWorkflowOutcomeNotifications({
tx,
config: fastify.config,
logger: fastify.log,
actorId: request.employee.id,
emailTasks,
workflowInstance,
outcome: 'rejected',
comment,
});
} catch (error) {
fastify.log.error(
{ err: error, taskId, entityType: workflowInstance.entity_type, entityId: workflowInstance.entity_id },
"Failed to create rejection outcome notifications",
);
}
result = {
@@ -1572,41 +1727,22 @@ async function workflowRoutes(fastify) {
},
});
if (workflowInstance.entity_type === "reimbursement") {
try {
const reimbursement = await loadReimbursementNotifyContext(tx, workflowInstance.entity_id);
const entityMeta = getWorkflowEntityMeta(
workflowInstance.entity_type,
reimbursement,
workflowInstance.entity_id,
);
const returnedCopy = buildReturnedCopy(entityMeta, comment);
const recipients = Array.from(
new Set([reimbursement?.owner_id, reimbursement?.submitter_id].filter(Boolean)),
);
await createNotifications(tx, {
recipientEmployeeIds: recipients,
type: "reimbursement.returned",
title: returnedCopy.title,
body: returnedCopy.body,
targetType: entityMeta.targetType,
targetId: workflowInstance.entity_id,
});
emailTasks.push({
type: "reimbursement.returned",
recipientEmployeeIds: recipients,
subject: returnedCopy.title,
body: returnedCopy.body,
targetPath: entityMeta.detailPath,
});
} catch (error) {
fastify.log.error(
{ err: error, taskId, reimbursementId: workflowInstance.entity_id },
"Failed to create reimbursement returned notifications",
);
}
try {
await queueWorkflowOutcomeNotifications({
tx,
config: fastify.config,
logger: fastify.log,
actorId: request.employee.id,
emailTasks,
workflowInstance,
outcome: 'returned',
comment,
});
} catch (error) {
fastify.log.error(
{ err: error, taskId, entityType: workflowInstance.entity_type, entityId: workflowInstance.entity_id },
"Failed to create return outcome notifications",
);
}
result = {
@@ -1719,21 +1855,18 @@ async function workflowRoutes(fastify) {
workflowInstance.entity_id,
);
const pendingCopy = buildPendingTaskCopy(entityMeta, { transfer: true });
await createNotifications(tx, {
await queueTaskAssignedNotifications({
tx,
config: fastify.config,
logger: fastify.log,
actorId: request.employee.id,
emailTasks,
recipientEmployeeIds: [toApproverId],
type: "workflow.task_assigned",
title: pendingCopy.title,
body: pendingCopy.body,
targetType: "workflow_task",
targetId: taskId,
});
emailTasks.push({
type: "workflow.task_assigned",
recipientEmployeeIds: [toApproverId],
subject: pendingCopy.title,
body: pendingCopy.body,
targetPath: `/workflow/tasks/${taskId}`,
taskId,
entityType: workflowInstance.entity_type,
entityId: workflowInstance.entity_id,
});
} catch (error) {
fastify.log.error(