From 67e6fdf0c8c6bc07f2a7d830a2cc247ef0b544df Mon Sep 17 00:00:00 2001 From: SaBo4K Date: Sun, 22 Nov 2026 00:38:47 +0700 Subject: [PATCH 1/2] feat(notification): align notification contracts and review totals --- .../directory/directory-rating.service.ts | 2 +- .../test/integration/directory.spec.ts | 44 ++ .../migration.sql | 83 ++++ .../prisma/migrations/migration_lock.toml | 1 + apps/notification/prisma/schema.prisma | 68 +++ apps/notification/src/app.module.ts | 5 +- .../consumers/application-recipients.ts | 41 ++ .../events/consumers/notification-events.ts | 410 ++++++++++++++++++ .../src/internal/identity-client.ts | 66 +++ .../modules/mail/notification-mail.service.ts | 116 +++++ .../notifications/notifications.controller.ts | 86 ++++ apps/notification/src/notification.module.ts | 32 ++ apps/notification/src/prisma.service.ts | 17 + apps/notification/src/recipient-key.ts | 4 + .../integration/notification-events.spec.ts | 381 ++++++++++++++++ apps/notification/test/setup.ts | 1 + docker-compose.yml | 1 + docs/data-schema.md | 6 +- docs/event-contract.md | 8 +- 19 files changed, 1365 insertions(+), 7 deletions(-) create mode 100644 apps/notification/prisma/migrations/20261121110000_notification_inbox/migration.sql create mode 100644 apps/notification/prisma/migrations/migration_lock.toml create mode 100644 apps/notification/src/events/consumers/application-recipients.ts create mode 100644 apps/notification/src/events/consumers/notification-events.ts create mode 100644 apps/notification/src/internal/identity-client.ts create mode 100644 apps/notification/src/modules/mail/notification-mail.service.ts create mode 100644 apps/notification/src/modules/notifications/notifications.controller.ts create mode 100644 apps/notification/src/notification.module.ts create mode 100644 apps/notification/src/prisma.service.ts create mode 100644 apps/notification/src/recipient-key.ts create mode 100644 apps/notification/test/integration/notification-events.spec.ts diff --git a/apps/identity/src/modules/directory/directory-rating.service.ts b/apps/identity/src/modules/directory/directory-rating.service.ts index d19b766..4b711cb 100644 --- a/apps/identity/src/modules/directory/directory-rating.service.ts +++ b/apps/identity/src/modules/directory/directory-rating.service.ts @@ -8,7 +8,7 @@ export class DirectoryRatingService { const count = payload.company_review_count; const sum = payload.company_rating_sum; const version = payload.entity_version; - if (!Number.isSafeInteger(count) || count < 1 || !Number.isSafeInteger(sum) || sum < count || sum > count * 5 || + if (!Number.isSafeInteger(count) || count < 0 || !Number.isSafeInteger(sum) || sum < count || sum > count * 5 || !Number.isSafeInteger(version) || version < 1) { throw new Error('Invalid ReviewPublished rating statistics'); } diff --git a/apps/identity/test/integration/directory.spec.ts b/apps/identity/test/integration/directory.spec.ts index 7f01160..76d70c1 100644 --- a/apps/identity/test/integration/directory.spec.ts +++ b/apps/identity/test/integration/directory.spec.ts @@ -1,3 +1,4 @@ +import { rejects } from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { randomBytes, randomUUID } from 'node:crypto'; import { existsSync, readFileSync } from 'node:fs'; @@ -139,4 +140,47 @@ describe('Identity company directory (Postgres จริง)', function () { expect(detail.body.review_count).to.equal(3); expect((await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: alphaId } })).entityVersion).to.equal(3); }); + + it('clears Directory statistics when the last review is removed and ignores stale totals', async () => { + const published: ReviewPublishedPayload = { + review_id: randomUUID(), company_id: betaId, rating: 4, company_review_count: 1, + company_rating_sum: 4, entity_version: 1, published_at: new Date().toISOString(), + }; + await db.$transaction((tx) => ratings.apply(published, tx)); + expect((await get(`/v1/directory/companies/${betaId}`).expect(200)).body) + .to.include({ rating_avg: 4, review_count: 1 }); + + const removed = { + ...published, change: 'REMOVED', company_review_count: 0, + company_rating_sum: 0, entity_version: 2, + }; + await db.$transaction((tx) => ratings.apply(removed, tx)); + await db.$transaction((tx) => ratings.apply(published, tx)); + expect((await get(`/v1/directory/companies/${betaId}`).expect(200)).body) + .to.include({ rating_avg: 0, review_count: 0 }); + expect(await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: betaId } })) + .to.include({ entityVersion: 2, ratingSum: 0, reviewCount: 0 }); + + const legacy = { ...published, company_review_count: 0, company_rating_sum: 0, entity_version: 3 }; + await db.$transaction((tx) => ratings.apply(legacy, tx)); + expect((await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: betaId } })).entityVersion) + .to.equal(3); + }); + + it('rejects impossible absolute totals without changing the Directory snapshot', async () => { + const original: ReviewPublishedPayload = { + review_id: randomUUID(), company_id: pendingId, rating: 4, company_review_count: 1, + company_rating_sum: 4, entity_version: 1, published_at: new Date().toISOString(), + }; + await db.$transaction((tx) => ratings.apply(original, tx)); + const before = await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: pendingId } }); + for (const [count, sum] of [[-1, 0], [0, 1], [1, 0], [1, 6], [1, 1.5]]) { + const payload: ReviewPublishedPayload = { + ...original, company_review_count: count, company_rating_sum: sum, entity_version: 2, + }; + await rejects(db.$transaction((tx) => ratings.apply(payload, tx)), /Invalid ReviewPublished rating statistics/); + } + const after = await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: pendingId } }); + expect(after).to.deep.equal(before); + }); }); diff --git a/apps/notification/prisma/migrations/20261121110000_notification_inbox/migration.sql b/apps/notification/prisma/migrations/20261121110000_notification_inbox/migration.sql new file mode 100644 index 0000000..1a897e8 --- /dev/null +++ b/apps/notification/prisma/migrations/20261121110000_notification_inbox/migration.sql @@ -0,0 +1,83 @@ +-- CreateSchema +CREATE SCHEMA IF NOT EXISTS "public"; + +-- CreateEnum +CREATE TYPE "notification_channel" AS ENUM ('IN_APP', 'EMAIL'); + +-- CreateEnum +CREATE TYPE "delivery_status" AS ENUM ('PENDING', 'SENT', 'FAILED'); + +-- CreateTable +CREATE TABLE "processed_events" ( + "event_id" UUID NOT NULL, + "consumer" TEXT NOT NULL, + "processed_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "processed_events_pkey" PRIMARY KEY ("event_id","consumer") +); + +-- CreateTable +CREATE TABLE "notifications" ( + "id" UUID NOT NULL DEFAULT gen_random_uuid(), + "user_id" UUID NOT NULL, + "type" TEXT NOT NULL, + "title" TEXT NOT NULL, + "body" TEXT NOT NULL, + "link" TEXT, + "data" JSONB, + "source_event_id" UUID NOT NULL, + "read_at" TIMESTAMPTZ(6), + "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "notifications_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "delivery_logs" ( + "id" UUID NOT NULL DEFAULT gen_random_uuid(), + "notification_id" UUID NOT NULL, + "channel" "notification_channel" NOT NULL, + "to_user_id" UUID NOT NULL, + "status" "delivery_status" NOT NULL, + "error" TEXT, + "attempts" INTEGER NOT NULL DEFAULT 0, + "sent_at" TIMESTAMPTZ(6), + + CONSTRAINT "delivery_logs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "recipient_states" ( + "recipient_key" CHAR(64) NOT NULL, + "suspended" BOOLEAN NOT NULL DEFAULT false, + "deleted" BOOLEAN NOT NULL DEFAULT false, + "suspension_version" INTEGER NOT NULL DEFAULT 0, + "advisor_link_version" INTEGER NOT NULL DEFAULT 0, + + CONSTRAINT "recipient_states_pkey" PRIMARY KEY ("recipient_key") +); + +-- CreateTable +CREATE TABLE "review_notices" ( + "review_id" UUID NOT NULL, + + CONSTRAINT "review_notices_pkey" PRIMARY KEY ("review_id") +); + +-- CreateIndex +CREATE INDEX "notifications_user_id_created_at_id_idx" ON "notifications"("user_id", "created_at" DESC, "id" DESC); + +-- CreateIndex +CREATE INDEX "notifications_user_id_read_at_idx" ON "notifications"("user_id", "read_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "notifications_source_event_id_user_id_type_key" ON "notifications"("source_event_id", "user_id", "type"); + +-- CreateIndex +CREATE INDEX "delivery_logs_status_attempts_idx" ON "delivery_logs"("status", "attempts"); + +-- CreateIndex +CREATE UNIQUE INDEX "delivery_logs_notification_id_channel_key" ON "delivery_logs"("notification_id", "channel"); + +-- AddForeignKey +ALTER TABLE "delivery_logs" ADD CONSTRAINT "delivery_logs_notification_id_fkey" FOREIGN KEY ("notification_id") REFERENCES "notifications"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/notification/prisma/migrations/migration_lock.toml b/apps/notification/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..2fe25d8 --- /dev/null +++ b/apps/notification/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/apps/notification/prisma/schema.prisma b/apps/notification/prisma/schema.prisma index 2f74e73..196f30e 100644 --- a/apps/notification/prisma/schema.prisma +++ b/apps/notification/prisma/schema.prisma @@ -18,3 +18,71 @@ model ProcessedEvent { @@id([eventId, consumer]) @@map("processed_events") } + +enum NotificationChannel { + IN_APP + EMAIL + + @@map("notification_channel") +} + +enum DeliveryStatus { + PENDING + SENT + FAILED + + @@map("delivery_status") +} + +model Notification { + id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid + userId String @map("user_id") @db.Uuid + type String + title String + body String + link String? + data Json? + sourceEventId String @map("source_event_id") @db.Uuid + readAt DateTime? @map("read_at") @db.Timestamptz(6) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6) + deliveries DeliveryLog[] + + @@unique([sourceEventId, userId, type]) + @@index([userId, createdAt(sort: Desc), id(sort: Desc)]) + @@index([userId, readAt]) + @@map("notifications") +} + +model DeliveryLog { + id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid + notificationId String @map("notification_id") @db.Uuid + channel NotificationChannel + toUserId String @map("to_user_id") @db.Uuid + status DeliveryStatus + error String? + attempts Int @default(0) + sentAt DateTime? @map("sent_at") @db.Timestamptz(6) + notification Notification @relation(fields: [notificationId], references: [id], onDelete: Cascade) + + @@unique([notificationId, channel]) + @@index([status, attempts]) + @@map("delivery_logs") +} + +// E15/E16 and E07 may arrive out of order. Keep only delivery eligibility and versions. +model RecipientState { + recipientKey String @id @map("recipient_key") @db.Char(64) + suspended Boolean @default(false) + deleted Boolean @default(false) + suspensionVersion Int @default(0) @map("suspension_version") + advisorLinkVersion Int @default(0) @map("advisor_link_version") + + @@map("recipient_states") +} + +// E11 also carries revised totals when a published review is removed. +model ReviewNotice { + reviewId String @id @map("review_id") @db.Uuid + + @@map("review_notices") +} diff --git a/apps/notification/src/app.module.ts b/apps/notification/src/app.module.ts index 00b6210..8dcaf37 100644 --- a/apps/notification/src/app.module.ts +++ b/apps/notification/src/app.module.ts @@ -1,6 +1,9 @@ import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { HealthModule, createLoggingModule } from '@internpath/common'; +import { NotificationModule } from './notification.module'; + +const infra = process.env.DISABLE_INFRA === 'true' ? [] : [NotificationModule]; @Module({ imports: [ @@ -8,7 +11,7 @@ import { HealthModule, createLoggingModule } from '@internpath/common'; ConfigModule.forRoot({ isGlobal: true, envFilePath: ['.env', '../../.env'] }), createLoggingModule('notification'), HealthModule.register({ service: 'notification', databaseUrlEnv: 'NOTIFICATION_DATABASE_URL', requireBroker: true }), - // TODO: ต่อ modules/* ตาม docs/architecture.md §2 + ...infra, ], }) export class AppModule {} diff --git a/apps/notification/src/events/consumers/application-recipients.ts b/apps/notification/src/events/consumers/application-recipients.ts new file mode 100644 index 0000000..042e5ab --- /dev/null +++ b/apps/notification/src/events/consumers/application-recipients.ts @@ -0,0 +1,41 @@ +import type { ApplicationStatus, ApplicationStatusChangedPayload } from '@internpath/contracts'; + +type Channel = 'EMAIL' | 'IN_APP'; +type Role = 'student' | 'hr' | 'advisor'; + +const matrix: Partial>>> = { + PENDING: { hr: 'EMAIL' }, + HR_ACCEPTED: { student: 'EMAIL' }, + ADVISOR_PENDING: { hr: 'IN_APP', advisor: 'EMAIL' }, + ADVISOR_APPROVED: { student: 'EMAIL', hr: 'EMAIL' }, + IN_PROGRESS: { student: 'EMAIL', advisor: 'IN_APP' }, + EVALUATED_PASS: { student: 'EMAIL', advisor: 'IN_APP' }, + EVALUATED_FAIL: { student: 'EMAIL', advisor: 'EMAIL' }, + FAIL_DISPUTED: { hr: 'IN_APP', advisor: 'EMAIL' }, + REEVALUATION_REQUESTED: { student: 'IN_APP', hr: 'EMAIL' }, + COMPLETED: { student: 'IN_APP', hr: 'IN_APP', advisor: 'IN_APP' }, + NO_EVALUATION: { student: 'IN_APP', hr: 'IN_APP', advisor: 'IN_APP' }, + TERMINATED: { student: 'EMAIL', hr: 'EMAIL', advisor: 'EMAIL' }, + HR_REJECTED: { student: 'EMAIL' }, + ADVISOR_REJECTED: { student: 'EMAIL', hr: 'IN_APP' }, + OFFER_RESCINDED: { student: 'EMAIL' }, + CANCELLED: { student: 'EMAIL', advisor: 'IN_APP' }, + STUDENT_DECLINED: { hr: 'IN_APP' }, + WITHDRAWN: { hr: 'IN_APP' }, + EXPIRED: { student: 'IN_APP', hr: 'IN_APP' }, +}; + +export function applicationChannels(payload: ApplicationStatusChangedPayload) { + const channels = { ...matrix[payload.to_status] }; + const reachedAdvisor = + payload.from_status === 'ADVISOR_PENDING' || payload.from_status === 'ADVISOR_APPROVED'; + if ( + (payload.to_status === 'OFFER_RESCINDED' || payload.to_status === 'WITHDRAWN') && + reachedAdvisor + ) { + channels.advisor = 'IN_APP'; + } + if (payload.to_status === 'EXPIRED' && payload.from_status === 'ADVISOR_APPROVED') + channels.advisor = 'IN_APP'; + return channels; +} diff --git a/apps/notification/src/events/consumers/notification-events.ts b/apps/notification/src/events/consumers/notification-events.ts new file mode 100644 index 0000000..3669ded --- /dev/null +++ b/apps/notification/src/events/consumers/notification-events.ts @@ -0,0 +1,410 @@ +import { EventConsumer, InvalidMessageError } from '@internpath/common'; +import { + EVENT_CATALOG, + type AdvisorLinkChangedPayload, + type ApplicationStatusChangedPayload, + type CertificateIssuedPayload, + type CertificateRevokedPayload, + type CompanyFlagChangedPayload, + type CompanyStatusChangedPayload, + type EventEnvelope, + type JobStatusChangedPayload, + type ProblemReportCreatedPayload, + type ReminderDuePayload, + type ReminderType, + type ReportThresholdReachedPayload, + type ReviewModerationResultPayload, + type ReviewPublishedPayload, + type UserDeletionRequestedPayload, + type UserSuspendedPayload, +} from '@internpath/contracts'; +import { Injectable, OnModuleInit } from '@nestjs/common'; +import type { Prisma } from '../../../generated/client'; +import { IdentityClient } from '../../internal/identity-client'; +import { recipientKey } from '../../recipient-key'; +import { applicationChannels } from './application-recipients'; + +type Tx = Prisma.TransactionClient; +interface Recipient { + id: string; + email?: boolean; + link?: string; +} +interface Notice { + title: string; + body: string; + recipients: Recipient[]; +} + +const jobStatusMessages: Partial> = { + PUBLISHED: 'ประกาศเผยแพร่แล้ว', + PENDING_REVIEW: 'ประกาศอยู่ระหว่างรอผู้ดูแลระบบตรวจ', + ADMIN_REJECTED: 'ผู้ดูแลระบบปฏิเสธประกาศ', + SUSPENDED: 'ประกาศถูกระงับชั่วคราว', + REMOVED: 'ประกาศถูกนำออก', +}; + +const companyStatusMessages: Partial> = { + VERIFIED: 'บริษัทผ่านการยืนยันแล้ว', + NEED_MORE_INFO: 'ผู้ดูแลระบบขอข้อมูลบริษัทเพิ่มเติม', + REJECTED: 'คำขอยืนยันบริษัทถูกปฏิเสธ', + SUSPENDED: 'บัญชีบริษัทถูกระงับ', +}; + +const applicationStatusMessages: Partial< + Record +> = { + PENDING: 'มีใบสมัครใหม่', + HR_ACCEPTED: 'บริษัทส่งข้อเสนอฝึกงานแล้ว', + ADVISOR_PENDING: 'ใบสมัครรออาจารย์อนุมัติ', + ADVISOR_APPROVED: 'อาจารย์อนุมัติการฝึกงานแล้ว', + IN_PROGRESS: 'บริษัทยืนยันการเริ่มฝึกงานแล้ว', + EVALUATED_PASS: 'ผลการประเมินการฝึกงานผ่าน', + EVALUATED_FAIL: 'ผลการประเมินการฝึกงานไม่ผ่าน', + FAIL_DISPUTED: 'มีคำขอทบทวนผลการประเมิน', + REEVALUATION_REQUESTED: 'มีคำขอประเมินผลการฝึกงานใหม่', + COMPLETED: 'สิ้นสุดการฝึกงานแล้ว', + NO_EVALUATION: 'สิ้นสุดการฝึกงานโดยไม่มีผลประเมิน', + TERMINATED: 'ยุติการฝึกงานแล้ว', + HR_REJECTED: 'บริษัทปฏิเสธใบสมัคร', + ADVISOR_REJECTED: 'อาจารย์ปฏิเสธใบสมัคร', + OFFER_RESCINDED: 'บริษัทถอนข้อเสนอฝึกงาน', + CANCELLED: 'ใบสมัครถูกยกเลิก', + STUDENT_DECLINED: 'นักศึกษาปฏิเสธข้อเสนอ', + WITHDRAWN: 'นักศึกษาถอนใบสมัคร', + EXPIRED: 'ใบสมัครหมดเวลา', +}; + +const escalations = new Set([ + 'ADVISOR_APPROVE_ESCALATE_ADMIN_D7', + 'START_CONFIRM_ESCALATE_D7', + 'EVALUATE_ESCALATE_D14', + 'ISSUE_CERT_ESCALATE_D14', + 'DISPUTE_ESCALATE_D7', +]); + +const reminderMessages: Record = { + HR_RESPOND_PENDING_D3: 'ใบสมัครรอบริษัทพิจารณา', + HR_RESPOND_PENDING_D7: 'ใบสมัครรอบริษัทพิจารณาเกินกำหนด', + STUDENT_CONFIRM_D3: 'ข้อเสนอฝึกงานรอนักศึกษาตอบรับ', + ADVISOR_APPROVE_D3: 'ใบสมัครรออาจารย์อนุมัติ', + ADVISOR_APPROVE_ESCALATE_ADMIN_D7: 'ใบสมัครรออาจารย์อนุมัติเกินกำหนด', + HR_START_CONFIRM_ON_START: 'ถึงวันเริ่มฝึกงาน กรุณายืนยันการเริ่มฝึกงาน', + HR_START_CONFIRM_D3: 'ยังไม่ได้ยืนยันการเริ่มฝึกงาน', + START_CONFIRM_ESCALATE_D7: 'ยังไม่ได้ยืนยันการเริ่มฝึกงานเกินกำหนด', + HR_EVALUATE_D3: 'การฝึกงานสิ้นสุดแล้ว กรุณาประเมินผล', + EVALUATE_ESCALATE_D14: 'ยังไม่ได้ประเมินผลการฝึกงานเกินกำหนด', + HR_ISSUE_CERT_D3: 'กรุณาออกใบรับรองการฝึกงาน', + ISSUE_CERT_ESCALATE_D14: 'ยังไม่ได้ออกใบรับรองเกินกำหนด', + ADVISOR_DISPUTE_D3: 'ข้อโต้แย้งผลประเมินรออาจารย์พิจารณา', + DISPUTE_ESCALATE_D7: 'ข้อโต้แย้งผลประเมินยังไม่ได้รับการพิจารณา', + COMPANY_SUSPENDED_DECISION: 'บริษัทถูกระงับ กรุณาพิจารณาการฝึกงานที่กำลังดำเนินอยู่', +}; + +const detailLink = (path: string, id: string) => `${path}/item?id=${encodeURIComponent(id)}`; + +@Injectable() +export class NotificationEvents implements OnModuleInit { + constructor( + private readonly consumer: EventConsumer, + private readonly identity: IdentityClient, + ) {} + + async onModuleInit(): Promise { + await Promise.all( + EVENT_CATALOG.filter((event) => event.consumers.includes('notification')).map( + ({ producer, type }) => + this.consumer.subscribe({ + producer, + type, + handler: (envelope, tx) => this.handle(envelope, tx), + }), + ), + ); + } + + async handle(event: EventEnvelope, tx: Tx): Promise { + if ( + event.payload === null || + typeof event.payload !== 'object' || + Array.isArray(event.payload) + ) { + throw new InvalidMessageError('Invalid notification event payload'); + } + if (event.type === 'UserDeletionRequested') { + await this.deleteInbox(tx, (event.payload as UserDeletionRequestedPayload).user_id); + return; + } + if (event.type === 'UserSuspended') { + const payload = event.payload as UserSuspendedPayload; + await this.lockRecipient(tx, payload.user_id); + await tx.recipientState.updateMany({ + where: { + recipientKey: recipientKey(payload.user_id), + suspensionVersion: { lt: payload.entity_version }, + }, + data: { suspended: payload.suspended, suspensionVersion: payload.entity_version }, + }); + return; + } + if (event.type === 'AdvisorLinkChanged') { + const payload = event.payload as AdvisorLinkChangedPayload; + if (payload.link_status !== 'LINKED' && payload.link_status !== 'UNLINKED') return; + const state = await this.lockRecipient(tx, payload.student_user_id); + if (state.deleted || state.advisorLinkVersion >= payload.entity_version) return; + await tx.recipientState.update({ + where: { recipientKey: recipientKey(payload.student_user_id) }, + data: { advisorLinkVersion: payload.entity_version }, + }); + if (payload.link_status === 'UNLINKED' && payload.changed_by === 'ADVISOR') { + // Identity cancels the pending account and leaves no active student inbox. + await this.deleteInbox(tx, payload.student_user_id); + return; + } + } + + if (event.type === 'ReviewPublished') { + // Legacy E11 events omitted change and are treated as publications. + const change = 'change' in event.payload ? event.payload.change : 'PUBLISHED'; + if (change === 'REMOVED') return; + if (change !== 'PUBLISHED') throw new InvalidMessageError('Invalid ReviewPublished change'); + + const { review_id: reviewId } = event.payload as ReviewPublishedPayload; + const inserted = await tx.reviewNotice.createMany({ + data: [{ reviewId }], + skipDuplicates: true, + }); + if (inserted.count === 0) return; + } + + const notice = await this.notice(event); + if (!notice?.recipients.length) return; + const recipients = new Map(); + for (const recipient of notice.recipients) { + const previous = recipients.get(recipient.id); + recipients.set(recipient.id, { + ...recipient, + link: previous?.link ?? recipient.link, + email: previous?.email || recipient.email, + }); + } + const ids = [...recipients.keys()].sort(); + const existing = await this.identity.existingUsers(ids, event.correlation_id); + for (const id of ids) { + if (!existing.has(id)) continue; + const state = await this.lockRecipient(tx, id); + if (state.deleted || state.suspended) continue; + const recipient = recipients.get(id)!; + await tx.notification.create({ + data: { + userId: id, + type: event.type, + title: notice.title, + body: notice.body, + link: recipient.link, + sourceEventId: event.event_id, + ...(recipient.email + ? { deliveries: { create: { channel: 'EMAIL', toUserId: id, status: 'PENDING' } } } + : {}), + }, + }); + } + } + + private lockRecipient(tx: Tx, userId: string) { + const key = recipientKey(userId); + return tx.recipientState.upsert({ + where: { recipientKey: key }, + create: { recipientKey: key }, + update: { recipientKey: key }, + }); + } + + private async deleteInbox(tx: Tx, userId: string): Promise { + const key = recipientKey(userId); + await tx.recipientState.upsert({ + where: { recipientKey: key }, + create: { recipientKey: key, deleted: true }, + update: { deleted: true }, + }); + await tx.notification.deleteMany({ where: { userId } }); + } + + private async notice(event: EventEnvelope): Promise { + const cid = event.correlation_id; + const admins = async (link = '/admin/queue') => + (await this.identity.admins(cid)).map(({ user_id: id }) => ({ id, link })); + const members = async (companyId: string, link: string) => + (await this.identity.members(companyId, cid)).map(({ user_id: id }) => ({ id, link })); + switch (event.type) { + case 'JobStatusChanged': { + const p = event.payload as JobStatusChangedPayload; + const title = jobStatusMessages[p.to_status]; + if (title) + return { + title, + body: 'เปิดรายละเอียดประกาศของบริษัทเพื่อดูสถานะล่าสุด', + recipients: (await members(p.company_id, detailLink('/hr/jobs', p.job_id))).map( + (recipient) => ({ + ...recipient, + email: p.to_status === 'ADMIN_REJECTED', + }), + ), + }; + return; + } + case 'ReportThresholdReached': { + const p = event.payload as ReportThresholdReachedPayload; + return { + title: 'ประกาศถูกรายงานครบเกณฑ์', + body: 'มีรายการรายงานรอพิจารณา', + recipients: await admins(detailLink('/admin/queue', p.queue_item_id)), + }; + } + case 'CompanyStatusChanged': { + const p = event.payload as CompanyStatusChangedPayload; + const title = companyStatusMessages[p.status]; + if (!title) return; + const owner = + p.owner_user_id ?? + (await this.identity.members(p.company_id, cid)).find( + (member) => member.member_role === 'OWNER', + )?.user_id; + return { + title, + body: 'ตรวจสอบสถานะหรือปรับข้อมูลบริษัทในหน้าบัญชีบริษัท', + recipients: owner ? [{ id: owner, link: '/hr/company' }] : [], + }; + } + case 'AdvisorLinkChanged': { + const p = event.payload as AdvisorLinkChangedPayload; + const linked = p.link_status === 'LINKED'; + const advisor = linked ? p.new_advisor_id : p.old_advisor_id; + const recipients: Recipient[] = []; + if (p.changed_by !== 'STUDENT') + recipients.push({ id: p.student_user_id, link: '/student/profile' }); + if (advisor && p.changed_by !== 'ADVISOR') + recipients.push({ id: advisor, link: '/advisor/students' }); + return { + title: linked ? 'ผูกอาจารย์ที่ปรึกษาแล้ว' : 'ยกเลิกการผูกอาจารย์ที่ปรึกษาแล้ว', + body: 'ข้อมูลอาจารย์ที่ปรึกษาของนักศึกษามีการเปลี่ยนแปลง', + recipients, + }; + } + case 'ApplicationStatusChanged': + return this.applicationNotice(event.payload as ApplicationStatusChangedPayload, cid); + case 'ReviewModerationResult': { + const p = event.payload as ReviewModerationResultPayload; + if (p.decision === 'ADMIN_REMOVE') + return { + title: 'ผู้ดูแลระบบนำรีวิวออก', + body: 'รีวิวนี้ไม่แสดงในหน้าบริษัทแล้ว', + recipients: [{ id: p.student_user_id }], + }; + return; + } + case 'ReviewPublished': { + const p = event.payload as ReviewPublishedPayload; + return { + title: 'มีรีวิวของบริษัทใหม่', + body: 'มีรีวิวการฝึกงานเผยแพร่ในหน้าบริษัท', + recipients: await members(p.company_id, detailLink('/companies', p.company_id)), + }; + } + case 'CertificateIssued': { + const p = event.payload as CertificateIssuedPayload; + return { + title: 'ออกใบรับรองการฝึกงานแล้ว', + body: 'เปิดหน้าของคุณเพื่อดูใบรับรอง', + recipients: [{ id: p.student_user_id, link: '/student/certificates' }], + }; + } + case 'CertificateRevoked': { + const p = event.payload as CertificateRevokedPayload; + return { + title: 'ใบรับรองการฝึกงานถูกเพิกถอน', + body: 'ตรวจสอบสถานะใบรับรองในหน้าของคุณ', + recipients: [{ id: p.student_user_id, link: '/student/certificates' }], + }; + } + case 'ReminderDue': { + const p = event.payload as ReminderDuePayload; + const recipients: Recipient[] = p.audience.map(({ user_id: id, role }) => ({ + id, + email: true, + link: p.context.application_id + ? this.applicationLink(role, p.context.application_id) + : undefined, + })); + if (escalations.has(p.reminder_type)) { + recipients.push(...(await admins()).map((recipient) => ({ ...recipient, email: true }))); + } + return { + title: reminderMessages[p.reminder_type], + body: `กำหนดวันที่ ${p.due_date} กรุณาตรวจสอบรายการที่เกี่ยวข้อง`, + recipients, + }; + } + case 'ProblemReportCreated': { + const p = event.payload as ProblemReportCreatedPayload; + return { + title: 'นักศึกษารายงานปัญหาการฝึกงาน', + body: 'มีรายงานปัญหาใหม่ที่ต้องพิจารณา', + recipients: [{ id: p.advisor_user_id }, ...(await admins())], + }; + } + case 'CompanyFlagChanged': { + const p = event.payload as CompanyFlagChangedPayload; + if (p.active) + return { + title: 'บริษัทถูกติดธงให้ตรวจสอบ', + body: 'เปิดรายการธงบริษัทเพื่อดูรายละเอียด', + recipients: await admins('/admin/flags'), + }; + return; + } + } + } + + private async applicationNotice( + p: ApplicationStatusChangedPayload, + cid: string, + ): Promise { + const title = applicationStatusMessages[p.to_status]; + if (!title) return; + const channels = applicationChannels(p); + const recipients: Recipient[] = []; + if (channels.student) + recipients.push({ + id: p.student_user_id, + email: channels.student === 'EMAIL', + link: detailLink('/student/applications', p.application_id), + }); + if (channels.advisor && p.advisor_user_id) + recipients.push({ + id: p.advisor_user_id, + email: channels.advisor === 'EMAIL', + }); + if (channels.hr) { + const ids = + p.hr_user_ids ?? + (await this.identity.members(p.company_id, cid)).map((member) => member.user_id); + for (const id of ids) + recipients.push({ + id, + email: channels.hr === 'EMAIL', + link: detailLink('/hr/applicants', p.application_id), + }); + } + return { + title, + body: 'ตรวจสอบสถานะล่าสุดในใบสมัครที่เกี่ยวข้อง', + recipients: recipients.filter((recipient) => recipient.id !== p.actor_user_id), + }; + } + + private applicationLink(role: string, id: string): string | undefined { + if (role === 'STUDENT') return detailLink('/student/applications', id); + if (role === 'COMPANY_HR') return detailLink('/hr/applicants', id); + } +} diff --git a/apps/notification/src/internal/identity-client.ts b/apps/notification/src/internal/identity-client.ts new file mode 100644 index 0000000..da05503 --- /dev/null +++ b/apps/notification/src/internal/identity-client.ts @@ -0,0 +1,66 @@ +import { signServiceToken } from '@internpath/common'; +import type { + InternalAdminsResponse, + InternalCompanyMembersResponse, + UserContact, +} from '@internpath/contracts'; +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; + +@Injectable() +export class IdentityClient { + constructor(private readonly config: ConfigService) {} + + async members(companyId: string, correlationId: string): Promise { + return ( + (await this.get( + `companies/${encodeURIComponent(companyId)}/members`, + correlationId, + )) ?? [] + ); + } + + async admins(correlationId: string): Promise { + return (await this.get('admins', correlationId)) ?? []; + } + + contact(userId: string): Promise { + return this.get(`users/${encodeURIComponent(userId)}/contact`); + } + + async existingUsers(ids: string[], correlationId: string): Promise> { + const known = new Set(); + for (let offset = 0; offset < ids.length; offset += 100) { + const idsQuery = encodeURIComponent(ids.slice(offset, offset + 100).join(',')); + const contacts = await this.get( + `users/contacts?ids=${idsQuery}`, + correlationId, + ); + for (const contact of contacts ?? []) known.add(contact.user_id); + } + return known; + } + + private async get(path: string, correlationId?: string): Promise { + const base = this.config + .get('IDENTITY_URL', 'http://localhost:3001') + .replace(/\/$/, ''); + const secret = this.config.get('IDENTITY_SERVICE_SECRET_NOTIFICATION'); + if (!secret || secret.length < 32) + throw new Error('Notification service credentials are unavailable'); + const headers = { + Authorization: `Bearer ${signServiceToken({ issuer: 'notification', audience: 'identity', secret })}`, + ...(correlationId ? { 'X-Correlation-Id': correlationId } : {}), + }; + for (let attempt = 0; attempt < 3; attempt += 1) { + const response = await fetch(`${base}/internal/v1/${path}`, { + headers, + signal: AbortSignal.timeout(3000), + }).catch(() => undefined); + if (response?.ok) return (await response.json()) as T; + if (response?.status === 404) return; + if (response && response.status < 500) break; + } + throw new Error('Identity lookup failed'); + } +} diff --git a/apps/notification/src/modules/mail/notification-mail.service.ts b/apps/notification/src/modules/mail/notification-mail.service.ts new file mode 100644 index 0000000..ec5bef4 --- /dev/null +++ b/apps/notification/src/modules/mail/notification-mail.service.ts @@ -0,0 +1,116 @@ +import { Injectable, Logger, OnApplicationBootstrap, OnModuleDestroy } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { createTransport } from 'nodemailer'; +import { IdentityClient } from '../../internal/identity-client'; +import { PrismaService } from '../../prisma.service'; +import { recipientKey } from '../../recipient-key'; + +const MAX_ATTEMPTS = 5; +const POLL_INTERVAL_MS = 10_000; + +@Injectable() +export class NotificationMailService implements OnApplicationBootstrap, OnModuleDestroy { + private readonly log = new Logger(NotificationMailService.name); + private timer?: NodeJS.Timeout; + private running?: Promise; + + constructor( + private readonly db: PrismaService, + private readonly identity: IdentityClient, + private readonly config: ConfigService, + ) {} + + onApplicationBootstrap(): void { + this.timer = setInterval(() => { + if (this.running) return; + this.running = this.deliverNext() + .catch(() => this.log.error('Notification email delivery failed')) + .finally(() => { + this.running = undefined; + }); + }, POLL_INTERVAL_MS); + this.timer.unref(); + } + + async onModuleDestroy(): Promise { + clearInterval(this.timer); + await this.running; + } + + async deliverNext(): Promise { + return this.db.$transaction(async (tx) => { + // PENDING is committed by the consumer before SMTP. Concurrent workers skip locked deliveries. + const [row] = await tx.$queryRaw>` + SELECT id FROM delivery_logs + WHERE channel = 'EMAIL' AND status IN ('PENDING', 'FAILED') AND attempts < ${MAX_ATTEMPTS} + ORDER BY attempts, notification_id + LIMIT 1 FOR UPDATE SKIP LOCKED + `; + if (!row) return false; + const delivery = await tx.deliveryLog.findUniqueOrThrow({ + where: { id: row.id }, + include: { notification: true }, + }); + const state = await tx.recipientState.findUnique({ + where: { recipientKey: recipientKey(delivery.toUserId) }, + }); + const attempts = delivery.attempts + 1; + try { + const contact = + state?.deleted || state?.suspended + ? undefined + : await this.identity.contact(delivery.toUserId); + if (!contact) { + await tx.deliveryLog.update({ + where: { id: row.id }, + data: { status: 'FAILED', error: 'RECIPIENT_UNAVAILABLE', attempts: MAX_ATTEMPTS }, + }); + return true; + } + await this.send(contact.email, delivery.notification); + } catch { + await tx.deliveryLog.update({ + where: { id: row.id }, + data: { status: 'FAILED', error: 'DELIVERY_FAILED', attempts }, + }); + return true; + } + await tx.deliveryLog.update({ + where: { id: row.id }, + data: { status: 'SENT', sentAt: new Date(), error: null, attempts }, + }); + return true; + }); + } + + private async send( + email: string, + notice: { title: string; body: string; link: string | null }, + ): Promise { + const host = this.config.get('SMTP_HOST'); + if (!host) throw new Error('SMTP host unavailable'); + const port = Number(this.config.get('SMTP_PORT') ?? 1025); + const user = this.config.get('SMTP_USER'); + const transport = createTransport({ + host, + port, + secure: port === 465, + auth: user ? { user, pass: this.config.get('SMTP_PASSWORD') } : undefined, + connectionTimeout: 5000, + greetingTimeout: 5000, + socketTimeout: 10000, + }); + const base = this.config.get('WEB_BASE_URL', 'http://localhost:3100'); + const link = notice.link ? new URL(notice.link, base).href : undefined; + try { + await transport.sendMail({ + from: this.config.get('SMTP_FROM', 'InternPath '), + to: email, + subject: notice.title, + text: link ? `${notice.body}\n\n${link}` : notice.body, + }); + } finally { + transport.close(); + } + } +} diff --git a/apps/notification/src/modules/notifications/notifications.controller.ts b/apps/notification/src/modules/notifications/notifications.controller.ts new file mode 100644 index 0000000..e8c5e7b --- /dev/null +++ b/apps/notification/src/modules/notifications/notifications.controller.ts @@ -0,0 +1,86 @@ +import { AppException, CurrentUser, JwtAuthGuard, JwtClaims, isUuid } from '@internpath/common'; +import type { NotificationItem, Paginated, UnreadCountResponse } from '@internpath/contracts'; +import { Controller, Get, HttpCode, Param, Post, Query, UseGuards } from '@nestjs/common'; +import { Type } from 'class-transformer'; +import { IsIn, IsInt, IsOptional, Max, Min } from 'class-validator'; +import { Prisma } from '../../../generated/client'; +import { PrismaService } from '../../prisma.service'; + +class NotificationsQuery { + @IsOptional() @IsIn(['true', 'false']) unread?: 'true' | 'false'; + @IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(2147483647) page?: number; + @IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) page_size?: number; +} + +@Controller('notifications') +@UseGuards(JwtAuthGuard) +export class NotificationsController { + constructor(private readonly db: PrismaService) {} + + @Get() + async list( + @CurrentUser() user: JwtClaims, + @Query() query: NotificationsQuery, + ): Promise> { + const page = query.page ?? 1; + const pageSize = query.page_size ?? 20; + const where = { userId: user.sub, ...(query.unread === 'true' ? { readAt: null } : {}) }; + const [rows, total] = await this.db.$transaction( + [ + this.db.notification.findMany({ + where, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + skip: (page - 1) * pageSize, + take: pageSize, + }), + this.db.notification.count({ where }), + ], + { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead }, + ); + return { + data: rows.map((row) => ({ + id: row.id, + type: row.type, + title: row.title, + body: row.body, + ...(row.link ? { link: row.link } : {}), + read: row.readAt !== null, + created_at: row.createdAt.toISOString(), + })), + meta: { page, page_size: pageSize, total }, + }; + } + + @Get('unread-count') + async unreadCount(@CurrentUser() user: JwtClaims): Promise { + return { + count: await this.db.notification.count({ where: { userId: user.sub, readAt: null } }), + }; + } + + @Post(':id/actions/read') + @HttpCode(204) + async read(@CurrentUser() user: JwtClaims, @Param('id') id: string): Promise { + const notFound = new AppException('NOT_FOUND', 'ไม่พบการแจ้งเตือน', 404); + if (!isUuid(id)) throw notFound; + const where = { userId: user.sub, id }; + const updated = await this.db.notification.updateMany({ + where: { ...where, readAt: null }, + data: { readAt: new Date() }, + }); + if ( + updated.count === 0 && + !(await this.db.notification.findFirst({ where, select: { id: true } })) + ) + throw notFound; + } + + @Post('actions/read-all') + @HttpCode(204) + async readAll(@CurrentUser() user: JwtClaims): Promise { + await this.db.notification.updateMany({ + where: { userId: user.sub, readAt: null }, + data: { readAt: new Date() }, + }); + } +} diff --git a/apps/notification/src/notification.module.ts b/apps/notification/src/notification.module.ts new file mode 100644 index 0000000..671b221 --- /dev/null +++ b/apps/notification/src/notification.module.ts @@ -0,0 +1,32 @@ +import { JwtAuthGuard, MessagingModule } from '@internpath/common'; +import { Global, Module } from '@nestjs/common'; +import type { Prisma } from '../generated/client'; +import { NotificationEvents } from './events/consumers/notification-events'; +import { IdentityClient } from './internal/identity-client'; +import { NotificationMailService } from './modules/mail/notification-mail.service'; +import { NotificationsController } from './modules/notifications/notifications.controller'; +import { PrismaService } from './prisma.service'; + +@Global() +@Module({ providers: [PrismaService], exports: [PrismaService] }) +class PrismaModule {} + +@Module({ + imports: [ + PrismaModule, + MessagingModule.register({ + service: 'notification', + imports: [PrismaModule], + consumes: { + inject: [PrismaService], + useFactory: (db: PrismaService) => ({ + runInTransaction: (fn: (tx: Prisma.TransactionClient) => Promise) => + db.$transaction(fn), + }), + }, + }), + ], + controllers: [NotificationsController], + providers: [NotificationEvents, NotificationMailService, IdentityClient, JwtAuthGuard], +}) +export class NotificationModule {} diff --git a/apps/notification/src/prisma.service.ts b/apps/notification/src/prisma.service.ts new file mode 100644 index 0000000..eb4a1bb --- /dev/null +++ b/apps/notification/src/prisma.service.ts @@ -0,0 +1,17 @@ +import { Injectable, OnModuleDestroy } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { PrismaClient } from '../generated/client'; + +@Injectable() +export class PrismaService extends PrismaClient implements OnModuleDestroy { + constructor(config: ConfigService) { + super({ + datasourceUrl: config.get('NOTIFICATION_DATABASE_URL'), + transactionOptions: { maxWait: 10_000, timeout: 45_000 }, + }); + } + + async onModuleDestroy(): Promise { + await this.$disconnect(); + } +} diff --git a/apps/notification/src/recipient-key.ts b/apps/notification/src/recipient-key.ts new file mode 100644 index 0000000..3e38db0 --- /dev/null +++ b/apps/notification/src/recipient-key.ts @@ -0,0 +1,4 @@ +import { createHash } from 'node:crypto'; + +export const recipientKey = (userId: string) => + createHash('sha256').update(userId.toLowerCase()).digest('hex'); diff --git a/apps/notification/test/integration/notification-events.spec.ts b/apps/notification/test/integration/notification-events.spec.ts new file mode 100644 index 0000000..ec7530c --- /dev/null +++ b/apps/notification/test/integration/notification-events.spec.ts @@ -0,0 +1,381 @@ +import { execFileSync } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { resolve } from 'node:path'; +import { processDelivery, type EventConsumer } from '@internpath/common'; +import type { + ApplicationStatusChangedPayload, + EventEnvelope, + UserContact, +} from '@internpath/contracts'; +import { expect } from 'chai'; +import { PrismaClient, type Prisma } from '../../generated/client'; +import { applicationChannels } from '../../src/events/consumers/application-recipients'; +import { NotificationEvents } from '../../src/events/consumers/notification-events'; +import type { IdentityClient } from '../../src/internal/identity-client'; + +describe('Notification E08 recipient matrix', () => { + const channels = ( + to_status: ApplicationStatusChangedPayload['to_status'], + from_status?: ApplicationStatusChangedPayload['from_status'], + ) => applicationChannels({ from_status, to_status } as ApplicationStatusChangedPayload); + + it('implements the documented channel and prior-status rules', () => { + expect(channels('PENDING')).to.deep.equal({ hr: 'EMAIL' }); + expect(channels('IN_PROGRESS')).to.deep.equal({ student: 'EMAIL', advisor: 'IN_APP' }); + expect(channels('HR_REJECTED', 'PENDING')).to.deep.equal({ student: 'EMAIL' }); + expect(channels('ADVISOR_REJECTED')).to.deep.equal({ student: 'EMAIL', hr: 'IN_APP' }); + expect(channels('OFFER_RESCINDED', 'HR_ACCEPTED')).to.deep.equal({ student: 'EMAIL' }); + expect(channels('OFFER_RESCINDED', 'ADVISOR_PENDING')).to.deep.equal({ + student: 'EMAIL', + advisor: 'IN_APP', + }); + expect(channels('WITHDRAWN', 'ADVISOR_APPROVED')).to.deep.equal({ + hr: 'IN_APP', + advisor: 'IN_APP', + }); + expect(channels('EXPIRED', 'ADVISOR_PENDING')).to.deep.equal({ + student: 'IN_APP', + hr: 'IN_APP', + }); + expect(channels('EXPIRED', 'ADVISOR_APPROVED')).to.deep.equal({ + student: 'IN_APP', + hr: 'IN_APP', + advisor: 'IN_APP', + }); + }); +}); + +describe('Notification event consumption (PostgreSQL)', function () { + this.timeout(60_000); + const student = randomUUID(); + const advisor = randomUUID(); + const admin = randomUUID(); + const hr = randomUUID(); + const company = randomUUID(); + let maint: PrismaClient | undefined; + let db: PrismaClient | undefined; + const dbName = `notification_it_${randomUUID().replace(/-/g, '')}`; + let created = false; + let service: NotificationEvents; + const contact = (id: string): UserContact => ({ + user_id: id, + email: 'local@example.test', + full_name: 'Local', + }); + + before(async function () { + const connection = process.env.NOTIFICATION_IT_ADMIN_URL; + if (!connection) return this.skip(); + const url = new URL(connection); + if ( + !['postgresql:', 'postgres:'].includes(url.protocol) || + !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || + url.pathname !== '/postgres' || + url.search || + url.hash + ) { + throw new Error( + 'NOTIFICATION_IT_ADMIN_URL must point to a local postgres maintenance database', + ); + } + maint = new PrismaClient({ datasourceUrl: url.toString() }); + try { + // The name contains only a fixed prefix and a locally generated hex UUID. + await maint.$executeRawUnsafe(`CREATE DATABASE "${dbName}"`); + created = true; + url.pathname = `/${dbName}`; + const datasourceUrl = url.toString(); + execFileSync( + process.execPath, + [require.resolve('prisma/build/index.js'), 'migrate', 'deploy'], + { + cwd: resolve(__dirname, '../..'), + stdio: 'pipe', + timeout: 30000, + env: { + ...process.env, + NOTIFICATION_DATABASE_URL: datasourceUrl, + NOTIFICATION_DIRECT_URL: datasourceUrl, + }, + }, + ); + db = new PrismaClient({ datasourceUrl }); + } catch { + throw new Error('Could not initialize disposable Notification test database'); + } + const identity: Pick = { + admins: async () => [{ user_id: admin }], + members: async () => [{ user_id: hr, member_role: 'OWNER' }], + existingUsers: async (ids) => new Set(ids), + contact: async (id) => contact(id), + }; + service = new NotificationEvents( + {} as EventConsumer, + identity as IdentityClient, + ); + }); + + after(async () => { + try { + await db?.$disconnect(); + if (created) await maint?.$executeRawUnsafe(`DROP DATABASE "${dbName}" WITH (FORCE)`); + } finally { + await maint?.$disconnect(); + } + }); + + const envelope = ( + type: string, + payload: object, + producer: EventEnvelope['producer'] = 'identity', + ): EventEnvelope => ({ + type, + producer, + payload, + event_id: randomUUID(), + correlation_id: randomUUID(), + version: 1, + occurred_at: new Date().toISOString(), + }); + + function processEvent(event: EventEnvelope) { + return processDelivery({ + raw: Buffer.from(JSON.stringify(event)), + retryCount: 0, + queue: `notification.${event.type}`, + sub: { + type: event.type, + producer: event.producer, + handler: (env, tx: Prisma.TransactionClient) => service.handle(env, tx), + }, + runInTransaction: (handler) => db!.$transaction(handler), + maxRetries: 3, + }); + } + + async function deliver(event: EventEnvelope) { + expect((await processEvent(event)).kind).to.equal('ack'); + return db!.notification.findMany({ + where: { sourceEventId: event.event_id }, + include: { deliveries: true }, + }); + } + + it('deduplicates LINKED, uses in-app only, clears a cancelled inbox, and discards old link events', async () => { + const linked = envelope('AdvisorLinkChanged', { + student_user_id: student, + new_advisor_id: advisor, + link_status: 'LINKED', + changed_by: 'ADVISOR', + entity_version: 2, + }); + const notified = await deliver(linked); + expect(notified.map((notice) => notice.userId)).to.deep.equal([student]); + expect(notified[0].deliveries).to.deep.equal([]); + expect(await deliver(linked)).to.have.length(1); + const cancelled = envelope('AdvisorLinkChanged', { + student_user_id: student, + old_advisor_id: advisor, + link_status: 'UNLINKED', + changed_by: 'ADVISOR', + entity_version: 3, + }); + expect(await deliver(cancelled)).to.deep.equal([]); + expect(await deliver(linked)).to.deep.equal([]); + expect(await deliver({ ...linked, event_id: randomUUID() })).to.deep.equal([]); + expect( + await deliver( + envelope('AdvisorLinkChanged', { + student_user_id: student, + link_status: 'ADVISOR_LINK_PENDING', + }), + ), + ).to.deep.equal([]); + }); + + it('skips retired decisions, notifies the student for ADMIN_REMOVE, and adds Admin for an empty escalation', async () => { + const otherStudent = randomUUID(); + expect( + await deliver( + envelope('JobStatusChanged', { company_id: company, to_status: 'AUTO_REJECTED' }, 'job'), + ), + ).to.deep.equal([]); + expect( + await deliver( + envelope( + 'ReviewModerationResult', + { decision: 'HOLD', student_user_id: otherStudent }, + 'verification', + ), + ), + ).to.deep.equal([]); + const removed = await deliver( + envelope( + 'ReviewModerationResult', + { review_id: randomUUID(), decision: 'ADMIN_REMOVE', student_user_id: otherStudent }, + 'verification', + ), + ); + expect(removed.map((notification) => notification.userId)).to.deep.equal([otherStudent]); + const reminder = await deliver( + envelope( + 'ReminderDue', + { + audience: [], + context: {}, + due_date: '2026-11-21', + reminder_type: 'ADVISOR_APPROVE_ESCALATE_ADMIN_D7', + }, + 'lifecycle', + ), + ); + expect(reminder.map((notification) => notification.userId)).to.deep.equal([admin]); + expect(reminder[0].deliveries[0]).to.include({ status: 'PENDING', toUserId: admin }); + const rejected = await deliver( + envelope( + 'JobStatusChanged', + { + company_id: company, + job_id: randomUUID(), + to_status: 'ADMIN_REJECTED', + }, + 'job', + ), + ); + expect(rejected[0].deliveries[0]).to.include({ status: 'PENDING', toUserId: hr }); + }); + + const reviewPublished = (reviewId = randomUUID()) => ({ + review_id: reviewId, + company_id: company, + rating: 5, + company_review_count: 3, + company_rating_sum: 13, + entity_version: 1, + published_at: new Date().toISOString(), + }); + + it('notifies HR once for E11 PUBLISHED, including redelivery with the same or a new event ID', async () => { + const payload = { ...reviewPublished(), change: 'PUBLISHED' }; + const published = envelope('ReviewPublished', payload, 'lifecycle'); + const notice = await deliver(published); + expect(notice.map((row) => row.userId)).to.deep.equal([hr]); + expect(await deliver(published)).to.have.length(1); + expect(await deliver(envelope('ReviewPublished', payload, 'lifecycle'))).to.deep.equal([]); + expect( + await deliver( + envelope( + 'ReviewPublished', + { + ...payload, + change: 'REMOVED', + company_review_count: 2, + company_rating_sum: 8, + entity_version: 2, + }, + 'lifecycle', + ), + ), + ).to.deep.equal([]); + }); + + it('skips E11 REMOVED even when it arrives before E10 or E11 PUBLISHED', async () => { + const payload = reviewPublished(); + const removed = envelope( + 'ReviewPublished', + { + ...payload, + change: 'REMOVED', + company_review_count: 2, + company_rating_sum: 8, + entity_version: 2, + }, + 'lifecycle', + ); + expect(await deliver(removed)).to.deep.equal([]); + expect(await deliver(removed)).to.deep.equal([]); + expect(await db!.reviewNotice.findUnique({ where: { reviewId: payload.review_id } })).to.equal( + null, + ); + const e10 = await deliver( + envelope( + 'ReviewModerationResult', + { + review_id: payload.review_id, + decision: 'ADMIN_REMOVE', + student_user_id: randomUUID(), + }, + 'verification', + ), + ); + expect(e10).to.have.length(1); + expect( + ( + await deliver(envelope('ReviewPublished', { ...payload, change: 'PUBLISHED' }, 'lifecycle')) + ).map((row) => row.userId), + ).to.deep.equal([hr]); + }); + + it('treats legacy E11 without change as PUBLISHED', async () => { + const payload = reviewPublished(); + await deliver( + envelope( + 'ReviewModerationResult', + { + review_id: payload.review_id, + decision: 'ADMIN_REMOVE', + student_user_id: randomUUID(), + }, + 'verification', + ), + ); + const legacy = envelope('ReviewPublished', payload, 'lifecycle'); + expect((await deliver(legacy)).map((row) => row.userId)).to.deep.equal([hr]); + expect(await deliver(legacy)).to.have.length(1); + }); + + it('dead-letters E11 with an invalid change instead of notifying HR', async () => { + for (const change of [null, 'UNKNOWN']) { + const event = envelope('ReviewPublished', { ...reviewPublished(), change }, 'lifecycle'); + expect(await processEvent(event)).to.include({ + kind: 'dead-letter', + reason: 'invalid_message', + }); + expect(await db!.notification.count({ where: { sourceEventId: event.event_id } })).to.equal( + 0, + ); + } + }); + + it('persists pending mail, excludes the actor and suspended recipients, and deletes delivery rows with the inbox', async () => { + const secondStudent = randomUUID(); + const app = { + application_id: randomUUID(), + company_id: company, + student_user_id: secondStudent, + advisor_user_id: advisor, + actor_user_id: hr, + to_status: 'ADVISOR_APPROVED', + }; + const send = envelope('ApplicationStatusChanged', app, 'lifecycle'); + const queued = await deliver(send); + expect(queued.map((notification) => notification.userId)).to.deep.equal([secondStudent]); + expect(queued[0].deliveries[0]).to.include({ + status: 'PENDING', + toUserId: secondStudent, + attempts: 0, + }); + await deliver( + envelope('UserSuspended', { user_id: secondStudent, entity_version: 2, suspended: true }), + ); + await deliver( + envelope('UserSuspended', { user_id: secondStudent, entity_version: 1, suspended: false }), + ); + expect(await deliver(envelope('ApplicationStatusChanged', app, 'lifecycle'))).to.deep.equal([]); + await deliver(envelope('UserDeletionRequested', { user_id: secondStudent })); + expect( + await db!.deliveryLog.findUnique({ where: { id: queued[0].deliveries[0].id } }), + ).to.equal(null); + expect(await deliver(envelope('ApplicationStatusChanged', app, 'lifecycle'))).to.deep.equal([]); + }); +}); diff --git a/apps/notification/test/setup.ts b/apps/notification/test/setup.ts index b71d79f..4ea0eb9 100644 --- a/apps/notification/test/setup.ts +++ b/apps/notification/test/setup.ts @@ -1,2 +1,3 @@ // ปิด Log ระหว่างรันเทสต์ (ต้องตั้งก่อน import AppModule) process.env.LOG_LEVEL = 'silent'; +process.env.DISABLE_INFRA = 'true'; diff --git a/docker-compose.yml b/docker-compose.yml index 47785e2..451b198 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -142,6 +142,7 @@ services: environment: <<: *service-env PORT: "3005" + IDENTITY_URL: http://identity:3001 NOTIFICATION_DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/notification_db NOTIFICATION_DIRECT_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/notification_db diff --git a/docs/data-schema.md b/docs/data-schema.md index be57f08..fd15ff5 100644 --- a/docs/data-schema.md +++ b/docs/data-schema.md @@ -382,7 +382,11 @@ Index: (`status`, `status_changed_at`) สำหรับ Scheduler, (`advisor_u **`templates`**: `id`, `key` (เช่น `application.ADVISOR_APPROVED`), `channel`, `subject_th`, `body_th`, `active` **`preferences`** *(optional)*: `user_id`, `channel`, `enabled` -+ `processed_events`, `status_history` ไม่จำเป็น +**`recipient_states`**: `recipient_key` (PK, SHA-256 ของ UUID ผู้รับ), `suspended`, `deleted`, `suspension_version`, `advisor_link_version` — เก็บสิทธิ์การรับแจ้งเตือนและเวอร์ชันล่าสุดของ E07/E16 เพื่อไม่สร้างแจ้งเตือนซ้ำจาก Event เก่าหลังยกเลิกบัญชีหรือระงับบัญชี + +**`review_notices`**: `review_id` (PK) — กันแจ้ง HR ซ้ำสำหรับ E11 ที่เป็น `PUBLISHED` รวมถึง Event รุ่นเดิมที่ไม่มี `change` + ++ `processed_events` สำหรับ deduplicate Event --- diff --git a/docs/event-contract.md b/docs/event-contract.md index f792da0..77046d7 100644 --- a/docs/event-contract.md +++ b/docs/event-contract.md @@ -393,15 +393,15 @@ Job เก็บค่าไว้เพื่อใส่ใน `JobSubmitted.c | Event | ผู้ได้รับแจ้ง | เงื่อนไข | | :--- | :--- | :--- | -| `JobStatusChanged` | HR ของบริษัท | to ∈ {`PUBLISHED`, `PENDING_REVIEW`, `ADMIN_REJECTED`, `SUSPENDED`, `REMOVED`} | +| `JobStatusChanged` | HR ของบริษัท | to ∈ {`PUBLISHED`, `PENDING_REVIEW`, `ADMIN_REJECTED`, `SUSPENDED`, `REMOVED`}; `ADMIN_REJECTED` แจ้งทางอีเมลด้วย (README UAT-32) | | `ReportThresholdReached` | Admin | เสมอ | | `CompanyStatusChanged` | HR Owner | เมื่อสถานะ = `VERIFIED` / `NEED_MORE_INFO` / `REJECTED` / `SUSPENDED` | -| `AdvisorLinkChanged` | อาจารย์ที่ผูกกับนักศึกษา, นักศึกษา | ตาม `link_status` (อาจารย์สร้างนักศึกษา = `LINKED` ทันที `changed_by=ADVISOR`) | +| `AdvisorLinkChanged` | อาจารย์ที่ผูกกับนักศึกษา, นักศึกษา | In-app ตาม `link_status` และกฎผู้รับด้านล่าง อาจารย์สร้างนักศึกษา = `LINKED` ทันที (`changed_by=ADVISOR`); ยกเลิกบัญชีที่ยังไม่ตั้งรหัสผ่าน = `UNLINKED` (`changed_by=ADVISOR`). อีเมลคำเชิญและการส่งซ้ำเป็นหน้าที่ของ Identity | | `ApplicationStatusChanged` | ตาม **Recipient Matrix §6.1** (แยกตาม `to_status`) | ผู้รับ: นักศึกษา, HR, อาจารย์ ตามสถานะ | -| `ReviewModerationResult` | นักศึกษา (`student_user_id` ใน payload; เมื่อ `HOLD`/`ADMIN_REMOVE`), Admin (เมื่อ `HOLD` — รายชื่อจาก `GET /internal/v1/admins`) | — | +| `ReviewModerationResult` | นักศึกษา (`student_user_id` ใน payload) | เฉพาะ `ADMIN_REMOVE` | | `ReviewPublished` | HR ของบริษัท | มีรีวิวใหม่ (เฉพาะ `change = PUBLISHED`) | | `CertificateIssued` / `CertificateRevoked` | นักศึกษา | — | -| `ReminderDue` | `audience` ใน Payload; **ชนิดยกระดับ 5 ชนิด** (`ADVISOR_APPROVE_ESCALATE_ADMIN_D7`, `START_CONFIRM_ESCALATE_D7`, `EVALUATE_ESCALATE_D14`, `ISSUE_CERT_ESCALATE_D14`, `DISPUTE_ESCALATE_D7`) Notification **เพิ่ม Admin เอง** (รายชื่อจาก `GET /internal/v1/admins` — Lifecycle เรียก Identity endpoint นี้ไม่ได้ จึงไม่ใส่ Admin ใน `audience`) • `audience` ว่างได้ (เช่น `ADVISOR_APPROVE_ESCALATE_ADMIN_D7` ส่งถึง Admin อย่างเดียว) ⇒ Notification **ต้องไม่ทิ้ง Event** ต้องเติม Admin แล้วส่งตามปกติ (PM ตัดสิน 2026-11-18) | — | +| `ReminderDue` | `audience` ใน Payload; **ชนิดยกระดับ 5 ชนิด** (`ADVISOR_APPROVE_ESCALATE_ADMIN_D7`, `START_CONFIRM_ESCALATE_D7`, `EVALUATE_ESCALATE_D14`, `ISSUE_CERT_ESCALATE_D14`, `DISPUTE_ESCALATE_D7`) Notification **เพิ่ม Admin เอง** (รายชื่อจาก `GET /internal/v1/admins` — Lifecycle เรียก Identity endpoint นี้ไม่ได้ จึงไม่ใส่ Admin ใน `audience`) • `audience` ว่างได้ (เช่น `ADVISOR_APPROVE_ESCALATE_ADMIN_D7` ส่งถึง Admin อย่างเดียว) ⇒ Notification **ต้องไม่ทิ้ง Event** ต้องเติม Admin แล้วส่งตามปกติ (PM ตัดสิน 2026-11-18) | In-App และอีเมล (README UAT-32) | | `ProblemReportCreated` | อาจารย์ + Admin | เสมอ | | `CompanyFlagChanged` | Admin | `active=true` | | `UserDeletionRequested` | — | ลบกล่องข้อความ/บันทึกส่ง | From 98ab75bb8f2907f70ace0a80bf998e3906bf3cd9 Mon Sep 17 00:00:00 2001 From: SaBo4K Date: Sun, 22 Nov 2026 00:56:53 +0700 Subject: [PATCH 2/2] test(identity): align E11 fixtures with the review contract --- .../test/integration/directory.spec.ts | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/apps/identity/test/integration/directory.spec.ts b/apps/identity/test/integration/directory.spec.ts index 76d70c1..2ba27e3 100644 --- a/apps/identity/test/integration/directory.spec.ts +++ b/apps/identity/test/integration/directory.spec.ts @@ -6,11 +6,14 @@ import path from 'node:path'; import { INestApplication } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { Test } from '@nestjs/testing'; -import { configureApp } from '@internpath/common'; -import type { ReviewPublishedPayload } from '@internpath/contracts'; +import { EventConsumer, configureApp, consumerQueueName, processDelivery } from '@internpath/common'; +import type { EventEnvelope, ReviewPublishedPayload } from '@internpath/contracts'; import { expect } from 'chai'; import { Client } from 'pg'; +import { createStubInstance } from 'sinon'; import request from 'supertest'; +import type { Prisma } from '../../generated/client'; +import { ReviewPublishedConsumer } from '../../src/events/consumers/review-published.consumer'; import { DirectoryModule } from '../../src/modules/directory/directory.module'; import { DirectoryRatingService } from '../../src/modules/directory/directory-rating.service'; import { PrismaModule } from '../../src/prisma/prisma.module'; @@ -142,8 +145,8 @@ describe('Identity company directory (Postgres จริง)', function () { }); it('clears Directory statistics when the last review is removed and ignores stale totals', async () => { - const published: ReviewPublishedPayload = { - review_id: randomUUID(), company_id: betaId, rating: 4, company_review_count: 1, + const published = { + review_id: randomUUID(), company_id: betaId, change: 'PUBLISHED' as const, rating: 4, company_review_count: 1, company_rating_sum: 4, entity_version: 1, published_at: new Date().toISOString(), }; await db.$transaction((tx) => ratings.apply(published, tx)); @@ -151,7 +154,7 @@ describe('Identity company directory (Postgres จริง)', function () { .to.include({ rating_avg: 4, review_count: 1 }); const removed = { - ...published, change: 'REMOVED', company_review_count: 0, + ...published, change: 'REMOVED' as const, company_review_count: 0, company_rating_sum: 0, entity_version: 2, }; await db.$transaction((tx) => ratings.apply(removed, tx)); @@ -161,15 +164,32 @@ describe('Identity company directory (Postgres จริง)', function () { expect(await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: betaId } })) .to.include({ entityVersion: 2, ratingSum: 0, reviewCount: 0 }); - const legacy = { ...published, company_review_count: 0, company_rating_sum: 0, entity_version: 3 }; - await db.$transaction((tx) => ratings.apply(legacy, tx)); + const { change: _change, ...legacy } = published; + const event: EventEnvelope = { + event_id: randomUUID(), type: 'ReviewPublished', version: 1, producer: 'lifecycle', + correlation_id: randomUUID(), occurred_at: new Date().toISOString(), + payload: { ...legacy, company_review_count: 0, company_rating_sum: 0, entity_version: 3 }, + }; + expect(event.payload).not.to.have.property('change'); + const consumer = createStubInstance(EventConsumer); + consumer.subscribe.resolves(); + await new ReviewPublishedConsumer(consumer, ratings).onModuleInit(); + const result = await processDelivery({ + raw: Buffer.from(JSON.stringify(event)), + queue: consumerQueueName('identity', event.type), + sub: consumer.subscribe.firstCall.args[0], + runInTransaction: (fn) => db.$transaction(fn), + retryCount: 0, + maxRetries: 3, + }); + expect(result).to.deep.equal({ kind: 'ack' }); expect((await db.companyRatingStats.findUniqueOrThrow({ where: { companyId: betaId } })).entityVersion) .to.equal(3); }); it('rejects impossible absolute totals without changing the Directory snapshot', async () => { - const original: ReviewPublishedPayload = { - review_id: randomUUID(), company_id: pendingId, rating: 4, company_review_count: 1, + const original = { + review_id: randomUUID(), company_id: pendingId, change: 'PUBLISHED' as const, rating: 4, company_review_count: 1, company_rating_sum: 4, entity_version: 1, published_at: new Date().toISOString(), }; await db.$transaction((tx) => ratings.apply(original, tx));