Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Expand Down
68 changes: 66 additions & 2 deletions apps/identity/test/integration/directory.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { rejects } from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { randomBytes, randomUUID } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
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';
Expand Down Expand Up @@ -139,4 +143,64 @@ 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 = {
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));
expect((await get(`/v1/directory/companies/${betaId}`).expect(200)).body)
.to.include({ rating_avg: 4, review_count: 1 });

const removed = {
...published, change: 'REMOVED' as const, 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 { 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<Prisma.TransactionClient>);
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 = {
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));
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);
});
});
Original file line number Diff line number Diff line change
@@ -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;
1 change: 1 addition & 0 deletions apps/notification/prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
provider = "postgresql"
68 changes: 68 additions & 0 deletions apps/notification/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
5 changes: 4 additions & 1 deletion apps/notification/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
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: [
// อ่าน .env ของโฟลเดอร์นี้ก่อน แล้วค่อย .env ที่ราก repo
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 {}
41 changes: 41 additions & 0 deletions apps/notification/src/events/consumers/application-recipients.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { ApplicationStatus, ApplicationStatusChangedPayload } from '@internpath/contracts';

type Channel = 'EMAIL' | 'IN_APP';
type Role = 'student' | 'hr' | 'advisor';

const matrix: Partial<Record<ApplicationStatus, Partial<Record<Role, Channel>>>> = {
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;
}
Loading
Loading