Compare commits

..

5 commits

Author SHA1 Message Date
Nathan Lamy
6213f3941c feat: count failed attempts 2025-08-21 11:39:14 +02:00
Nathan Lamy
169df9715e feat: send notifications on update 2025-08-21 10:49:56 +02:00
Nathan Lamy
7093b344ed feat: add radar chart 2025-08-20 18:18:03 +02:00
Nathan Lamy
fb00495840 feat: add back fetch route 2025-08-20 16:43:31 +02:00
Nathan Lamy
1d3728b48d feat: add grades & averages 2025-08-20 16:10:48 +02:00
8 changed files with 415 additions and 23 deletions

View file

@ -1,5 +1,6 @@
import Colle from '#models/colle'
import { ColleService } from '#services/colle_service'
import { NotificationService } from '#services/notification_service'
import { createColleValidator, createUpcomingCollesValidator } from '#validators/colle'
import { inject } from '@adonisjs/core'
import type { HttpContext } from '@adonisjs/core/http'
@ -8,7 +9,10 @@ import { DateTime } from 'luxon'
@inject()
export default class CollesController {
constructor(private service: ColleService) {}
constructor(
private service: ColleService,
private notificationService: NotificationService
) {}
async index({ request, response, auth }: HttpContext) {
const { startDate: rawStartDate } = request.qs()
@ -137,6 +141,7 @@ export default class CollesController {
// If it exists, update the existing colle
if (existing) {
// Merge the new data with the existing colle
const beforeColle = existing.serialize()
Object.assign(existing, colleData)
// Handle attachments if any
@ -161,6 +166,19 @@ export default class CollesController {
}
}
const afterColle = existing.serialize()
if (!beforeColle.grade && afterColle.grade) {
await this.notificationService.sendNotification('GRADE_ADDED', existing)
} else if (parseFloat(beforeColle.grade) !== afterColle.grade) {
await this.notificationService.sendNotification(
'GRADE_UPDATED',
existing,
parseFloat(beforeColle.grade)
)
}
if (!deepEqual(beforeColle, afterColle)) {
await this.notificationService.sendNotification('COLLE_UPDATED', existing)
}
return existing.save()
}
const colle = await Colle.create(colleData)
@ -226,25 +244,49 @@ export default class CollesController {
// Create a new colle if it doesn't exist
if (!oldColle) {
await Colle.create(updatedColle)
const colle = await Colle.create(updatedColle)
await this.notificationService.sendNotification('COLLE_ADDED', colle)
continue
}
// Update the colle with the new data
// and remove it from the list
const beforeColle = oldColle.serialize()
Object.assign(oldColle, updatedColle)
await oldColle.save()
const afterColle = oldColle.serialize()
upcomingCollesIds.delete(oldColle.id)
if (beforeColle.room !== afterColle.room) {
await this.notificationService.sendNotification('ROOM_UPDATED', oldColle)
} else if (!deepEqual(beforeColle, afterColle)) {
await this.notificationService.sendNotification('COLLE_UPDATED', oldColle)
}
}
// Delete the colles that were not updated
const deleted = await Colle.query()
.whereHas('student', (query) => {
query.where('className', payload.className)
const collesToDelete = await Promise.all(
Array.from(upcomingCollesIds).map((id) => {
return Colle.query()
.where('id', id)
.whereHas('student', (query) => {
query.where('className', payload.className)
})
.first()
})
.whereIn('id', Array.from(upcomingCollesIds))
.delete()
)
for (const colle of collesToDelete) {
if (colle) {
await this.notificationService.sendNotification('COLLE_REMOVED', colle)
await colle.delete()
}
}
console.log(`Deleted ${deleted} upcoming colles that were not updated`)
console.log(`Deleted ${collesToDelete.length} upcoming colles that were not updated`)
}
}
function deepEqual(a: any, b: any) {
return JSON.stringify(a) === JSON.stringify(b)
}

View file

@ -0,0 +1,58 @@
import { GradeService } from '#services/grade_service'
import { inject } from '@adonisjs/core'
import type { HttpContext } from '@adonisjs/core/http'
import { DateTime } from 'luxon'
const PERIODS = ['MONTH', 'TRIMESTER', 'YEAR']
@inject()
export default class GradesController {
constructor(private gradeService: GradeService) {}
// GET /grades
async index({ auth, request, response }: HttpContext) {
const period = request.input('period', PERIODS[0]).toUpperCase()
if (!PERIODS.includes(period)) {
return response.badRequest({
message: `Invalid period. Allowed values are: ${PERIODS.join(', ')}`,
})
}
// TODO: Choose a start date
// const { startDate: rawStartDate } = request.qs()
// Validate startDate
// const startDate = rawStartDate ? DateTime.fromISO(rawStartDate, { zone: 'local' }) : null
// if (!rawStartDate || !startDate || !startDate.isValid) {
// return response.badRequest({ message: 'Invalid start date format' })
// }
const userId = auth.user!.id
if (period === PERIODS[0]) {
const startDate = DateTime.now().minus({ month: 1 })
return this.gradeService.getMonthGrade(userId, startDate)
}
const months = period === PERIODS[1] ? 3 : 12
const startDate = DateTime.now().minus({ months })
return this.gradeService.getPeriodGrade(userId, startDate, months)
}
// GET /averages
async averages({ auth, request, response }: HttpContext) {
const period = request.input('period', PERIODS[0]).toUpperCase()
if (!PERIODS.includes(period)) {
return response.badRequest({
message: `Invalid period. Allowed values are: ${PERIODS.join(', ')}`,
})
}
const userId = auth.user!.id
if (period === PERIODS[0]) {
const startDate = DateTime.now().minus({ month: 1 })
return this.gradeService.getSubjectsAverages(userId, startDate, 1)
}
const months = period === PERIODS[1] ? 3 : 12
const startDate = DateTime.now().minus({ months })
return this.gradeService.getSubjectsAverages(userId, startDate, months)
}
}

View file

@ -0,0 +1,46 @@
import type { HttpContext } from '@adonisjs/core/http'
import redis from '@adonisjs/redis/services/main'
import { DateTime } from 'luxon'
export default class InternalsController {
// POST /internals/back-fetch
async backFetch({ response, request }: HttpContext) {
const className = request.input('className')
if (!className) {
return response.badRequest({ message: 'className is required' })
}
// Start a new thread to avoid blocking the event loop
response.send({
success: true,
message: `Fetching colles for class ${className}...`,
})
setImmediate(async () => {
await queue(className)
console.log(`Colles fetching for class ${className} completed.`)
})
}
}
async function queue(className: string) {
// 1er Septembre 2019 début de BJColle
const startDate = DateTime.fromISO('2019-09-01T00:00:00')
const endDate = DateTime.now()
let date = endDate
// Loop through all days from startDate to endDate
while (date >= startDate) {
await redis.publish(
'jobs_queue',
JSON.stringify({
type: 1, // Fetch day colles
// Format DD/MM/YYYY
date: date.toFormat('dd/MM/yyyy'),
class_name: className,
})
)
date = date.minus({ days: 1 })
// Wait for 1 second to avoid overwhelming the queue
await new Promise((resolve) => setTimeout(resolve, 1000))
}
}

View file

@ -24,7 +24,7 @@ export default class NotificationsController {
const device = this.service.getUserSignature(ua)
const data = await request.validateUsing(subscribeValidator)
await Subscription.create({
return Subscription.create({
userId: auth.user!.id,
device,
events: 0, // Default to no events

View file

@ -0,0 +1,185 @@
import Colle from '#models/colle'
import { DateTime } from 'luxon'
export class GradeService {
private calculateAverage(colles: Colle[]) {
const total = colles
.map((colle) => parseFloat(colle.grade?.toString()))
.filter(Boolean)
.reduce((sum, grade) => sum + grade, 0)
return (total / colles.length).toFixed(2)
}
private calculateSubjectAverage(colles: Colle[], subject: string) {
const subjectColles = colles.filter((colle) => colle.subject.name === subject && colle.grade)
return this.calculateAverage(subjectColles)
}
private getSubjects(colles: Colle[]) {
return Array.from(new Set(colles.map((colle) => colle.subject.name)))
}
private getPeriodColles(colles: Colle[], startDate: DateTime, endDate: DateTime) {
return colles.filter((colle) => colle.date >= startDate && colle.date < endDate)
}
public async getSubjectsAverages(userId: number, startDate: DateTime, months: number = 0) {
const colles = await this.getColles(userId, startDate, months)
const subjects = this.getSubjects(colles)
const subjectAverages: SubjectPerformance[] = []
for (const subject of subjects) {
const average = this.calculateSubjectAverage(colles, subject)
subjectAverages.push({ subject, average })
}
const globalAverage = this.calculateAverage(colles)
return {
globalAverage,
subjectAverages,
}
}
public getColles(userId: number, startDate: DateTime, months: number = 0) {
const endDate = startDate.plus({ months })
return Colle.query()
.where('studentId', userId)
.where('date', '>=', startDate.toJSDate())
.where('date', '<', endDate.toJSDate())
.preload('subject')
.orderBy('date', 'asc')
}
private async getGlobalAverage(userId: number, subjectId: number, beforeDate: DateTime) {
const colles = await Colle.query()
.where('studentId', userId)
.where('subjectId', subjectId)
.where('date', '<', beforeDate.toJSDate())
return colles.length ? this.calculateAverage(colles) : 0
}
public async getMonthGrade(userId: number, startDate: DateTime) {
const colles = await this.getColles(userId, startDate, 1)
const subjects = this.getSubjects(colles)
const results: any = []
let periodStartDate = startDate
for (let week = 1; week <= 4; week++) {
const periodEndDate = periodStartDate.plus({ weeks: 1 })
const periodColles = this.getPeriodColles(colles, periodStartDate, periodEndDate)
const periodAverage = this.calculateAverage(periodColles)
const subjectAverages = await this.getSubjectAverages(
subjects,
periodColles,
colles,
results,
week,
userId,
periodStartDate
)
results.push({
period: `Week ${week}`,
average: periodAverage,
...this.reduce(subjectAverages),
})
periodStartDate = periodEndDate
}
return { grades: results, subjects }
}
public async getPeriodGrade(userId: number, startDate: DateTime, months: number = 0) {
const colles = await this.getColles(userId, startDate, months)
const subjects = this.getSubjects(colles)
const results: any = []
let periodStartDate = startDate
let index = 1
while (periodStartDate < startDate.plus({ months })) {
const periodEndDate = periodStartDate.endOf('month')
const periodColles = this.getPeriodColles(colles, startDate, periodEndDate)
const periodAverage = this.calculateAverage(periodColles)
const subjectAverages = await this.getSubjectAverages(
subjects,
periodColles,
colles,
results,
index,
userId,
periodStartDate
)
results.push({
period: periodStartDate.toFormat('MMM'),
average: periodAverage,
...this.reduce(subjectAverages),
})
periodStartDate = periodEndDate.plus({ days: 1 })
index++
}
return { grades: results, subjects }
}
private reduce(subjectAverages: SubjectPerformance[]) {
return subjectAverages.reduce((acc: any, { subject, average }) => {
acc[subject] = average
return acc
}, {})
}
private async getSubjectAverages(
subjects: string[],
periodColles: Colle[],
allColles: Colle[],
previousResults: Record<string, number>[],
unitIndex: number,
userId: number,
periodStart: DateTime
) {
const results = await Promise.all(
subjects.map(async (subject) => {
const subjectColles = periodColles.filter(
(colle) => colle.subject.name === subject && colle.grade
)
if (subjectColles.length > 0) {
return {
subject,
average: this.calculateSubjectAverage(periodColles, subject),
}
}
// Try to use the previous unit's average
if (unitIndex > 1) {
const prev = previousResults[unitIndex - 2]?.[subject]
if (prev) {
return { subject, average: prev }
}
}
// Otherwise fall back to global average before this period
const subjectId = allColles.find((colle) => colle.subject.name === subject)!.subjectId
const beforeAverage = await this.getGlobalAverage(userId, subjectId, periodStart)
if (beforeAverage) {
return { subject, average: beforeAverage }
}
return undefined
})
)
return results.filter((s): s is SubjectPerformance => Boolean(s))
}
}
interface SubjectPerformance {
subject: string
average: string
}

View file

@ -5,6 +5,8 @@ import { DateTime } from 'luxon'
import { UAParser } from 'ua-parser-js'
import webpush, { PushSubscription } from 'web-push'
const MAX_FAILED_ATTEMPTS = 5
export const EVENTS = {
SYSTEM: 1 << 0,
@ -45,18 +47,38 @@ export class NotificationService {
})
}
public async sendNotification(notificationId: NotificationId, colle: Colle) {
const payload = Object.assign(DEFAULT_NOTIFICATION, NOTIFICATIONS[notificationId](colle))
public async sendNotification(notificationId: NotificationId, colle: Colle, args?: any) {
await colle.load('subject')
if (notificationId === 'ROOM_UPDATED') {
await colle.load('room')
}
const payload = Object.assign(DEFAULT_NOTIFICATION, NOTIFICATIONS[notificationId](colle, args))
const subscriptions = await Subscription.query()
.where('enabled', true)
.where('userId', colle.studentId)
// TODO: Check if working??
.whereRaw(`(events & ${EVENTS[notificationId]}) > 0`)
for (const subscription of subscriptions) {
await this.pushNotification(subscription.data, payload)
// TODO: Count failed attempts and disable subscription if too many failures
try {
await this.pushNotification(subscription.data, payload)
// Reset failed attempts on successful notification
if (subscription.failedAttempts) {
subscription.failedAttempts = 0
await subscription.save()
}
} catch (err) {
console.error(
`Error sending notification for ${notificationId} to user ${colle.studentId}:`,
err
)
// Increment failed attempts and disable subscription if too many failures
subscription.failedAttempts = (subscription.failedAttempts || 0) + 1
if (subscription.failedAttempts >= MAX_FAILED_ATTEMPTS) {
subscription.enabled = false
}
await subscription.save()
}
}
}
@ -85,14 +107,14 @@ export class NotificationService {
? device.type
: 'Desktop'
return [deviceStr, osStr, browserStr].filter(Boolean).join(' | ')
return [deviceStr, osStr, browserStr].filter(Boolean).join(' - ')
}
}
const NOTIFICATIONS = {
COLLE_ADDED: (colle: Colle) => ({
title: 'Nouvelle colle',
body: `Colle de ${colle.subject} ajoutée le ${formatDate(colle.date)}.`,
body: `Colle de ${colle.subject.name} ajoutée le ${formatDate(colle.date)}.`,
data: {
id: colle.id,
},
@ -100,12 +122,12 @@ const NOTIFICATIONS = {
}),
COLLE_REMOVED: (colle: Colle) => ({
title: 'Colle supprimée',
body: `Votre colle de ${colle.subject}, le ${formatDate(colle.date)} a été supprimée.`,
body: `Votre colle de ${colle.subject.name}, le ${formatDate(colle.date)} a été supprimée.`,
actions: [HOME_ACTION],
}),
COLLE_UPDATED: (colle: Colle) => ({
title: 'Colle modifiée',
body: `Votre colle de ${colle.subject} du ${formatDate(colle.date)} a été modifiée.`,
body: `Votre colle de ${colle.subject.name} du ${formatDate(colle.date)} a été modifiée.`,
data: {
id: colle.id,
},
@ -114,15 +136,15 @@ const NOTIFICATIONS = {
GRADE_ADDED: (colle: Colle) => ({
title: 'Nouvelle note',
body: `Colle de ${colle.subject} : ${colle.grade}/20`,
body: `Colle de ${colle.subject.name} : ${colle.grade}/20`,
data: {
id: colle.id,
},
actions: [OPEN_ACION, HOME_ACTION],
}),
GRADE_UPDATED: (colle: Colle) => ({
GRADE_UPDATED: (colle: Colle, oldGrade: number) => ({
title: 'Note modifiée',
body: `Colle de ${colle.subject} : ${colle.grade}/20`,
body: `Colle de ${colle.subject.name} : ${oldGrade}/20 --> ${colle.grade}/20`,
data: {
id: colle.id,
},
@ -131,7 +153,7 @@ const NOTIFICATIONS = {
ROOM_UPDATED: (colle: Colle) => ({
title: 'Salle modifiée',
body: `Colle de ${colle.subject} en ${colle.room}.`,
body: `Colle de ${colle.subject.name} en ${colle.room.name}.`,
data: {
id: colle.id,
},

View file

@ -0,0 +1,27 @@
import { BaseSchema } from '@adonisjs/lucid/schema'
export default class extends BaseSchema {
protected tableName = 'subscriptions'
async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table
.integer('user_id')
.notNullable()
.unsigned()
.references('id')
.inTable('users')
.onDelete('CASCADE')
table.string('device').notNullable()
table.integer('events').defaultTo(0).notNullable()
table.jsonb('data').notNullable()
table.integer('failed_attempts').defaultTo(0).notNullable()
table.boolean('enabled').defaultTo(true).notNullable()
})
}
async down() {
this.schema.dropTable(this.tableName)
}
}

View file

@ -52,10 +52,22 @@ const NotificationsController = () => import('#controllers/notifications_control
router
.group(() => {
router.get('/', [NotificationsController, 'index'])
router.post('/subscribe', [NotificationsController, 'subscribe'])
router.post('/', [NotificationsController, 'subscribe'])
router.post('/:id/unsubscribe', [NotificationsController, 'unsubscribe'])
router.post('/:id', [NotificationsController, 'update'])
router.post('/:id/test', [NotificationsController, 'test']).use(middleware.auth())
})
.prefix('/notifications')
.use(middleware.auth())
const GradesController = () => import('#controllers/grades_controller')
router.get('/grades', [GradesController, 'index']).use(middleware.auth())
router.get('/averages', [GradesController, 'averages']).use(middleware.auth())
const InternalsController = () => import('#controllers/internals_controller')
router
.group(() => {
router.post('/back-fetch', [InternalsController, 'backFetch'])
})
.prefix('/internals')
// TODO: Token authentication