Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Replace update with simple delete for removeDeliveryOption #4825

Merged
merged 4 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -348,20 +348,19 @@ export const sendResponsesToVault = async ({
}: {
id: string;
}): Promise<{
formRecord: FormRecord | null;
success?: boolean;
error?: string;
}> => {
try {
const { ability } = await authCheckAndThrow();

const response = await removeDeliveryOption(ability, formID);
if (!response) {
throw new Error(`Template API response was null. Request information: { ${formID} }`);
}
await removeDeliveryOption(ability, formID);

return { formRecord: response };
return {
success: true,
};
} catch (error) {
return { formRecord: null, error: (error as Error).message };
return { success: false, error: (error as Error).message };
}
};

Expand Down
6 changes: 0 additions & 6 deletions app/api/templates/[formID]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,6 @@ export const PUT = middleware(
return NextResponse.json(response);
} else if (sendResponsesToVault) {
const response = await removeDeliveryOption(ability, formID);
if (!response)
throw new Error(
`Template API response was null. Request information: method = ${
req.method
} ; query = ${JSON.stringify(props.params)} ; body = ${JSON.stringify(props.body)}`
);
return NextResponse.json(response);
}
throw new MalformedAPIRequest(
Expand Down
65 changes: 20 additions & 45 deletions lib/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1143,63 +1143,38 @@ export async function updateResponseDeliveryOption(
/**
* Remove DeliveryOption from template. Form responses will be sent to the Vault.
* @param formID The unique identifier of the form you want to modify
* @returns The updated form template or null if the record does not exist
* @returns void
*/
export async function removeDeliveryOption(
ability: UserAbility,
formID: string
): Promise<FormRecord | null> {
export async function removeDeliveryOption(ability: UserAbility, formID: string): Promise<void> {
try {
await authorization.canEditForm(ability, formID);

const updatedTemplate = await prisma.template
.update({
where: {
id: formID,
isPublished: false,
deliveryOption: {
isNot: null,
},
},
data: {
deliveryOption: {
delete: true,
},
},
select: {
id: true,
created_at: true,
updated_at: true,
name: true,
jsonConfig: true,
isPublished: true,
deliveryOption: true,
securityAttribute: true,
formPurpose: true,
publishReason: true,
publishFormType: true,
publishDesc: true,
},
})
.catch((e) => {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === "P2025") {
throw new TemplateAlreadyPublishedError();
}
}
return prismaErrors(e, null);
});
// Don't change delivery option if the form is published
const template = await prisma.template.findFirstOrThrow({
where: {
id: formID,
},
select: {
isPublished: true,
},
});

if (updatedTemplate === null) return updatedTemplate;
if (!template) throw new TemplateNotFoundError();

if (template.isPublished) throw new TemplateAlreadyPublishedError();

await prisma.deliveryOption.deleteMany({
where: {
templateId: formID,
},
});

logEvent(
ability.userID,
{ type: "Form", id: formID },
"ChangeDeliveryOption",
"Delivery Option set to the Vault"
);

return _parseTemplate(updatedTemplate);
} catch (e) {
if (e instanceof AccessControlError)
logEvent(
Expand Down
29 changes: 6 additions & 23 deletions lib/tests/templates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -522,37 +522,20 @@ describe("Template CRUD functions", () => {
});

it("Remove DeliveryOption from template", async () => {
(prismaMock.template.update as jest.MockedFunction<any>).mockResolvedValue(
buildPrismaResponse("formtestID", formConfiguration)
);
(prismaMock.template.findFirstOrThrow as jest.MockedFunction<any>).mockResolvedValue({
isPublished: false,
});

const updatedTemplate = await removeDeliveryOption(user1Ability, "formtestID");
await removeDeliveryOption(user1Ability, "formtestID");

expect(prismaMock.template.update).toHaveBeenCalledWith(
expect(prismaMock.deliveryOption.deleteMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
id: "formtestID",
isPublished: false,
deliveryOption: {
isNot: null,
},
},
data: {
deliveryOption: {
delete: true,
},
templateId: "formtestID",
},
})
);

expect(updatedTemplate).toEqual(
expect.objectContaining({
id: "formtestID",
form: formConfiguration,
isPublished: false,
securityAttribute: "Unclassified",
})
);
expect(mockedLogEvent).toHaveBeenCalledWith(
user1Ability.userID,
{ id: "formtestID", type: "Form" },
Expand Down
Loading