|
| 1 | +import { Response } from 'express'; |
| 2 | +import { PrismaClient } from '@prisma/client'; |
| 3 | +import { WebhookHandledStatus, respondWebHookHandledStatus } from '../hooks'; |
| 4 | +import { handleFixedPointScore } from '../../handlers/points'; |
| 5 | + |
| 6 | +export interface PointGiven { |
| 7 | + id: number; |
| 8 | + campus_id: number; |
| 9 | + cursus_id: number; |
| 10 | + given_by: { |
| 11 | + id: number; |
| 12 | + first_name: string; |
| 13 | + last_name: string; |
| 14 | + usual_first_name: string | null; |
| 15 | + email: string; |
| 16 | + login: string; |
| 17 | + correction_points: number; |
| 18 | + } | null; |
| 19 | + points: { |
| 20 | + old: number; |
| 21 | + current: number; |
| 22 | + }, |
| 23 | + max_points: number; |
| 24 | +}; |
| 25 | + |
| 26 | +export const handlePointGivenWebhook = async function(prisma: PrismaClient, pointGiven: PointGiven, res: Response | null = null, webhookDeliveryId: string | null = null): Promise<Response | null> { |
| 27 | + try { |
| 28 | + // Get fixed point type |
| 29 | + const fixedPointType = await prisma.codamCoalitionFixedType.findFirst({ |
| 30 | + where: { |
| 31 | + type: 'point_donated', |
| 32 | + }, |
| 33 | + }); |
| 34 | + if (!fixedPointType || fixedPointType.point_amount === 0) { |
| 35 | + console.warn("No fixed point type found for point_donated or point amount is set to 0, skipping..."); |
| 36 | + return (res ? respondWebHookHandledStatus(prisma, webhookDeliveryId, res, WebhookHandledStatus.Skipped) : null); |
| 37 | + } |
| 38 | + if (!pointGiven.given_by) { |
| 39 | + return (res ? respondWebHookHandledStatus(prisma, webhookDeliveryId, res, WebhookHandledStatus.Skipped) : null); |
| 40 | + } |
| 41 | + |
| 42 | + // Calculate the score |
| 43 | + const actualPointsGiven = pointGiven.points.current - pointGiven.points.old; |
| 44 | + const points = actualPointsGiven * fixedPointType.point_amount; |
| 45 | + |
| 46 | + // Create a score |
| 47 | + const score = await handleFixedPointScore(prisma, fixedPointType, pointGiven.id, pointGiven.given_by.id, points, |
| 48 | + `Donated ${actualPointsGiven} points to the pool`); |
| 49 | + if (!score) { |
| 50 | + console.warn("Refused or failed to create score, skipping..."); |
| 51 | + return (res ? respondWebHookHandledStatus(prisma, webhookDeliveryId, res, WebhookHandledStatus.Skipped) : null); |
| 52 | + } |
| 53 | + return (res ? respondWebHookHandledStatus(prisma, webhookDeliveryId, res, WebhookHandledStatus.Ok) : null); |
| 54 | + } |
| 55 | + catch (error) { |
| 56 | + console.error("Failed to handle pool point_given webhook", error); |
| 57 | + return (res ? respondWebHookHandledStatus(prisma, webhookDeliveryId, res, WebhookHandledStatus.Error) : null); |
| 58 | + } |
| 59 | +}; |
0 commit comments