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

feat(backend): logging events #244

Merged
merged 16 commits into from
Feb 19, 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
12 changes: 12 additions & 0 deletions backend/prisma/migrations/20240214083722_events/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- AlterTable
ALTER TABLE `ContactForm` MODIFY `email` VARCHAR(254) NOT NULL;

-- CreateTable
CREATE TABLE `Event` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`type` VARCHAR(100) NOT NULL,
`involvedEmail` VARCHAR(254) NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
9 changes: 8 additions & 1 deletion backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ model ContactForm {
id Int @id @default(autoincrement())
firstName String @db.VarChar(50)
lastName String @db.VarChar(50)
email String @db.VarChar(100)
email String @db.VarChar(254)
content String @db.VarChar(255)
createdAt DateTime @default(now())
brevoSuccess DateTime?
Expand All @@ -37,4 +37,11 @@ model NewsletterPreOptIn {
deletedAt DateTime?
brevoSuccessMail DateTime?
brevoSuccessList DateTime?
}

model Event {
id Int @id @default(autoincrement())
type String @db.VarChar(100)
involvedEmail String? @db.VarChar(254)
createdAt DateTime @default(now())
}
123 changes: 93 additions & 30 deletions backend/src/api/Brevo.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { randomBytes } from 'crypto'

import { TransactionalEmailsApi } from '@getbrevo/brevo'
import { ContactForm, NewsletterPreOptIn } from '@prisma/client'

import { CONFIG } from '#config/config'
import { prisma } from '#src/prisma'
Expand Down Expand Up @@ -61,17 +60,14 @@ jest.mock('@getbrevo/brevo', () => {

describe('Brevo', () => {
describe('sendContactEmails', () => {
let contactForm: ContactForm
const contactFormData = {
firstName: 'Bibi',
lastName: 'Bloxberg',
content: 'Hello DreamMall!',
email: 'bibi@bloxberg.de',
}
beforeEach(async () => {
await prisma.contactForm.deleteMany()
contactForm = await prisma.contactForm.create({
data: {
firstName: 'Bibi',
lastName: 'Bloxberg',
content: 'Hello DreamMall!',
email: 'bibi@bloxberg.de',
},
})
})

describe('brevo key given', () => {
Expand All @@ -92,15 +88,16 @@ describe('Brevo', () => {
})

it('does reject with error', async () => {
await expect(sendContactEmails(contactForm)).rejects.toStrictEqual({
await expect(sendContactEmails(contactFormData)).rejects.toStrictEqual({
response: {
statusCode: 400,
},
})
})

it('does not update the database', async () => {
const result: ContactForm[] = await prisma.contactForm.findMany()
it('has the contact form stored in the database without brevo success date', async () => {
await expect(sendContactEmails(contactFormData)).rejects.toBeTruthy()
const result = await prisma.contactForm.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand Down Expand Up @@ -129,7 +126,7 @@ describe('Brevo', () => {

beforeEach(async () => {
jest.clearAllMocks()
await sendContactEmails(contactForm)
await sendContactEmails(contactFormData)
})

it('calls TransactionalEmailsApi constructor', () => {
Expand All @@ -145,7 +142,8 @@ describe('Brevo', () => {
expect(mockSendTransacEmail).toHaveBeenCalledTimes(2)
})

it('sends email to admin', () => {
it('sends email to admin', async () => {
const contactForm = await prisma.contactForm.findFirst()
expect(mockSendTransacEmail).toHaveBeenCalledWith({
templateId: 1,
to: [
Expand All @@ -166,7 +164,8 @@ describe('Brevo', () => {
})
})

it('sends email to user', () => {
it('sends email to user', async () => {
const contactForm = await prisma.contactForm.findFirst()
expect(mockSendTransacEmail).toHaveBeenCalledWith({
templateId: 2,
to: [
Expand All @@ -187,8 +186,8 @@ describe('Brevo', () => {
})
})

it('does update the database', async () => {
const result: ContactForm[] = await prisma.contactForm.findMany()
it('has the contact form stored in the database with brevo success date', async () => {
const result = await prisma.contactForm.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand All @@ -212,7 +211,7 @@ describe('Brevo', () => {
beforeEach(async () => {
jest.clearAllMocks()
CONFIG.BREVO_KEY = undefined
await sendContactEmails(contactForm)
await sendContactEmails(contactFormData)
})

it('does not call sendSmtpEmail', () => {
Expand Down Expand Up @@ -275,7 +274,7 @@ describe('Brevo', () => {
})

it('creates database entry with brevoSuccessMail = null', async () => {
const result: NewsletterPreOptIn[] = await prisma.newsletterPreOptIn.findMany()
const result = await prisma.newsletterPreOptIn.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand Down Expand Up @@ -316,7 +315,7 @@ describe('Brevo', () => {
})

it('creates database entry with brevoSuccessMail = null', async () => {
const result: NewsletterPreOptIn[] = await prisma.newsletterPreOptIn.findMany()
const result = await prisma.newsletterPreOptIn.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand Down Expand Up @@ -390,7 +389,7 @@ describe('Brevo', () => {
})

it('creates database entry', async () => {
const result: NewsletterPreOptIn[] = await prisma.newsletterPreOptIn.findMany()
const result = await prisma.newsletterPreOptIn.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand Down Expand Up @@ -475,11 +474,27 @@ describe('Brevo', () => {
})

it('does not reject with error', async () => {
await expect(confirmNewsletter(code)).resolves.toStrictEqual(true)
await expect(confirmNewsletter(code)).resolves.toEqual({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id: expect.any(Number),
firstName: 'Peter',
lastName: 'Lustig',
email: 'peter@lustig.de',
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
code: expect.any(String),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
validTill: expect.any(Date),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
createdAt: expect.any(Date),
deletedAt: null,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
brevoSuccessMail: expect.any(Date),
brevoSuccessList: null,
})
})

it('does not update database entry', async () => {
const result: NewsletterPreOptIn[] = await prisma.newsletterPreOptIn.findMany()
const result = await prisma.newsletterPreOptIn.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand Down Expand Up @@ -513,11 +528,27 @@ describe('Brevo', () => {
})

it('does not reject with error', async () => {
await expect(confirmNewsletter(code)).resolves.toStrictEqual(true)
await expect(confirmNewsletter(code)).resolves.toEqual({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id: expect.any(Number),
firstName: 'Peter',
lastName: 'Lustig',
email: 'peter@lustig.de',
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
code: expect.any(String),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
validTill: expect.any(Date),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
createdAt: expect.any(Date),
deletedAt: null,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
brevoSuccessMail: expect.any(Date),
brevoSuccessList: null,
})
})

it('does not update database entry', async () => {
const result: NewsletterPreOptIn[] = await prisma.newsletterPreOptIn.findMany()
const result = await prisma.newsletterPreOptIn.findMany()
expect(result).toHaveLength(1)
expect(result).toEqual([
{
Expand Down Expand Up @@ -615,8 +646,24 @@ describe('Brevo', () => {
])
})

it('returns true', () => {
expect(result).toBe(true)
it('returns database entry', () => {
expect(result).toEqual({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id: expect.any(Number),
firstName: 'Peter',
lastName: 'Lustig',
email: 'peter@lustig.de',
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
code: expect.any(String),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
validTill: expect.any(Date),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
createdAt: expect.any(Date),
deletedAt: null,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
brevoSuccessMail: expect.any(Date),
brevoSuccessList: null,
})
})
})

Expand Down Expand Up @@ -733,8 +780,24 @@ describe('Brevo', () => {
])
})

it('returns true', () => {
expect(result).toBe(true)
it('returns database entry', () => {
expect(result).toEqual({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id: expect.any(Number),
firstName: 'Bibi',
lastName: 'Bloxberg',
email: 'peter@lustig.de',
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
code: expect.any(String),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
validTill: expect.any(Date),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
createdAt: expect.any(Date),
deletedAt: null,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
brevoSuccessMail: expect.any(Date),
brevoSuccessList: null,
})
})
})
})
Expand Down
23 changes: 17 additions & 6 deletions backend/src/api/Brevo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,25 @@ import {
TransactionalEmailsApi,
TransactionalEmailsApiApiKeys,
} from '@getbrevo/brevo'
import { ContactForm } from '@prisma/client'
import { NewsletterPreOptIn } from '@prisma/client'

import { CONFIG, CONFIG_CHECKS } from '#config/config'
import { ContactFormInput } from '#graphql/inputs/ContactFormInput'
import { prisma } from '#src/prisma'

export const sendContactEmails = async (
contactForm: ContactForm,
): Promise<Awaited<ReturnType<typeof apiInstance.sendTransacEmail>>[] | undefined> => {
export const sendContactEmails = async ({
firstName,
lastName,
email,
content,
}: ContactFormInput): Promise<
Awaited<ReturnType<typeof apiInstance.sendTransacEmail>>[] | undefined
> => {
// We save this wether config is correctly set or not
const contactForm = await prisma.contactForm.create({
data: { firstName, lastName, email, content },
})

if (!CONFIG_CHECKS.CONFIG_CHECK_BREVO_SEND_CONTACT(CONFIG)) {
return undefined
}
Expand Down Expand Up @@ -168,7 +179,7 @@ export const subscribeToNewsletter = async (
return true
}

export const confirmNewsletter = async (code: string): Promise<boolean> => {
export const confirmNewsletter = async (code: string): Promise<false | NewsletterPreOptIn> => {
if (!CONFIG_CHECKS.CONFIG_CHECK_BREVO_NEWSLETTER(CONFIG)) {
return false
}
Expand Down Expand Up @@ -218,5 +229,5 @@ export const confirmNewsletter = async (code: string): Promise<boolean> => {
// TODO: logging or event
}

return true
return optin
}
8 changes: 8 additions & 0 deletions backend/src/config/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const VALIDATION = {
MAX_CHARS_FIRST_NAME: 50,
MAX_CHARS_LAST_NAME: 50,
MAX_CHARS_EMAIL: 254,
MAX_CHARS_CONTENT: 255,
}

export { VALIDATION }
5 changes: 5 additions & 0 deletions backend/src/event/EVENT_CONTACTFORM_SEND.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Event } from './Event'
import { EventType } from './EventType'

export const EVENT_CONTACTFORM_SEND = (involvedEmail: string) =>
Event(EventType.CONTACTFORM_SEND, involvedEmail)
5 changes: 5 additions & 0 deletions backend/src/event/EVENT_NEWSLETTER_CONFIRM.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Event } from './Event'
import { EventType } from './EventType'

export const EVENT_NEWSLETTER_CONFIRM = (involvedEmail?: string) =>
Event(EventType.NEWSLETTER_CONFIRM, involvedEmail)
5 changes: 5 additions & 0 deletions backend/src/event/EVENT_NEWSLETTER_SUBSCRIBE.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Event } from './Event'
import { EventType } from './EventType'

export const EVENT_NEWSLETTER_SUBSCRIBE = (involvedEmail: string) =>
Event(EventType.NEWSLETTER_SUBSCRIBE, involvedEmail)
6 changes: 6 additions & 0 deletions backend/src/event/Event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { prisma } from '#src/prisma'

import { EventType } from './EventType'

export const Event = async (type: EventType, involvedEmail?: string) =>
await prisma.event.create({ data: { type, involvedEmail } })
5 changes: 5 additions & 0 deletions backend/src/event/EventType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export enum EventType {
CONTACTFORM_SEND = 'CONTACTFORM_SEND',
NEWSLETTER_CONFIRM = 'NEWSLETTER_CONFIRM',
NEWSLETTER_SUBSCRIBE = 'NEWSLETTER_SUBSCRIBE',
}
5 changes: 5 additions & 0 deletions backend/src/event/Events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// export { EventType } from './EventType'
// export { Event } from './Event'
export { EVENT_CONTACTFORM_SEND } from './EVENT_CONTACTFORM_SEND'
export { EVENT_NEWSLETTER_CONFIRM } from './EVENT_NEWSLETTER_CONFIRM'
export { EVENT_NEWSLETTER_SUBSCRIBE } from './EVENT_NEWSLETTER_SUBSCRIBE'
Loading
Loading