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: add emails endpoints #47

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
114 changes: 114 additions & 0 deletions app/controllers/emails_controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { HttpContext } from '@adonisjs/core/http'
import Email from '#models/email'
import Event from '#models/event'
import { emailsStoreValidator, emailsUpdateValidator } from '#validators/emails'

export default class EmailsController {
/**
* List emails for a specific event
*/
async index({ params, response }: HttpContext) {
const eventId = Number.parseInt(String(params.event_id), 10);

const emails = await Email.query().where('event_id', eventId);

const emailSummaries = await Promise.all(
emails.map(async (email) => {
const pendingCount = await email
.related('participants')
.query()
.wherePivot('status', 'pending')
.count('* as total');

const sentCount = await email
.related('participants')
.query()
.wherePivot('status', 'sent')
.count('* as total');

const failedCount = await email
.related('participants')
.query()
.wherePivot('status', 'failed')
.count('* as total');

return {
id: email.id,
name: email.name,
pending: Number(pendingCount[0]?.$extras?.total || 0),
sent: Number(sentCount[0]?.$extras?.total || 0),
failed: Number(failedCount[0]?.$extras?.total || 0),
};
})
);

return response.status(200).send(emailSummaries);
}

/**
* Show a specific email for a specific event
*/
async show({ params, response }: HttpContext) {

const emailId = Number.parseInt(String(params.id));
try {
const event = await Event.findOrFail(params.event_id);
const email = await event.related('emails').query().where('id', emailId).firstOrFail();

return response.status(200).send(email);
} catch (error) {
console.error('Error fetching email:', error);
return response.status(404).send({
message: 'Email not found'
});
}
}

/**
* Create email for a specific event
*/
async store({ params, request, response }: HttpContext) {
const eventId = Number(params.event_id);

try {
const event = await Event.findOrFail(eventId);
const data = await emailsStoreValidator.validate(request.all());
const email = await event.related('emails').create(data);

return response.status(201).send(email);
} catch (error) {
console.error('Error creating email:', error);
return response.status(400).send({
message: 'Failed to create email'
});
}
}

/**
* Update an email for a specific event
*/
async update({ params, request, response }: HttpContext) {
const emailId = Number(params.id)

const data = await emailsUpdateValidator.validate(request.all())

const email = await Email.findOrFail(emailId)
email.merge(data)
await email.save()

return response.status(200).send({ message: 'Email successfully updated.', email })
}

/**
* Delete an email for a specific event
*/
async destroy({ params, response }: HttpContext) {
const emailId = Number(params.id)

const email = await Email.findOrFail(emailId)
await email.related('participants').detach()
await email.delete()

return response.status(200).send({ message: 'Email successfully deleted.' })
}
}
45 changes: 21 additions & 24 deletions app/controllers/participants_controller.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,54 @@
import Participant from "#models/participant";
import {
participantsStoreValidator,
participantsUpdateValidator,
} from "#validators/participants";
import { HttpContext } from "@adonisjs/core/http";
import { HttpContext } from '@adonisjs/core/http'
import Participant from '#models/participant'
import { participantsStoreValidator, participantsUpdateValidator } from '#validators/participants'

export default class ParticipantsController {
/**
* @index
* @tag participants
* Display a list of resource
*/
async index(): Promise<Participant[]> {
const participants = await Participant.all();
return participants;
}

async index({response}: HttpContext) {
const participants = await Participant.all();
if (!participants) {
return response.status(404).send([]);
}
return participants;
}

/**
* @store
* @tag participants
* Handle form submission for the create action
*/

async store({ request, response }: HttpContext) {
const data = await participantsStoreValidator.validate(request.all());
const participant = await Participant.create(data);
return response.status(201).send(participant);
}

/**
* @show
* @tag participants
* Show individual record
*/
async show({ params }: HttpContext) {
return await Participant.findOrFail(params.id);
}
return await Participant.findOrFail(params.id);
}

/**
* @update
* @tag participants
* Edit individual record
*/
async update({ params, request }: HttpContext) {
const data = await participantsUpdateValidator.validate(request.all());
const participant = await Participant.findOrFail(params.id);
participant.merge(data);
await participant.save();
return { message: `Participant successfully updated.`, participant };
return {"message": `Participant successfully updated.`, participant};
}

/**
* @destroy
* @tag participants
* Delete record
*/
async destroy({ params }: HttpContext) {
const participant = await Participant.findOrFail(params.id);
await participant.delete();
return { message: `Participant successfully deleted.` };
return {"message": `Participant successfully deleted.`};
}
}
11 changes: 11 additions & 0 deletions app/models/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,15 @@ export default class Email extends BaseModel {
})

declare participants: ManyToMany<typeof Participant>;

public $extras: {
pending_count: number;
sent_count: number;
failed_count: number;
} = {
pending_count: 0,
sent_count: 0,
failed_count: 0,
};

}
4 changes: 4 additions & 0 deletions app/models/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { /*BelongsTo,*/ HasMany } from "@adonisjs/lucid/types/relations";
import { DateTime } from "luxon";

import Participant from "./participant.js";
import Email from "#models/email";

// import Admin from './Admin.ts';
// import Form from './Form.ts';
Expand Down Expand Up @@ -58,4 +59,7 @@ export default class Event extends BaseModel {

@hasMany(() => Participant)
declare participants: HasMany<typeof Participant>;

@hasMany(() => Email)
declare emails: HasMany<typeof Email>;
}
29 changes: 29 additions & 0 deletions app/validators/emails.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import vine from '@vinejs/vine';

export const emailsStoreValidator = vine.compile(
vine.object({
eventId: vine.number().optional(),
name: vine.string(),
content: vine.string(),
trigger: vine.enum(['participant_registered', 'form_filled', 'attribute_changed']),
triggerValue: vine
.string()
.optional()
.requiredWhen('trigger', '=', 'form_filled')
.requiredWhen('trigger', '=', 'attribute_changed')
})
);

export const emailsUpdateValidator = vine.compile(
vine.object({
eventId: vine.number().optional(),
name: vine.string().optional(),
content: vine.string().optional(),
trigger: vine.enum(['participant_registered', 'form_filled', 'attribute_changed']).optional(),
triggerValue: vine
.string()
.optional()
.requiredWhen('trigger', '=', 'form_filled')
.requiredWhen('trigger', '=', 'attribute_changed')
})
);
2 changes: 1 addition & 1 deletion database/migrations/1735547965570_create_emails_table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default class EmailsSchema extends BaseSchema {
table.text("name").notNullable();
table.text("content").notNullable();
table.text("trigger").notNullable();
table.text("trigger_value").notNullable();
table.text("trigger_value").nullable();
table.timestamps();
});
}
Expand Down
43 changes: 43 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"@adonisjs/core": "^6.14.1",
"@adonisjs/cors": "^2.2.1",
"@adonisjs/lucid": "^21.3.0",
"@outloud/adonis-autoswagger": "^1.8.7",
"@vinejs/vine": "^2.1.0",
"adonis-autoswagger": "^3.64.0",
"luxon": "^3.5.0",
Expand Down
7 changes: 7 additions & 0 deletions start/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const ParticipantsController = () => import("#controllers/participants_controlle
const AuthController = () => import("#controllers/auth_controller");
const PermissionsController = () => import("#controllers/permissions_controller");
const AdminsController = () => import("#controllers/admins_controller");
const EmailsController = () => import("#controllers/emails_controller");

router.get("/swagger", async () => {
return AutoSwagger.default.docs(router.toJSON(), swagger);
Expand All @@ -18,6 +19,12 @@ router.get("/docs", async () => {
return AutoSwagger.default.scalar("/swagger");
});

router
.group(() => {
router.resource("emails", EmailsController).apiOnly();
})
.prefix("api/v1/events/:event_id");

router
.group(() => {
router.resource("participants", ParticipantsController).apiOnly();
Expand Down