fix(api): harden broadcast transactions and estimate fallbacks

This commit is contained in:
2026-03-30 12:18:10 +02:00
parent c82a146f84
commit 649c8feb22
4 changed files with 580 additions and 62 deletions
@@ -2231,6 +2231,59 @@ describe("assistant import/export and dispo tools", () => {
});
});
it("returns a stable assistant error when broadcast finalization loses the broadcast row", async () => {
const txCreateBroadcast = vi.fn().mockResolvedValue({
id: "broadcast_missing_after_create",
title: "Office update",
targetType: "all",
});
const txCreateNotification = vi.fn().mockResolvedValue({ id: "notification_2", userId: "user_2" });
const txUpdateBroadcast = vi.fn().mockRejectedValue(
Object.assign(new Error("Record to update not found"), {
code: "P2025",
meta: { modelName: "NotificationBroadcast" },
}),
);
const tx = {
notificationBroadcast: {
create: txCreateBroadcast,
update: txUpdateBroadcast,
},
notification: {
create: txCreateNotification,
},
};
const ctx = createToolContext(
{
user: {
findMany: vi.fn().mockResolvedValue([{ id: "user_2" }]),
},
$transaction: vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => callback(tx)),
notificationBroadcast: {
create: vi.fn(),
update: vi.fn(),
},
notification: {
create: vi.fn(),
},
},
{ userRole: SystemRole.MANAGER },
);
const result = await executeTool(
"send_broadcast",
JSON.stringify({
title: "Office update",
targetType: "all",
}),
ctx,
);
expect(JSON.parse(result.content)).toEqual({
error: "Broadcast not found with the given criteria.",
});
});
it("reads broadcast details through the real notification router and rejects plain users", async () => {
const db = {
notificationBroadcast: {
@@ -2830,6 +2883,84 @@ describe("assistant import/export and dispo tools", () => {
),
expected: "Estimate scope item not found with the given criteria.",
},
{
name: "update_estimate_draft missing project reference",
toolName: "update_estimate_draft",
payload: {
id: "est_project_missing",
baseCurrency: "EUR",
assumptions: [],
scopeItems: [],
demandLines: [],
resourceSnapshots: [],
metrics: [],
},
permission: PermissionKey.MANAGE_PROJECTS,
db: {
estimate: {
findUnique: vi.fn().mockResolvedValue({ projectId: null }),
},
},
setup: () => vi.mocked(updateEstimateDraft).mockRejectedValueOnce(
Object.assign(new Error("Foreign key constraint failed"), {
code: "P2003",
meta: { field_name: "Estimate_projectId_fkey" },
}),
),
expected: "Project not found with the given criteria.",
},
{
name: "update_estimate_draft missing role reference",
toolName: "update_estimate_draft",
payload: {
id: "est_role_missing",
baseCurrency: "EUR",
assumptions: [],
scopeItems: [],
demandLines: [],
resourceSnapshots: [],
metrics: [],
},
permission: PermissionKey.MANAGE_PROJECTS,
db: {
estimate: {
findUnique: vi.fn().mockResolvedValue({ projectId: null }),
},
},
setup: () => vi.mocked(updateEstimateDraft).mockRejectedValueOnce(
Object.assign(new Error("Foreign key constraint failed"), {
code: "P2003",
meta: { field_name: "EstimateDemandLine_roleId_fkey" },
}),
),
expected: "Role not found with the given criteria.",
},
{
name: "update_estimate_draft missing resource reference",
toolName: "update_estimate_draft",
payload: {
id: "est_resource_missing",
baseCurrency: "EUR",
assumptions: [],
scopeItems: [],
demandLines: [],
resourceSnapshots: [],
metrics: [],
},
permission: PermissionKey.MANAGE_PROJECTS,
db: {
estimate: {
findUnique: vi.fn().mockResolvedValue({ projectId: null }),
},
},
setup: () => vi.mocked(updateEstimateDraft).mockRejectedValueOnce(
Object.assign(new Error("Foreign key constraint failed"), {
code: "P2003",
meta: { field_name: "EstimateDemandLine_resourceId_fkey" },
}),
),
expected: "Resource not found with the given criteria.",
},
{
name: "update_estimate_draft generic missing estimate reference",
toolName: "update_estimate_draft",
@@ -2864,6 +2995,19 @@ describe("assistant import/export and dispo tools", () => {
setup: () => vi.mocked(submitEstimateVersion).mockRejectedValueOnce(new Error("Estimate version not found")),
expected: "Estimate version not found with the given criteria.",
},
{
name: "submit_estimate_version deleted version race",
toolName: "submit_estimate_version",
payload: { estimateId: "est_1", versionId: "ver_deleted" },
permission: PermissionKey.MANAGE_PROJECTS,
setup: () => vi.mocked(submitEstimateVersion).mockRejectedValueOnce(
Object.assign(new Error("Record to update not found"), {
code: "P2025",
meta: { modelName: "EstimateVersion" },
}),
),
expected: "Estimate version not found with the given criteria.",
},
{
name: "submit_estimate_version without working version",
toolName: "submit_estimate_version",
@@ -2888,6 +3032,19 @@ describe("assistant import/export and dispo tools", () => {
setup: () => vi.mocked(approveEstimateVersion).mockRejectedValueOnce(new Error("Estimate version not found")),
expected: "Estimate version not found with the given criteria.",
},
{
name: "approve_estimate_version deleted version race",
toolName: "approve_estimate_version",
payload: { estimateId: "est_1", versionId: "ver_deleted" },
permission: PermissionKey.MANAGE_PROJECTS,
setup: () => vi.mocked(approveEstimateVersion).mockRejectedValueOnce(
Object.assign(new Error("Record to update not found"), {
code: "P2025",
meta: { modelName: "EstimateVersion" },
}),
),
expected: "Estimate version not found with the given criteria.",
},
{
name: "approve_estimate_version without submitted version",
toolName: "approve_estimate_version",
@@ -2912,6 +3069,19 @@ describe("assistant import/export and dispo tools", () => {
setup: () => vi.mocked(createEstimateRevision).mockRejectedValueOnce(new Error("Estimate already has a working version")),
expected: "Estimate already has a working version.",
},
{
name: "create_estimate_revision deleted source version race",
toolName: "create_estimate_revision",
payload: { estimateId: "est_1", sourceVersionId: "ver_deleted" },
permission: PermissionKey.MANAGE_PROJECTS,
setup: () => vi.mocked(createEstimateRevision).mockRejectedValueOnce(
Object.assign(new Error("Record to update not found"), {
code: "P2025",
meta: { modelName: "EstimateVersion" },
}),
),
expected: "Estimate version not found with the given criteria.",
},
{
name: "create_estimate_revision with unlocked source version",
toolName: "create_estimate_revision",
@@ -2936,6 +3106,19 @@ describe("assistant import/export and dispo tools", () => {
setup: () => vi.mocked(createEstimateExport).mockRejectedValueOnce(new Error("Estimate version not found")),
expected: "Estimate version not found with the given criteria.",
},
{
name: "create_estimate_export deleted version race",
toolName: "create_estimate_export",
payload: { estimateId: "est_1", versionId: "ver_deleted", format: "XLSX" },
permission: PermissionKey.MANAGE_PROJECTS,
setup: () => vi.mocked(createEstimateExport).mockRejectedValueOnce(
Object.assign(new Error("Record to update not found"), {
code: "P2025",
meta: { modelName: "EstimateVersion" },
}),
),
expected: "Estimate version not found with the given criteria.",
},
{
name: "create_estimate_planning_handoff with missing linked project",
toolName: "create_estimate_planning_handoff",
@@ -3151,6 +3334,92 @@ describe("assistant import/export and dispo tools", () => {
});
});
it("returns a stable assistant error when commercial term persistence loses the working version", async () => {
const ctx = createToolContext(
{
estimate: {
findUnique: vi.fn().mockResolvedValue({
id: "est_1",
versions: [{ id: "ver_working", status: "WORKING" }],
}),
},
estimateVersion: {
update: vi.fn().mockRejectedValue({
code: "P2025",
message: "Record to update not found",
meta: { modelName: "EstimateVersion" },
}),
},
},
{
userRole: SystemRole.MANAGER,
permissions: [PermissionKey.MANAGE_PROJECTS],
},
);
const result = await executeTool(
"update_estimate_commercial_terms",
JSON.stringify({
estimateId: "est_1",
terms: {},
}),
ctx,
);
expect(JSON.parse(result.content)).toEqual({
error: "Estimate version not found with the given criteria.",
});
});
it("returns stable assistant errors for estimate weekly phasing and commercial term reads", async () => {
vi.mocked(getEstimateById).mockResolvedValueOnce(null as never);
const missingEstimateCtx = createToolContext({}, {
userRole: SystemRole.CONTROLLER,
});
const missingEstimateResult = await executeTool(
"get_estimate_weekly_phasing",
JSON.stringify({ estimateId: "est_missing" }),
missingEstimateCtx,
);
expect(JSON.parse(missingEstimateResult.content)).toEqual({
error: "Estimate not found with the given criteria.",
});
vi.mocked(getEstimateById).mockResolvedValueOnce({
id: "est_empty",
name: "Estimate Empty",
versions: [],
} as Awaited<ReturnType<typeof getEstimateById>>);
const noVersionResult = await executeTool(
"get_estimate_weekly_phasing",
JSON.stringify({ estimateId: "est_empty" }),
missingEstimateCtx,
);
expect(JSON.parse(noVersionResult.content)).toEqual({
error: "Estimate version not found with the given criteria.",
});
const missingCommercialTermsCtx = createToolContext(
{
estimate: {
findUnique: vi.fn().mockResolvedValue(null),
},
},
{
userRole: SystemRole.CONTROLLER,
},
);
const missingCommercialTermsResult = await executeTool(
"get_estimate_commercial_terms",
JSON.stringify({ estimateId: "est_missing" }),
missingCommercialTermsCtx,
);
expect(JSON.parse(missingCommercialTermsResult.content)).toEqual({
error: "Estimate version not found with the given criteria.",
});
});
it("reads countries through the real country router identifier path", async () => {
const db = {
country: {