Skip to content

Commit

Permalink
chore: add emailType to prisma queries
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardBray committed Aug 16, 2023
1 parent eb7f672 commit 8f2d179
Show file tree
Hide file tree
Showing 18 changed files with 102 additions and 288 deletions.
13 changes: 11 additions & 2 deletions src/scheduler/workers/helpers/addReminderEvent.ts
Original file line number Diff line number Diff line change
@@ -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 }),
},
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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<string, string>)?.notes[0]);
reminderHasBeenSent = subsequentEmails.includes((event.jsonData as Record<string, string>)?.notes[0]);
}

if (reminderHasBeenSent) {
Expand Down
34 changes: 15 additions & 19 deletions src/scheduler/workers/processListsBeforeAndDuringStart/main.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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) {
Expand Down Expand Up @@ -55,10 +50,10 @@ async function processPostEmailsForList(
data: {
auditEvent: AuditEvent.REMINDER,
type: "list",
emailType: reminderType,
jsonData: {
eventName: "reminder",
annualReviewRef: list.jsonData.currentAnnualReview?.reference,
reminderType,
},
},
});
Expand Down Expand Up @@ -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,
});
}
}
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -179,22 +175,22 @@ 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;
}
if (isSameDay(new Date(annualReviewKeyDates?.START ?? ""), today)) {
// 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
@@ -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 },
};

Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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.`
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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(
Expand Down
18 changes: 9 additions & 9 deletions src/scheduler/workers/unpublish/weekly/sendUnpublishReminder.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion src/server/components/annual-review/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
7 changes: 3 additions & 4 deletions src/server/components/dashboard/listsItems/helpers.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@ CREATE TYPE "PostEmailType" AS ENUM (
'sendOneDayPostEmail',
'sendStartedPostEmail',
'sendUnpublishOneDayPostEmail',
'sendUnpublishWeeklyPostEmail',
'undefined'
'sendUnpublishWeeklyPostEmail'
);

-- CreateEnum
CREATE TYPE "ProviderEmailType" AS ENUM (
'sendStartedProviderEmail',
'sendUnpublishedProviderEmail',
'sendUnpublishOneDayProviderEmail',
'sendUnpublishWeeklyProviderEmail',
'undefined'
'sendUnpublishWeeklyProviderEmail'
);

-- Alter Audit and Event Tables
Expand All @@ -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
Expand All @@ -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;
Loading

0 comments on commit 8f2d179

Please sign in to comment.