From 8f2d179b72bce905c7085d7934aee371ac0edb15 Mon Sep 17 00:00:00 2001 From: RichardBray Date: Tue, 25 Jul 2023 15:54:34 +0100 Subject: [PATCH] chore: add emailType to prisma queries --- .../workers/helpers/addReminderEvent.ts | 13 +- .../helpers.ts | 6 +- .../processListsBeforeAndDuringStart/main.ts | 34 ++- .../day/sendUnpublishProviderConfirmation.ts | 18 +- .../addDayBeforePostReminderAudit.ts | 9 +- .../dayBefore/sendDayBeforePostReminder.ts | 15 +- .../sendDayBeforeProviderReminder.ts | 18 +- .../unpublish/weekly/sendUnpublishReminder.ts | 18 +- .../components/annual-review/controller.ts | 2 +- .../dashboard/listsItems/helpers.ts | 7 +- .../update/actionHandlers/requestChanges.ts | 2 +- .../controllers/ingest/ingestPutController.ts | 2 +- .../migration.sql | 10 +- src/server/models/db/schema.prisma | 6 +- src/server/models/listItem/listItem.ts | 2 +- .../listItemCreateInputFromWebhook.ts | 2 +- src/server/models/listItem/listItemEvent.ts | 202 ------------------ src/shared/listItemEvent.ts | 24 ++- 18 files changed, 102 insertions(+), 288 deletions(-) delete mode 100644 src/server/models/listItem/listItemEvent.ts diff --git a/src/scheduler/workers/helpers/addReminderEvent.ts b/src/scheduler/workers/helpers/addReminderEvent.ts index 2314f906b..6341f65d7 100644 --- a/src/scheduler/workers/helpers/addReminderEvent.ts +++ b/src/scheduler/workers/helpers/addReminderEvent.ts @@ -1,15 +1,24 @@ +import type { ProviderEmailType } from "@prisma/client"; import type { SendEmailResponse } from "notifications-node-client"; import { prisma } from "scheduler/prismaClient"; import { EVENTS } from "shared/listItemEvent"; -export async function addReminderEvent(id: number, response: SendEmailResponse, notes?: string[], reference?: string) { +interface AddReminderEventInput { + id: number; + response: SendEmailResponse; + notes?: string[]; + reference?: string; + emailType: ProviderEmailType; +} + +export async function addReminderEvent({ id, response, notes, reference, emailType }: AddReminderEventInput) { return await prisma.listItem.update({ where: { id, }, data: { history: { - create: EVENTS.REMINDER(response, notes, reference), + create: EVENTS.REMINDER({ response, notes, reference, emailType }), }, }, }); diff --git a/src/scheduler/workers/processListsBeforeAndDuringStart/helpers.ts b/src/scheduler/workers/processListsBeforeAndDuringStart/helpers.ts index 81dff45c6..c215d2b5f 100644 --- a/src/scheduler/workers/processListsBeforeAndDuringStart/helpers.ts +++ b/src/scheduler/workers/processListsBeforeAndDuringStart/helpers.ts @@ -18,7 +18,7 @@ export function isEmailSentBefore( event: Event | Audit | undefined, reminderType: ListAnnualReviewPostReminderType | ListItemAnnualReviewProviderReminderType ): boolean { - if (!event?.jsonData) { + if (!event?.jsonData || !reminderType) { return false; } const subsequentEmailsForReminderType = { @@ -36,9 +36,9 @@ export function isEmailSentBefore( const subsequentEmails: string[] = subsequentEmailsForReminderType[reminderType]; let reminderHasBeenSent = false; if ("createdAt" in event) { - reminderHasBeenSent = subsequentEmails?.includes?.((event.jsonData as ListEventJsonData)?.reminderType as string); + reminderHasBeenSent = subsequentEmails.includes((event.jsonData as ListEventJsonData)?.reminderType as string); } else { - reminderHasBeenSent = subsequentEmails?.includes?.((event.jsonData as Record)?.notes[0]); + reminderHasBeenSent = subsequentEmails.includes((event.jsonData as Record)?.notes[0]); } if (reminderHasBeenSent) { diff --git a/src/scheduler/workers/processListsBeforeAndDuringStart/main.ts b/src/scheduler/workers/processListsBeforeAndDuringStart/main.ts index 3cb9ba2a2..b1e370c56 100644 --- a/src/scheduler/workers/processListsBeforeAndDuringStart/main.ts +++ b/src/scheduler/workers/processListsBeforeAndDuringStart/main.ts @@ -1,18 +1,13 @@ import { endOfDay, isSameDay, isWithinInterval, startOfDay, subDays } from "date-fns"; import { lowerCase, startCase } from "lodash"; -import { AuditEvent, ListItemEvent } from "@prisma/client"; +import { AuditEvent, ListItemEvent, PostEmailType, ProviderEmailType } from "@prisma/client"; import type { Event, Audit } from "@prisma/client"; import { prisma } from "scheduler/prismaClient"; import type { SendEmailResponse } from "notifications-node-client"; import { findListItems, findListsWithCurrentAnnualReview, updateIsAnnualReview } from "scheduler/dbHelpers"; import { logger } from "scheduler/logger"; -import type { - List, - ListAnnualReviewPostReminderType, - ListItemAnnualReviewProviderReminderType, - ListItemWithHistory, -} from "shared/types"; +import type { List, ListItemWithHistory } from "shared/types"; import type { MilestoneTillAnnualReview } from "../../batch/helpers"; import { formatDate, isEmailSentBefore } from "./helpers"; import { createAnnualReviewProviderUrl } from "scheduler/workers/createAnnualReviewProviderUrl"; @@ -27,7 +22,7 @@ import { addReminderEvent } from "../helpers/addReminderEvent"; async function processPostEmailsForList( list: List, milestoneTillAnnualReview: MilestoneTillAnnualReview, - reminderType: ListAnnualReviewPostReminderType | ListItemAnnualReviewProviderReminderType + reminderType: PostEmailType ) { // Check if sent before if (!list.jsonData.users) { @@ -55,10 +50,10 @@ async function processPostEmailsForList( data: { auditEvent: AuditEvent.REMINDER, type: "list", + emailType: reminderType, jsonData: { eventName: "reminder", annualReviewRef: list.jsonData.currentAnnualReview?.reference, - reminderType, }, }, }); @@ -105,12 +100,13 @@ async function processProviderEmailsForListItems(list: List, listItems: ListItem const annualReviewReference = list.jsonData.currentAnnualReview?.reference; if (result) { - await addReminderEvent( - listItem.id, - result as SendEmailResponse, - ["sendStartedProviderEmail"], - annualReviewReference - ); + await addReminderEvent({ + id: listItem.id, + response: result as SendEmailResponse, + notes: ["sendStartedProviderEmail"], + reference: annualReviewReference, + emailType: ProviderEmailType.sendStartedProviderEmail, + }); } } } @@ -167,7 +163,7 @@ export async function processList(list: List, listItemsForList: ListItemWithHist ) { isEmailSent = isEmailSentBefore(latestAudit as Audit, "sendOneMonthPostEmail"); if (!isEmailSent) { - await processPostEmailsForList(list, "POST_ONE_MONTH", "sendOneMonthPostEmail"); + await processPostEmailsForList(list, "POST_ONE_MONTH", PostEmailType.sendOneMonthPostEmail); } return; } @@ -179,14 +175,14 @@ export async function processList(list: List, listItemsForList: ListItemWithHist ) { isEmailSent = isEmailSentBefore(latestAudit as Audit, "sendOneWeekPostEmail"); if (!isEmailSent) { - await processPostEmailsForList(list, "POST_ONE_WEEK", "sendOneWeekPostEmail"); + await processPostEmailsForList(list, "POST_ONE_WEEK", PostEmailType.sendOneWeekPostEmail); } return; } if (isSameDay(today, new Date(annualReviewKeyDates?.POST_ONE_DAY ?? ""))) { isEmailSent = isEmailSentBefore(latestAudit as Audit, "sendOneDayPostEmail"); if (!isEmailSent) { - await processPostEmailsForList(list, "POST_ONE_DAY", "sendOneDayPostEmail"); + await processPostEmailsForList(list, "POST_ONE_DAY", PostEmailType.sendOneDayPostEmail); } return; } @@ -194,7 +190,7 @@ export async function processList(list: List, listItemsForList: ListItemWithHist // email posts to notify of annual review start isEmailSent = isEmailSentBefore(latestAudit as Audit, "sendStartedPostEmail"); if (!isEmailSent) { - await processPostEmailsForList(list, "START", "sendStartedPostEmail"); + await processPostEmailsForList(list, "START", PostEmailType.sendStartedPostEmail); } // update ListItem.isAnnualReview if today = the START milestone date diff --git a/src/scheduler/workers/unpublish/day/sendUnpublishProviderConfirmation.ts b/src/scheduler/workers/unpublish/day/sendUnpublishProviderConfirmation.ts index bd6852fbc..bb02ca4b1 100644 --- a/src/scheduler/workers/unpublish/day/sendUnpublishProviderConfirmation.ts +++ b/src/scheduler/workers/unpublish/day/sendUnpublishProviderConfirmation.ts @@ -1,10 +1,10 @@ import { ListItemJsonData } from "server/models/listItem/providers/deserialisers/types"; import { schedulerLogger } from "scheduler/logger"; -import { NotifyClient, RequestError } from "notifications-node-client"; +import { NotifyClient, RequestError, SendEmailResponse } from "notifications-node-client"; import { NOTIFY } from "server/config"; import { Meta } from "./types"; import { providerReminderPersonalisation } from "./dayReminderPersonalisation"; -import { ListItem } from "@prisma/client"; +import { ListItem, ProviderEmailType } from "@prisma/client"; import { addReminderEvent } from "scheduler/workers/helpers/addReminderEvent"; const template = NOTIFY.templates.unpublishNotice.providerUnpublished; @@ -30,13 +30,13 @@ export async function sendUnpublishProviderConfirmation(listItem: ListItem, meta reference: meta.reference, }); - const event = await addReminderEvent( - listItem.id, - // @ts-ignore - error responses are thrown, so ts-ignoring ErrorResponse warning - response.data, - [`sent reminder for ${meta.daysUntilUnpublish} days until unpublish`], - meta.reference - ); + const event = await addReminderEvent({ + id: listItem.id, + response: response.data as SendEmailResponse, + notes: [`sent reminder for ${meta.daysUntilUnpublish} days until unpublish`], + reference: meta.reference, + emailType: ProviderEmailType.sendUnpublishedProviderEmail, + }); if (!event) { logger.error( diff --git a/src/scheduler/workers/unpublish/dayBefore/addDayBeforePostReminderAudit.ts b/src/scheduler/workers/unpublish/dayBefore/addDayBeforePostReminderAudit.ts index 1005ba8a1..aacc808eb 100644 --- a/src/scheduler/workers/unpublish/dayBefore/addDayBeforePostReminderAudit.ts +++ b/src/scheduler/workers/unpublish/dayBefore/addDayBeforePostReminderAudit.ts @@ -1,11 +1,16 @@ import { prisma } from "scheduler/prismaClient"; import type { AuditCreateInput, ListEventJsonData } from "server/models/types"; -import type { AuditEvent } from "@prisma/client"; +import type { AuditEvent, PostEmailType } from "@prisma/client"; -export async function addUnpublishPostReminderAudit(eventData: ListEventJsonData, auditEvent: AuditEvent) { +export async function addUnpublishPostReminderAudit( + eventData: ListEventJsonData, + auditEvent: AuditEvent, + emailType: PostEmailType +) { const data: AuditCreateInput = { auditEvent, type: "list", + emailType, jsonData: { ...eventData }, }; diff --git a/src/scheduler/workers/unpublish/dayBefore/sendDayBeforePostReminder.ts b/src/scheduler/workers/unpublish/dayBefore/sendDayBeforePostReminder.ts index ffa386755..628bdfd36 100644 --- a/src/scheduler/workers/unpublish/dayBefore/sendDayBeforePostReminder.ts +++ b/src/scheduler/workers/unpublish/dayBefore/sendDayBeforePostReminder.ts @@ -1,10 +1,13 @@ import { schedulerLogger } from "scheduler/logger"; -import { NotifyClient, RequestError } from "notifications-node-client"; +import { NotifyClient } from "notifications-node-client"; import { NOTIFY } from "server/config"; import { postReminderPersonalisation } from "./dayBeforeReminderPersonalisation"; -import { AuditEvent, List } from "@prisma/client"; +import { AuditEvent, PostEmailType } from "@prisma/client"; import { addUnpublishPostReminderAudit } from "./addDayBeforePostReminderAudit"; -import { Meta } from "./types"; + +import type { Meta } from "./types"; +import type { List } from "@prisma/client"; +import type { RequestError } from "notifications-node-client"; const template = NOTIFY.templates.unpublishNotice.postOneDay; @@ -34,17 +37,17 @@ export async function sendDayBeforePostReminder( const updateAudit = await addUnpublishPostReminderAudit( { - reminderType: "sendUnpublishOneDayPostEmail", eventName: "reminder", itemId: list.id, annualReviewRef: meta.reference, }, - AuditEvent.REMINDER + AuditEvent.REMINDER, + PostEmailType.sendUnpublishOneDayPostEmail ); if (!updateAudit) { logger.error( - `failed to add npublish reminder event for annual review ${meta.reference}. This email will be sent again at the next scheduled run unless an event is created.` + `failed to add publish reminder event for annual review ${meta.reference}. This email will be sent again at the next scheduled run unless an event is created.` ); } diff --git a/src/scheduler/workers/unpublish/dayBefore/sendDayBeforeProviderReminder.ts b/src/scheduler/workers/unpublish/dayBefore/sendDayBeforeProviderReminder.ts index 7ac2529c6..fab692c3c 100644 --- a/src/scheduler/workers/unpublish/dayBefore/sendDayBeforeProviderReminder.ts +++ b/src/scheduler/workers/unpublish/dayBefore/sendDayBeforeProviderReminder.ts @@ -1,9 +1,9 @@ import { ListItemJsonData } from "server/models/listItem/providers/deserialisers/types"; import { schedulerLogger } from "scheduler/logger"; -import { NotifyClient, RequestError } from "notifications-node-client"; +import { NotifyClient, RequestError, SendEmailResponse } from "notifications-node-client"; import { NOTIFY } from "server/config"; import { providerReminderPersonalisation } from "./dayBeforeReminderPersonalisation"; -import { ListItem } from "@prisma/client"; +import { ListItem, ProviderEmailType } from "@prisma/client"; import { Meta } from "./types"; import { addReminderEvent } from "scheduler/workers/helpers/addReminderEvent"; @@ -31,13 +31,13 @@ export async function sendDayBeforeProviderReminder(listItem: ListItem, meta: Me reference: meta.reference, }); - const event = await addReminderEvent( - listItem.id, - // @ts-ignore - error responses are thrown, so ts-ignoring ErrorResponse warning - response.data, - [`sent reminder for ${meta.daysUntilUnpublish} days until unpublish`], - meta.reference - ); + const event = await addReminderEvent({ + id: listItem.id, + response: response.data as SendEmailResponse, + notes: [`sent reminder for ${meta.daysUntilUnpublish} days until unpublish`], + reference: meta.reference, + emailType: ProviderEmailType.sendUnpublishOneDayProviderEmail, + }); if (!event) { logger.error( diff --git a/src/scheduler/workers/unpublish/weekly/sendUnpublishReminder.ts b/src/scheduler/workers/unpublish/weekly/sendUnpublishReminder.ts index 6c86bed23..a6ff8948a 100644 --- a/src/scheduler/workers/unpublish/weekly/sendUnpublishReminder.ts +++ b/src/scheduler/workers/unpublish/weekly/sendUnpublishReminder.ts @@ -1,9 +1,9 @@ import { ListItemJsonData } from "server/models/listItem/providers/deserialisers/types"; import { schedulerLogger } from "scheduler/logger"; -import { NotifyClient, RequestError } from "notifications-node-client"; +import { NotifyClient, RequestError, SendEmailResponse } from "notifications-node-client"; import { NOTIFY } from "server/config"; import { weeklyReminderPersonalisation } from "./weeklyReminderPersonalisation"; -import { ListItem } from "@prisma/client"; +import { ListItem, ProviderEmailType } from "@prisma/client"; import { Meta } from "./types"; import { addReminderEvent } from "scheduler/workers/helpers/addReminderEvent"; @@ -30,13 +30,13 @@ export async function sendUnpublishReminder(listItem: ListItem, meta: Meta) { reference: meta.reference, }); - const event = await addReminderEvent( - listItem.id, - // @ts-ignore - error responses are thrown, so ts-ignoring ErrorResponse warning - response.data, - [`sent reminder for week ${meta.weeksSinceStart}. (${meta.weeksUntilUnpublish} until unpublish date)`], - meta.reference - ); + const event = await addReminderEvent({ + id: listItem.id, + response: response.data as SendEmailResponse, + notes: [`sent reminder for week ${meta.weeksSinceStart}. (${meta.weeksUntilUnpublish} until unpublish date)`], + reference: meta.reference, + emailType: ProviderEmailType.sendUnpublishWeeklyProviderEmail, + }); if (!event) { logger.error( diff --git a/src/server/components/annual-review/controller.ts b/src/server/components/annual-review/controller.ts index ad4e3b2ae..2539a0ac9 100644 --- a/src/server/components/annual-review/controller.ts +++ b/src/server/components/annual-review/controller.ts @@ -11,7 +11,7 @@ import { prisma } from "server/models/db/prisma-client"; import { logger } from "server/services/logger"; import type { ListItemGetObject, List, ListJsonData } from "server/models/types"; -import { EVENTS } from "server/models/listItem/listItemEvent"; +import { EVENTS } from "shared/listItemEvent"; import { initialiseFormRunnerSession } from "server/components/formRunner/helpers"; import { sendAnnualReviewCompletedEmailForList } from "server/components/annual-review/helpers"; import type { ListWithJsonData } from "server/components/dashboard/helpers"; diff --git a/src/server/components/dashboard/listsItems/helpers.ts b/src/server/components/dashboard/listsItems/helpers.ts index 3acabd749..889ade720 100644 --- a/src/server/components/dashboard/listsItems/helpers.ts +++ b/src/server/components/dashboard/listsItems/helpers.ts @@ -1,12 +1,11 @@ import { logger } from "server/services/logger"; - -import type { NextFunction, Request } from "express"; import { HttpException } from "server/middlewares/error-handlers"; import { prisma } from "server/models/db/prisma-client"; import type { ListItemRes } from "server/components/dashboard/listsItems/types"; import type { ListItem, User } from "server/models/types"; -import { ServiceType } from "shared/types"; -import { EVENTS } from "server/models/listItem/listItemEvent"; +import type { ServiceType } from "shared/types"; +import type { NextFunction, Request } from "express"; +import { EVENTS } from "shared/listItemEvent"; /** * TODO:- this does not redirect, just next(err) which renders diff --git a/src/server/components/dashboard/listsItems/item/update/actionHandlers/requestChanges.ts b/src/server/components/dashboard/listsItems/item/update/actionHandlers/requestChanges.ts index 98aee5e50..da92d1c6f 100644 --- a/src/server/components/dashboard/listsItems/item/update/actionHandlers/requestChanges.ts +++ b/src/server/components/dashboard/listsItems/item/update/actionHandlers/requestChanges.ts @@ -5,7 +5,7 @@ import serviceName from "server/utils/service-name"; import { sendEditDetailsEmail } from "server/services/govuk-notify"; import { Status } from "@prisma/client"; import { prisma } from "server/models/db/prisma-client"; -import { EVENTS } from "server/models/listItem/listItemEvent"; +import { EVENTS } from "shared/listItemEvent"; import type { ListItemGetObject, User } from "server/models/types"; import type { ListItemRes } from "server/components/dashboard/listsItems/types"; diff --git a/src/server/components/lists/controllers/ingest/ingestPutController.ts b/src/server/components/lists/controllers/ingest/ingestPutController.ts index fd9e99dc6..bd40e60eb 100644 --- a/src/server/components/lists/controllers/ingest/ingestPutController.ts +++ b/src/server/components/lists/controllers/ingest/ingestPutController.ts @@ -6,7 +6,7 @@ import { Status } from "@prisma/client"; import { ServiceType } from "shared/types"; import { deserialise } from "server/models/listItem/listItemCreateInputFromWebhook"; import { getServiceTypeName } from "server/components/lists/helpers"; -import { EVENTS } from "server/models/listItem/listItemEvent"; +import { EVENTS } from "shared/listItemEvent"; import { getObjectDiff } from "./helpers"; import { sendAnnualReviewCompletedEmailForList } from "server/components/annual-review/helpers"; import { sendManualActionNotificationToPost, sendProviderInformedOfEditEmail } from "server/services/govuk-notify"; diff --git a/src/server/models/db/migrations/20230725094906_add_email_type_columns_to_tables/migration.sql b/src/server/models/db/migrations/20230725094906_add_email_type_columns_to_tables/migration.sql index 1ef8ea384..797b3e4c5 100644 --- a/src/server/models/db/migrations/20230725094906_add_email_type_columns_to_tables/migration.sql +++ b/src/server/models/db/migrations/20230725094906_add_email_type_columns_to_tables/migration.sql @@ -7,8 +7,7 @@ CREATE TYPE "PostEmailType" AS ENUM ( 'sendOneDayPostEmail', 'sendStartedPostEmail', 'sendUnpublishOneDayPostEmail', - 'sendUnpublishWeeklyPostEmail', - 'undefined' + 'sendUnpublishWeeklyPostEmail' ); -- CreateEnum @@ -16,8 +15,7 @@ CREATE TYPE "ProviderEmailType" AS ENUM ( 'sendStartedProviderEmail', 'sendUnpublishedProviderEmail', 'sendUnpublishOneDayProviderEmail', - 'sendUnpublishWeeklyProviderEmail', - 'undefined' + 'sendUnpublishWeeklyProviderEmail' ); -- Alter Audit and Event Tables @@ -33,7 +31,7 @@ SET "emailType" = CASE WHEN a."jsonData" ->> 'reminderType' = 'sendStartedPostEmail' THEN 'sendStartedPostEmail'::"PostEmailType" WHEN a."jsonData" ->> 'reminderType' = 'sendUnpublishOneDayPostEmail' THEN 'sendUnpublishOneDayPostEmail'::"PostEmailType" WHEN a."jsonData" ->> 'reminderType' = 'sendUnpublishWeeklyPostEmail' THEN 'sendUnpublishWeeklyPostEmail'::"PostEmailType" - ELSE 'undefined'::"PostEmailType" + ELSE NULL END; UPDATE "Event" AS e @@ -42,7 +40,7 @@ SET "emailType" = CASE WHEN EXISTS (SELECT 1 FROM jsonb_array_elements_text(e."jsonData"->'notes') AS note WHERE note ILIKE 'sent reminder for week%') THEN 'sendUnpublishWeeklyProviderEmail'::"ProviderEmailType" WHEN EXISTS (SELECT 1 FROM jsonb_array_elements_text(e."jsonData"->'notes') AS note WHERE note ILIKE 'sent reminder for 1 days%') THEN 'sendUnpublishOneDayProviderEmail'::"ProviderEmailType" WHEN EXISTS (SELECT 1 FROM jsonb_array_elements_text(e."jsonData"->'notes') AS note WHERE note ILIKE 'sent reminder for 0 days%') THEN 'sendUnpublishedProviderEmail'::"ProviderEmailType" - ELSE 'undefined'::"ProviderEmailType" + ELSE NULL END; COMMIT; diff --git a/src/server/models/db/schema.prisma b/src/server/models/db/schema.prisma index 3e5bd8d21..9592b0814 100644 --- a/src/server/models/db/schema.prisma +++ b/src/server/models/db/schema.prisma @@ -106,7 +106,7 @@ model Audit { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - emailType PostEmailType @default(undefined) + emailType PostEmailType? type String? auditEvent AuditEvent @default(UNDEFINED) @@ -155,7 +155,7 @@ model Event { listItem ListItem? @relation(fields: [listItemId], references: [id], onDelete: Cascade, onUpdate: Cascade) listItemId Int type ListItemEvent - emailType ProviderEmailType @default(undefined) + emailType ProviderEmailType? jsonData Json @@index([time, listItemId]) @@ -215,7 +215,6 @@ enum PostEmailType { sendStartedPostEmail sendUnpublishOneDayPostEmail sendUnpublishWeeklyPostEmail - undefined } enum ProviderEmailType { @@ -223,5 +222,4 @@ enum ProviderEmailType { sendUnpublishedProviderEmail sendUnpublishOneDayProviderEmail sendUnpublishWeeklyProviderEmail - undefined } diff --git a/src/server/models/listItem/listItem.ts b/src/server/models/listItem/listItem.ts index 63c3f7bec..4c68eabf0 100644 --- a/src/server/models/listItem/listItem.ts +++ b/src/server/models/listItem/listItem.ts @@ -8,7 +8,7 @@ import { prisma } from "server/models/db/prisma-client"; import { logger } from "server/services/logger"; import { AuditEvent, Status } from "@prisma/client"; import { merge } from "lodash"; -import { EVENTS } from "./listItemEvent"; +import { EVENTS } from "shared/listItemEvent"; import { subMonths } from "date-fns"; import type { WebhookData } from "server/components/formRunner"; diff --git a/src/server/models/listItem/listItemCreateInputFromWebhook.ts b/src/server/models/listItem/listItemCreateInputFromWebhook.ts index f8a94c2aa..c417ee241 100644 --- a/src/server/models/listItem/listItemCreateInputFromWebhook.ts +++ b/src/server/models/listItem/listItemCreateInputFromWebhook.ts @@ -10,7 +10,7 @@ import { import { WebhookData } from "server/components/formRunner"; import { checkListItemExists } from "server/models/listItem/providers/helpers"; import { DeserialisedWebhookData } from "server/models/listItem/providers/deserialisers/types"; -import { EVENTS } from "./listItemEvent"; +import { EVENTS } from "shared/listItemEvent"; export function deserialise(webhook: WebhookData): DeserialisedWebhookData { const baseDeserialised = baseDeserialiser(webhook); diff --git a/src/server/models/listItem/listItemEvent.ts b/src/server/models/listItem/listItemEvent.ts deleted file mode 100644 index ce9839c1c..000000000 --- a/src/server/models/listItem/listItemEvent.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { prisma } from "server/models/db/prisma-client"; -import type { Prisma } from "@prisma/client"; -import { ListItemEvent } from "@prisma/client"; -import type { Event, EventCreateInput, EventJsonData } from "./types"; -import { logger } from "server/services/logger"; -import type { SendEmailResponse } from "notifications-node-client"; - -export type EventCreate = Prisma.EventCreateWithoutListItemInput & { type: E }; - -interface AnnualReviewAdditionalInfo { - reference: string; -} - -interface PostEditedAdditionalInfo { - isPostEdit: boolean; - userId: number; - note: string; -} - -type AdditionalEditedInfo = AnnualReviewAdditionalInfo | PostEditedAdditionalInfo; - -/** - * These are intended to be used during a nested write via Prisma.EventCreateWithoutListItemInput. - * You do not need to pass "connect" or "date". Connections are done automatically when doing a nested write. - * Date is now a defaulted field. - */ -export const EVENTS = { - // Completely new form - [ListItemEvent.NEW]: (): EventCreate<"NEW"> => ({ - type: ListItemEvent.NEW, - jsonData: { - eventName: "new", - }, - }), - - [ListItemEvent.PUBLISHED]: (userId: number): EventCreate<"PUBLISHED"> => ({ - type: ListItemEvent.PUBLISHED, - jsonData: { - eventName: "publish", - userId, - }, - }), - - [ListItemEvent.ARCHIVED]: (userId: number, reason: string): EventCreate<"ARCHIVED"> => ({ - type: ListItemEvent.ARCHIVED, - jsonData: { - eventName: "archived", - userId, - reason, - }, - }), - - [ListItemEvent.UNPUBLISHED]: (userId?: number, reference?: string): EventCreate<"UNPUBLISHED"> => ({ - type: ListItemEvent.UNPUBLISHED, - jsonData: { - eventName: "unpublish", - ...(userId && { userId }), - ...(reference && { reference }), - }, - }), - - [ListItemEvent.PINNED]: (userId: number): EventCreate<"PINNED"> => ({ - type: ListItemEvent.PINNED, - jsonData: { - eventName: "pin", - userId, - }, - }), - - [ListItemEvent.UNPINNED]: (userId: number): EventCreate<"UNPINNED"> => { - return { - type: ListItemEvent.UNPINNED, - jsonData: { - eventName: "unpin", - userId, - }, - }; - }, - - [ListItemEvent.DELETED]: (userId?: number, id?: number): EventCreate<"DELETED"> => ({ - type: ListItemEvent.DELETED, - ...(id && { listItemId: id }), - jsonData: { - eventName: "deleted", - ...(userId && { userId }), - }, - }), - - /** - * After post requests a change. - */ - [ListItemEvent.OUT_WITH_PROVIDER]: ( - userId: number, - requestedChanges: string, - reference?: string - ): EventCreate<"OUT_WITH_PROVIDER"> => ({ - type: ListItemEvent.OUT_WITH_PROVIDER, - jsonData: { - eventName: "requestChange", - userId, - requestedChanges, - ...{ reference }, - }, - }), - - /** - * After the provider makes the change - */ - [ListItemEvent.EDITED]: (updatedJsonData = {}, options?: AdditionalEditedInfo): EventCreate<"EDITED"> => { - let extraData = {}; - const DEFAULT_MESSAGE = "provider resubmitted with these updates"; - - if (options) { - const isPostEdit = "isPostEdit" in options; - extraData = isPostEdit - ? { isPostEdit: options.isPostEdit, userId: options.userId, notes: [options.note] } - : { reference: options.reference, notes: [] }; - } - - return { - type: ListItemEvent.EDITED, - jsonData: { - notes: [DEFAULT_MESSAGE], // will be overwritten by extraData if extraData.notes is present. - eventName: "edited", - updatedJsonData, - ...extraData, - }, - }; - }, - - [ListItemEvent.CHECK_ANNUAL_REVIEW]: ( - updatedJsonData = {}, - reference?: string - ): EventCreate<"CHECK_ANNUAL_REVIEW"> => ({ - type: ListItemEvent.CHECK_ANNUAL_REVIEW, - jsonData: { - notes: ["user submitted annual review with these updates"], - eventName: "check annual review", - updatedJsonData, - ...{ reference }, - }, - }), - - [ListItemEvent.ANNUAL_REVIEW_STARTED]: (reference?: string): EventCreate<"ANNUAL_REVIEW_STARTED"> => ({ - type: ListItemEvent.ANNUAL_REVIEW_STARTED, - jsonData: { - eventName: "annual review started", - ...{ reference }, - }, - }), - - [ListItemEvent.REMINDER]: ( - response: SendEmailResponse, - notes?: string[], - reference?: string - ): EventCreate<"REMINDER"> => { - const notifyResponseWithoutContent = { - id: response.id, - template: response.template, - }; - - return { - type: ListItemEvent.REMINDER, - // @ts-ignore -- issue is with response.Template, there is a tsc/prisma incompatibility - jsonData: { - eventName: "reminder", - ...{ notes }, - ...{ reference }, - response: notifyResponseWithoutContent, - }, - }; - }, - - [ListItemEvent.ANNUAL_REVIEW_OVERDUE]: (reference?: string): EventCreate<"ANNUAL_REVIEW_OVERDUE"> => ({ - type: ListItemEvent.ANNUAL_REVIEW_OVERDUE, - jsonData: { - eventName: "annual review overdue", - ...{ reference }, - }, - }), -}; - -export function recordEvent( - eventData: EventJsonData, - listItemId: number, - eventType: ListItemEvent -): Prisma.Prisma__EventClient { - logger.debug(`event type ${eventType} to record`); - const data: EventCreateInput = { - time: new Date(), - type: eventType, - jsonData: { ...eventData }, - listItem: { - connect: { - id: listItemId, - }, - }, - }; - logger.debug(`creating Event record with data [${JSON.stringify(data)}`); - - return prisma.event.create({ data }) as Prisma.Prisma__EventClient; -} diff --git a/src/shared/listItemEvent.ts b/src/shared/listItemEvent.ts index b2c86f15b..b0bb274c3 100644 --- a/src/shared/listItemEvent.ts +++ b/src/shared/listItemEvent.ts @@ -1,6 +1,6 @@ import type { SendEmailResponse } from "notifications-node-client"; import { ListItemEvent } from "@prisma/client"; -import type { Prisma } from "@prisma/client"; +import type { Prisma, ProviderEmailType } from "@prisma/client"; export type EventCreate = Prisma.EventCreateWithoutListItemInput & { type: E }; @@ -122,19 +122,20 @@ export const EVENTS = { }, }), - [ListItemEvent.REMINDER]: ( - response: SendEmailResponse, - notes?: string[], - reference?: string - ): EventCreate<"REMINDER"> => { + [ListItemEvent.REMINDER]: ({ + response, + notes, + reference, + emailType, + }: EventReminderInput): EventCreate<"REMINDER"> => { const notifyResponseWithoutContent = { id: response.id, - template: response.template, + template: response.template as unknown as Prisma.InputJsonObject, }; return { type: ListItemEvent.REMINDER, - // @ts-ignore -- issue is with response.Template, there is a tsc/prisma incompatibility + emailType, jsonData: { eventName: "reminder", ...{ notes }, @@ -152,3 +153,10 @@ export const EVENTS = { }, }), }; + +interface EventReminderInput { + response: SendEmailResponse; + notes?: string[]; + reference?: string; + emailType: ProviderEmailType; +}