diff --git a/.env.example b/.env.example index b39b8f9..eed24b8 100644 --- a/.env.example +++ b/.env.example @@ -61,6 +61,8 @@ LIFECYCLE_SERVICE_SECRET_IDENTITY= # Lifecycle เซ็น token ไปเรียก Job (โควตา/ข้อมูลประกาศ) — ต้องเท่ากันทั้งสอง Service ≥ 32 ตัวอักษร # Lifecycle จะไม่เริ่มหาก IDENTITY_SERVICE_SECRET_LIFECYCLE หรือ JOB_SERVICE_SECRET_LIFECYCLE ว่างหรือสั้นกว่า 32 ตัวอักษร JOB_SERVICE_SECRET_LIFECYCLE= +# Identity เซ็น token ไป Job เพื่อกรองบริษัทตามสายงาน; Job ตรวจด้วยค่าเดียวกัน (>= 32 ตัวอักษร) +JOB_SERVICE_SECRET_IDENTITY= # Lifecycle ตรวจ token ที่ Job เซ็น (POST /internal/v1/applications/reservation-check) — ต้องเท่ากันทั้งสอง Service ≥ 32 ตัวอักษร LIFECYCLE_SERVICE_SECRET_JOB= diff --git a/apps/gateway/src/gateway.middleware.ts b/apps/gateway/src/gateway.middleware.ts index c31fab2..9a7162e 100644 --- a/apps/gateway/src/gateway.middleware.ts +++ b/apps/gateway/src/gateway.middleware.ts @@ -67,7 +67,9 @@ export class GatewayMiddleware { const rate = this.rateLimiter.rule(req.method, path); let body: Buffer | undefined; if (rate) { - const retry = this.rateLimiter.checkIp(rate, clientIp); + const retry = rate.name === 'advisor-create-student' && user + ? this.rateLimiter.checkAdvisorCreateIp(clientIp) || this.rateLimiter.checkActor(rate, user.sub) + : this.rateLimiter.checkIp(rate, clientIp); if (retry) { res.setHeader('Retry-After', String(retry)); return this.error(req, res, 429, 'RATE_LIMITED'); } if (req.method === 'POST' && path.startsWith('/auth/')) { try { body = await this.rateLimiter.readAuthBody(req); } diff --git a/apps/gateway/src/rate-limit/rate-limiter.ts b/apps/gateway/src/rate-limit/rate-limiter.ts index 81127fa..fdb003d 100644 --- a/apps/gateway/src/rate-limit/rate-limiter.ts +++ b/apps/gateway/src/rate-limit/rate-limiter.ts @@ -11,6 +11,8 @@ export class RateLimiter { rule(method: string, path: string): Rule | undefined { // README §5.7 fixes categories; these conservative defaults can be tuned by env later. if (method === 'POST' && path === '/auth/login') return { name: 'login', max: 10, windowMs: 60_000 }; + if (method === 'POST' && path === '/advisor-links/students') + return { name: 'advisor-create-student', max: 30, windowMs: 3_600_000 }; if (method === 'POST' && path.startsWith('/auth/register/')) return { name: 'register', max: 5, windowMs: 3_600_000 }; if (method === 'POST' && ['/auth/password/forgot', '/auth/password/reset', '/auth/resend-verification', '/auth/login/unlock/request'].includes(path)) @@ -26,6 +28,15 @@ export class RateLimiter { return this.limit(`${rule.name}:ip:${clientIp}`, rule.max, rule.windowMs); } + checkActor(rule: Rule, userId: string): number { + return this.limit(`${rule.name}:actor:${userId}`, rule.max, rule.windowMs); + } + + checkAdvisorCreateIp(clientIp: string): number { + // A university may have several advisors behind one IP; retain a broader network cap. + return this.limit(`advisor-create-student:ip:${clientIp}`, 120, 3_600_000); + } + checkAccount(rule: Rule, path: string, body: Buffer): number { const account = this.accountKey(path, body); return account ? this.limit(`${rule.name}:account:${account}`, rule.max, rule.windowMs) : 0; diff --git a/apps/gateway/test/integration/proxy.spec.ts b/apps/gateway/test/integration/proxy.spec.ts index 294b798..cfd8144 100644 --- a/apps/gateway/test/integration/proxy.spec.ts +++ b/apps/gateway/test/integration/proxy.spec.ts @@ -21,6 +21,9 @@ describe('Gateway proxy and security', function () { const token = () => jwt.sign({ role: 'STUDENT' }, privateKey, { algorithm: 'RS256', subject: userId, expiresIn: 900, jwtid: randomUUID(), }); + const advisorToken = (id: string) => jwt.sign({ role: 'ADVISOR' }, privateKey, { + algorithm: 'RS256', subject: id, expiresIn: 900, jwtid: randomUUID(), + }); const edge = (call: request.Test) => call.set('X-Edge-Secret', 'edge-test-secret'); before(async () => { @@ -114,6 +117,24 @@ describe('Gateway proxy and security', function () { expect(Number(limited.headers['retry-after'])).to.be.greaterThan(0); }); + it('limits student creation per advisor, including requests from different IPs', async () => { + const first = advisorToken(randomUUID()); + const second = advisorToken(randomUUID()); + for (let index = 0; index < 30; index++) { + await edge(request(app.getHttpServer()).post('/api/v1/advisor-links/students')) + .set('Authorization', `Bearer ${first}`).set('X-Client-IP', `203.0.113.${index + 1}`) + .send({ email: `student-${index}@school.ac.th` }).expect(200); + } + const limited = await edge(request(app.getHttpServer()).post('/api/v1/advisor-links/students')) + .set('Authorization', `Bearer ${first}`).set('X-Client-IP', '203.0.113.99') + .send({ email: 'another@school.ac.th' }).expect(429); + expect(limited.body.error.code).to.equal('RATE_LIMITED'); + expect(Number(limited.headers['retry-after'])).to.be.greaterThan(0); + await edge(request(app.getHttpServer()).post('/api/v1/advisor-links/students')) + .set('Authorization', `Bearer ${second}`).set('X-Client-IP', '203.0.113.99') + .send({ email: 'other-advisor@school.ac.th' }).expect(200); + }); + it('limits login attempts for one email across different IPs', async () => { for (let index = 0; index < 10; index++) { await edge(request(app.getHttpServer()).post('/api/v1/auth/login')) diff --git a/apps/gateway/test/unit/rate-limiter.spec.ts b/apps/gateway/test/unit/rate-limiter.spec.ts index 14696ca..cd1a3d8 100644 --- a/apps/gateway/test/unit/rate-limiter.spec.ts +++ b/apps/gateway/test/unit/rate-limiter.spec.ts @@ -2,6 +2,18 @@ import { expect } from 'chai'; import { RateLimiter } from '../../src/rate-limit/rate-limiter'; describe('Gateway rate limiter capacity', () => { + it('limits student creation per advisor without sharing a bucket across advisors', () => { + const limiter = new RateLimiter(); + const rule = limiter.rule('POST', '/advisor-links/students')!; + expect(rule).to.include({ name: 'advisor-create-student', max: 30, windowMs: 3_600_000 }); + expect(limiter.rule('GET', '/advisor-links/students')).to.equal(undefined); + for (let index = 0; index < 30; index++) expect(limiter.checkActor(rule, 'advisor-a')).to.equal(0); + expect(limiter.checkActor(rule, 'advisor-a')).to.be.greaterThan(0); + expect(limiter.checkActor(rule, 'advisor-b')).to.equal(0); + for (let index = 0; index < 120; index++) expect(limiter.checkAdvisorCreateIp('203.0.113.10')).to.equal(0); + expect(limiter.checkAdvisorCreateIp('203.0.113.10')).to.be.greaterThan(0); + expect(limiter.checkAdvisorCreateIp('203.0.113.11')).to.equal(0); + }); it('evicts the least recently used bucket instead of rejecting every new client', () => { const limiter = new RateLimiter(); const login = { name: 'login', max: 1, windowMs: 60_000 }; diff --git a/apps/identity/src/modules/admin/admin.controller.ts b/apps/identity/src/modules/admin/admin.controller.ts index 4debf57..683eedc 100644 --- a/apps/identity/src/modules/admin/admin.controller.ts +++ b/apps/identity/src/modules/admin/admin.controller.ts @@ -1,7 +1,7 @@ import { Body, Controller, Get, Headers, HttpCode, Param, ParseUUIDPipe, Post, Put, Query, UseGuards } from '@nestjs/common'; import { CurrentUser, JwtAuthGuard, type JwtClaims, Roles, RolesGuard } from '@internpath/common'; import { AdminService } from './admin.service'; -import { AuditQueryDto, SetEntitlementsDto, SetPartnerDto, UserActionDto } from './admin.dto'; +import { AdminUsersQueryDto, AuditQueryDto, SetEntitlementsDto, SetPartnerDto, UserActionDto } from './admin.dto'; @Controller('admin') @UseGuards(JwtAuthGuard, RolesGuard) @@ -27,6 +27,9 @@ export class AdminController { return this.service.userAction(actor.sub, userId, action, body.reason, correlationId); } + @Get('users') + users(@CurrentUser() actor: JwtClaims, @Query() query: AdminUsersQueryDto) { return this.service.users(actor.sub, query); } + @Get('audit-logs') audit(@CurrentUser() actor: JwtClaims, @Query() query: AuditQueryDto) { return this.service.audit(actor.sub, query); } } diff --git a/apps/identity/src/modules/admin/admin.dto.ts b/apps/identity/src/modules/admin/admin.dto.ts index 96bb949..cffc4fe 100644 --- a/apps/identity/src/modules/admin/admin.dto.ts +++ b/apps/identity/src/modules/admin/admin.dto.ts @@ -1,5 +1,6 @@ import { Type } from 'class-transformer'; -import { IsBoolean, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from 'class-validator'; +import { IsBoolean, IsEnum, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from 'class-validator'; +import { Role, UserStatus } from '../../../generated/client'; export class SetPartnerDto { @IsBoolean() enabled!: boolean; @@ -14,6 +15,14 @@ export class UserActionDto { @IsOptional() @IsString() @MaxLength(1000) reason?: string; } +export class AdminUsersQueryDto { + @IsOptional() @IsString() @MaxLength(100) q?: string; + @IsOptional() @IsEnum(Role) role?: Role; + @IsOptional() @IsEnum(UserStatus) status?: UserStatus; + @IsOptional() @Type(() => Number) @IsInt() @Min(1) page = 1; + @IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) page_size = 20; +} + export class AuditQueryDto { @IsOptional() @Type(() => Number) @IsInt() @Min(1) page = 1; @IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) page_size = 20; diff --git a/apps/identity/src/modules/admin/admin.service.ts b/apps/identity/src/modules/admin/admin.service.ts index 8720b7e..c311cd7 100644 --- a/apps/identity/src/modules/admin/admin.service.ts +++ b/apps/identity/src/modules/admin/admin.service.ts @@ -3,7 +3,7 @@ import { AppException, OutboxWriter, asUuid } from '@internpath/common'; import type { CompanyEntitlementChangedPayload, CompanyStatusChangedPayload, UserSuspendedPayload } from '@internpath/contracts'; import { Company, Prisma, User } from '../../../generated/client'; import { PrismaService } from '../../prisma/prisma.service'; -import { AuditQueryDto, SetEntitlementsDto } from './admin.dto'; +import { AdminUsersQueryDto, AuditQueryDto, SetEntitlementsDto } from './admin.dto'; @Injectable() export class AdminService { @@ -123,4 +123,28 @@ export class AdminService { correlation_id: row.correlationId, occurred_at: row.occurredAt.toISOString() })), meta: { page: query.page, page_size: query.page_size, total } }; } + + async users(adminId: string, query: AdminUsersQueryDto) { + await this.admin(adminId); + const q = query.q?.trim(); + const where: Prisma.UserWhereInput = { + ...(query.role ? { role: query.role } : {}), + ...(query.status ? { status: query.status } : { status: { not: 'DELETED' } }), + ...(q ? { OR: [ + { fullName: { contains: q, mode: 'insensitive' } }, + { email: { contains: q, mode: 'insensitive' } }, + { studentProfile: { is: { studentCode: { contains: q, mode: 'insensitive' } } } }, + ] } : {}), + }; + const [rows, total] = await Promise.all([ + this.db.user.findMany({ where, include: { studentProfile: true, companyMember: true }, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], skip: (query.page - 1) * query.page_size, take: query.page_size }), + this.db.user.count({ where }), + ]); + return { data: rows.map((user) => ({ id: user.id, full_name: user.fullName, email: user.email, + role: user.role, status: user.status, university_id: user.universityId, + advisor_id: user.studentProfile?.advisorId ?? null, student_code: user.studentProfile?.studentCode ?? null, + company_id: user.companyMember?.companyId ?? null, created_at: user.createdAt.toISOString() })), + meta: { page: query.page, page_size: query.page_size, total } }; + } } diff --git a/apps/identity/src/modules/advisor-links/advisor-link.service.ts b/apps/identity/src/modules/advisor-links/advisor-link.service.ts index b0c3881..1d663f8 100644 --- a/apps/identity/src/modules/advisor-links/advisor-link.service.ts +++ b/apps/identity/src/modules/advisor-links/advisor-link.service.ts @@ -10,6 +10,7 @@ import { AdminAdvisorQueryDto, AdvisorStudentsQueryDto, CreateStudentDto, Update const normalizeEmail = (email: string): string => email.trim().toLowerCase(); const isUniqueError = (error: unknown): boolean => error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002'; +const isSerializationError = (error: unknown): boolean => error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2034'; type Page = { data: T[]; meta: { page: number; page_size: number; total: number } }; @@ -97,9 +98,19 @@ export class AdvisorLinkService { actorId: advisorId, actorRole: 'ADVISOR', reason: 'STUDENT_CREATED_BY_ADVISOR', correlationId: cid, occurredAt: now } }); await this.linkEvent(tx, { studentId: user.id, before: { advisorId: null, advisorLinkStatus: 'NONE' } as StudentProfileIdentity, toStatus: 'LINKED', newAdvisorId: advisorId, changedBy: 'ADVISOR', actorId: advisorId, correlationId: cid, now }); - }); + }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }); } catch (error) { if (isUniqueError(error)) throw new AppException('STATE_CONFLICT', 'อีเมลนี้ลงทะเบียนแล้ว', 409, [{ field: 'email', issue: 'EMAIL_ALREADY_REGISTERED' }]); + if (isSerializationError(error)) { + if (await this.db.user.findUnique({ where: { email } })) + throw new AppException('STATE_CONFLICT', 'อีเมลนี้ลงทะเบียนแล้ว', 409, [{ field: 'email', issue: 'EMAIL_ALREADY_REGISTERED' }]); + const duplicate = await this.db.studentProfileIdentity.findFirst({ where: { + studentCode: body.student_code.trim(), user: { universityId: advisor.universityId, status: { not: 'DELETED' } }, + } }); + if (duplicate) throw new AppException('STATE_CONFLICT', 'รหัสนักศึกษานี้ถูกใช้แล้วในสถาบันเดียวกัน', 409, + [{ field: 'student_code', issue: 'STUDENT_CODE_ALREADY_USED' }]); + throw new AppException('STATE_CONFLICT', 'ข้อมูลถูกเปลี่ยนระหว่างบันทึก กรุณาลองใหม่', 409); + } throw error; } // บัญชีถูกสร้างแล้ว: ส่งอีเมลไม่สำเร็จไม่ทำให้คำขอล้ม — อาจารย์กดส่งคำเชิญใหม่ได้ diff --git a/apps/identity/src/modules/directory/directory-job.client.ts b/apps/identity/src/modules/directory/directory-job.client.ts new file mode 100644 index 0000000..ac6e465 --- /dev/null +++ b/apps/identity/src/modules/directory/directory-job.client.ts @@ -0,0 +1,60 @@ +import { AppException, signServiceToken } from '@internpath/common'; +import type { DirectoryCompanyIdsResponse, JobCategory } from '@internpath/contracts'; +import { Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { isUUID } from 'class-validator'; + +const unavailable = () => new AppException('UPSTREAM_UNAVAILABLE', 'ยังกรองสายงานบริษัทไม่ได้ กรุณาลองใหม่ภายหลัง', 503); + +/** Job owns job categories; Directory uses its published jobs as the category source. */ +@Injectable() +export class DirectoryJobClient { + private readonly log = new Logger(DirectoryJobClient.name); + + constructor(private readonly config: ConfigService) {} + + async companyIds(category: JobCategory): Promise> { + const secret = this.config.get('JOB_SERVICE_SECRET_IDENTITY'); + if (!secret || secret.length < 32) { + this.log.error('JOB_SERVICE_SECRET_IDENTITY is missing or shorter than 32 characters'); + throw unavailable(); + } + const base = (this.config.get('JOB_URL') || 'http://localhost:3002').replace(/\/+$/, ''); + const token = signServiceToken({ issuer: 'identity', audience: 'job', secret }); + const ids = new Set(); + let cursor: string | null = null; + do { + const query = new URLSearchParams({ category }); + if (cursor) query.set('after', cursor); + let response: Response; + try { + response = await fetch(`${base}/internal/v1/directory/company-ids?${query}`, { + headers: { authorization: `Bearer ${token}`, accept: 'application/json' }, + signal: AbortSignal.timeout(5000), + }); + } catch (error) { + this.log.warn(`Job directory lookup unreachable: ${(error as Error).name}`); + throw unavailable(); + } + if (response.status !== 200) { + this.log.warn(`Job directory lookup answered ${response.status}`); + throw unavailable(); + } + const body = (await response.json().catch(() => null)) as Partial | null; + if (!body || !Array.isArray(body.company_ids) || body.company_ids.some((id) => typeof id !== 'string' || !isUUID(id)) || + (body.next_cursor !== null && (typeof body.next_cursor !== 'string' || !isUUID(body.next_cursor))) || + (body.next_cursor !== null && (body.company_ids.length === 0 || body.next_cursor !== body.company_ids.at(-1)))) { + this.log.warn('Job directory lookup answered an invalid body'); + throw unavailable(); + } + for (const id of body.company_ids) ids.add(id.toLowerCase()); + const nextCursor = body.next_cursor; + if (nextCursor && cursor && nextCursor <= cursor) { + this.log.warn('Job directory lookup did not advance its cursor'); + throw unavailable(); + } + cursor = nextCursor; + } while (cursor); + return ids; + } +} diff --git a/apps/identity/src/modules/directory/directory.dto.ts b/apps/identity/src/modules/directory/directory.dto.ts index 19b4aa9..49f73fc 100644 --- a/apps/identity/src/modules/directory/directory.dto.ts +++ b/apps/identity/src/modules/directory/directory.dto.ts @@ -1,6 +1,7 @@ import { Transform, Type } from 'class-transformer'; -import { IsBoolean, IsInt, IsOptional, IsString, Matches, Max, MaxLength, Min, ValidateIf } from 'class-validator'; +import { IsBoolean, IsEnum, IsInt, IsOptional, IsString, Matches, Max, MaxLength, Min, ValidateIf } from 'class-validator'; import type { DirectoryCompaniesQuery } from '@internpath/contracts'; +import { JobCategory } from '../../../generated/client'; const UUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'; export const DIRECTORY_IDS_MAX = 50; @@ -14,9 +15,8 @@ export class DirectoryQueryDto implements DirectoryCompaniesQuery { q?: string; @ValidateIf((_body, value) => value !== undefined) - @IsString() - @MaxLength(100) - category?: string; + @IsEnum(JobCategory) + category?: JobCategory; @Transform(({ value }: { value: unknown }) => value === 'true' ? true : value === 'false' ? false : value) @ValidateIf((_body, value) => value !== undefined) diff --git a/apps/identity/src/modules/directory/directory.module.ts b/apps/identity/src/modules/directory/directory.module.ts index f32056f..e536570 100644 --- a/apps/identity/src/modules/directory/directory.module.ts +++ b/apps/identity/src/modules/directory/directory.module.ts @@ -1,11 +1,12 @@ import { Module } from '@nestjs/common'; import { DirectoryController } from './directory.controller'; +import { DirectoryJobClient } from './directory-job.client'; import { DirectoryRatingService } from './directory-rating.service'; import { DirectoryService } from './directory.service'; @Module({ controllers: [DirectoryController], - providers: [DirectoryService, DirectoryRatingService], + providers: [DirectoryService, DirectoryRatingService, DirectoryJobClient], exports: [DirectoryRatingService], }) export class DirectoryModule {} diff --git a/apps/identity/src/modules/directory/directory.service.ts b/apps/identity/src/modules/directory/directory.service.ts index 17cf94a..e5edad3 100644 --- a/apps/identity/src/modules/directory/directory.service.ts +++ b/apps/identity/src/modules/directory/directory.service.ts @@ -4,6 +4,7 @@ import { AppException } from '@internpath/common'; import type { DirectoryCompanyDetail, DirectoryCompanyListItem, Paginated } from '@internpath/contracts'; import { Prisma } from '../../../generated/client'; import { PrismaService } from '../../prisma/prisma.service'; +import { DirectoryJobClient } from './directory-job.client'; import { DirectoryQueryDto } from './directory.dto'; type DirectoryCompany = Prisma.CompanyGetPayload<{ include: { ratingStats: true } }>; @@ -12,7 +13,7 @@ type DirectoryCompanySummary = DirectoryCompanyListItem & Pick('S3_PUBLIC_BASE_URL'); @@ -37,15 +38,15 @@ export class DirectoryService { } async list(query: DirectoryQueryDto): Promise> { - if (query.category?.trim()) { - throw new AppException('VALIDATION_FAILED', 'ยังไม่มีแหล่งข้อมูลหมวดหมู่บริษัทสำหรับตัวกรอง category', 400); - } + const categoryIds = query.category ? await this.jobs.companyIds(query.category) : undefined; const q = query.q?.trim(); // Unknown / non-VERIFIED ids simply drop out of the result (no error). const ids = query.ids ? [...new Set(query.ids.toLowerCase().split(','))] : undefined; + const matchingIds = categoryIds ? (ids ? ids.filter((id) => categoryIds.has(id)) : [...categoryIds]) : ids; + if (matchingIds?.length === 0) return { data: [], meta: { page: query.page, page_size: query.page_size, total: 0 } }; const where: Prisma.CompanyWhereInput = { status: 'VERIFIED', - ...(ids ? { id: { in: ids } } : {}), + ...(matchingIds ? { id: { in: matchingIds } } : {}), ...(q ? { name: { contains: q, mode: 'insensitive' as const } } : {}), ...(query.partner === undefined ? {} : { universityPartner: query.partner }), }; diff --git a/apps/identity/test/integration/admin-controls.spec.ts b/apps/identity/test/integration/admin-controls.spec.ts index b9a27f9..71bfe27 100644 --- a/apps/identity/test/integration/admin-controls.spec.ts +++ b/apps/identity/test/integration/admin-controls.spec.ts @@ -89,6 +89,18 @@ describe('Identity Admin controls (Postgres จริง)', function () { delete process.env.JWT_PUBLIC_KEY; }); + it('lists filtered users for Admin without exposing password hashes', async () => { + await request(app.getHttpServer()).get('/v1/admin/users') + .set('Authorization', bearer(memberId, 'COMPANY_HR')).expect(403); + const result = await request(app.getHttpServer()).get('/v1/admin/users?role=COMPANY_HR&q=member&page_size=10') + .set('Authorization', bearer(adminId, 'PLATFORM_ADMIN')).expect(200); + expect(result.body.meta.total).to.equal(1); + expect(result.body.data[0]).to.include({ id: memberId, email: 'member@company.test', role: 'COMPANY_HR' }); + expect(result.body.data[0]).to.not.have.property('passwordHash'); + await request(app.getHttpServer()).get('/v1/admin/users?role=unknown') + .set('Authorization', bearer(adminId, 'PLATFORM_ADMIN')).expect(400); + }); + it('sets University Partner with E05 snapshot and one audit row; repeated PUT is a no-op', async () => { const adminToken = bearer(adminId, 'PLATFORM_ADMIN'); const url = `/v1/admin/companies/${companyId}/university-partner`; diff --git a/apps/identity/test/integration/advisor-link.spec.ts b/apps/identity/test/integration/advisor-link.spec.ts index ae3d04b..799ddd6 100644 --- a/apps/identity/test/integration/advisor-link.spec.ts +++ b/apps/identity/test/integration/advisor-link.spec.ts @@ -10,6 +10,8 @@ import { expect } from 'chai'; import * as jwt from 'jsonwebtoken'; import { Client } from 'pg'; import request from 'supertest'; +import sinon from 'sinon'; +import { AuthMailer } from '../../src/modules/auth/auth.mailer'; import { AdvisorLinkModule } from '../../src/modules/advisor-links/advisor-link.module'; import { UsersModule } from '../../src/modules/users/users.module'; import { PrismaModule } from '../../src/prisma/prisma.module'; @@ -170,6 +172,16 @@ describe('Identity advisor-created students (Postgres จริง)', function ( expect(await db.user.count({ where: { email: body.email } })).to.equal(1); }); + it('simultaneous creates with one student code in the same university produce one account', async () => { + const code = `R${randomBytes(3).toString('hex')}`; + const results = await Promise.all([1, 2].map(() => http().post('/v1/advisor-links/students') + .set(advisorAuth(advisorB)).send(newStudent({ student_code: code })))); + expect(results.map((r) => r.status).sort()).to.deep.equal([201, 409]); + const advisor = await db.user.findUniqueOrThrow({ where: { id: advisorB } }); + expect(await db.studentProfileIdentity.count({ where: { studentCode: code, + user: { universityId: advisor.universityId } } })).to.equal(1); + }); + it('lists only own students with q / year_level / activation filters and invitation expiry for pending ones', async () => { const mine = await db.user.findMany({ where: { studentProfile: { is: { advisorId: advisorB } } }, include: { studentProfile: true } }); await db.user.update({ where: { id: mine[0].id }, data: { status: 'ACTIVE', emailVerifiedAt: new Date(), passwordHash: 'x' } }); @@ -203,7 +215,11 @@ describe('Identity advisor-created students (Postgres จริง)', function ( const before = await db.emailToken.findMany({ where: { userId: id } }); await http().post(`/v1/advisor-links/students/${id}/actions/resend-invitation`).set(advisorAuth(advisorA)).expect(404); - await http().post(`/v1/advisor-links/students/${id}/actions/resend-invitation`).set(advisorAuth(advisorB)).expect(503); // ไม่ได้ตั้งค่า SMTP ในเทสต์ แต่คำเชิญใหม่ถูกออกแล้ว + // Force a mail failure so the expected 503 does not depend on a running Mailpit or developer SMTP settings. + const mailFailure = sinon.stub(app.get(AuthMailer), 'send').rejects(new Error('test SMTP failure')); + try { + await http().post(`/v1/advisor-links/students/${id}/actions/resend-invitation`).set(advisorAuth(advisorB)).expect(503); + } finally { mailFailure.restore(); } const after = await db.emailToken.findMany({ where: { userId: id }, orderBy: { createdAt: 'asc' } }); expect(after).to.have.length(before.length + 1); expect(after.filter((t) => !t.usedAt)).to.have.length(1); // ลิงก์เดิมใช้ไม่ได้ diff --git a/apps/identity/test/integration/directory.spec.ts b/apps/identity/test/integration/directory.spec.ts index 7f01160..6dc4aee 100644 --- a/apps/identity/test/integration/directory.spec.ts +++ b/apps/identity/test/integration/directory.spec.ts @@ -12,6 +12,7 @@ import { Client } from 'pg'; import request from 'supertest'; import { DirectoryModule } from '../../src/modules/directory/directory.module'; import { DirectoryRatingService } from '../../src/modules/directory/directory-rating.service'; +import { DirectoryJobClient } from '../../src/modules/directory/directory-job.client'; import { PrismaModule } from '../../src/prisma/prisma.module'; import { PrismaService } from '../../src/prisma/prisma.service'; @@ -39,6 +40,7 @@ describe('Identity company directory (Postgres จริง)', function () { let alphaId: string; let betaId: string; let pendingId: string; + let categoryIds = new Set(); const get = (url: string) => request(app.getHttpServer()).get(url); before(async function () { @@ -58,7 +60,10 @@ describe('Identity company directory (Postgres จริง)', function () { process.env.IDENTITY_DIRECT_URL = testUrl; process.env.S3_PUBLIC_BASE_URL = 'https://assets.example.test'; const moduleRef = await Test.createTestingModule({ imports: [ConfigModule.forRoot({ isGlobal: true, ignoreEnvFile: true }), - PrismaModule, DirectoryModule] }).compile(); + PrismaModule, DirectoryModule] }) + .overrideProvider(DirectoryJobClient) + .useValue({ companyIds: async () => categoryIds }) + .compile(); app = moduleRef.createNestApplication(); configureApp(app); await app.init(); db = app.get(PrismaService); ratings = app.get(DirectoryRatingService); alphaId = (await db.company.create({ data: { name: 'Alpha Studio', registrationNo: 'DIR-001', @@ -93,6 +98,20 @@ describe('Identity company directory (Postgres จริง)', function () { await get('/v1/directory/companies?category=TECH').expect(400); }); + it('filters published-job companies with other filters and exact pagination', async () => { + categoryIds = new Set([betaId, pendingId]); + const matched = await get('/v1/directory/companies?category=TECH_IT&page_size=1').expect(200); + expect(ids(matched.body)).to.deep.equal([betaId]); + expect(matched.body.meta).to.deep.equal({ page: 1, page_size: 1, total: 1 }); + expect(ids((await get(`/v1/directory/companies?category=TECH_IT&ids=${alphaId},${betaId}`).expect(200)).body)) + .to.deep.equal([betaId]); + const none = await get('/v1/directory/companies?category=TECH_IT&partner=true').expect(200); + expect(none.body.meta.total).to.equal(0); + categoryIds = new Set(); + const empty = await get('/v1/directory/companies?category=TECH_IT').expect(200); + expect(empty.body.meta.total).to.equal(0); + }); + it('paginates with page/page_size (max 100)', async () => { const second = await get('/v1/directory/companies?page=2&page_size=1').expect(200); expect(ids(second.body)).to.deep.equal([betaId]); diff --git a/apps/identity/test/unit/directory-job.client.spec.ts b/apps/identity/test/unit/directory-job.client.spec.ts new file mode 100644 index 0000000..ca19531 --- /dev/null +++ b/apps/identity/test/unit/directory-job.client.spec.ts @@ -0,0 +1,48 @@ +import { randomUUID } from 'node:crypto'; +import { AppException } from '@internpath/common'; +import { ConfigService } from '@nestjs/config'; +import { expect } from 'chai'; +import { DirectoryJobClient } from '../../src/modules/directory/directory-job.client'; + +const secret = 'identity-to-job-directory-test-secret-long-enough'; +const page = (company_ids: string[], next_cursor: string | null) => + new Response(JSON.stringify({ company_ids, next_cursor }), { status: 200 }); + +describe('Directory Job client', () => { + const originalFetch = globalThis.fetch; + afterEach(() => { globalThis.fetch = originalFetch; }); + + it('collects all pages and signs an Identity service token', async () => { + const first = randomUUID(); + const second = randomUUID(); + const requests: string[] = []; + globalThis.fetch = async (input, init) => { + requests.push(String(input)); + expect(init?.headers).to.have.property('authorization').that.matches(/^Bearer /); + return requests.length === 1 ? page([first], first) : page([second], null); + }; + const client = new DirectoryJobClient(new ConfigService({ JOB_SERVICE_SECRET_IDENTITY: secret, + JOB_URL: 'http://job:3002' })); + expect([...await client.companyIds('TECH_IT')]).to.deep.equal([first, second]); + expect(requests[0]).to.equal('http://job:3002/internal/v1/directory/company-ids?category=TECH_IT'); + expect(requests[1]).to.include(`after=${first}`); + }); + + it('fails closed if Job is unavailable or returns an invalid page', async () => { + const client = new DirectoryJobClient(new ConfigService({ JOB_SERVICE_SECRET_IDENTITY: secret })); + for (const fetcher of [ + async () => { throw new Error('offline'); }, + async () => new Response('', { status: 503 }), + async () => page(['not-a-uuid'], null), + async () => page([], randomUUID()), + ]) { + globalThis.fetch = fetcher as typeof fetch; + const error = await client.companyIds('TECH_IT').then(() => null, (cause: unknown) => cause); + expect(error).to.be.instanceOf(AppException); + expect((error as AppException).getStatus()).to.equal(503); + } + const missingSecret = new DirectoryJobClient(new ConfigService({})); + const error = await missingSecret.companyIds('TECH_IT').then(() => null, (cause: unknown) => cause); + expect((error as AppException).getStatus()).to.equal(503); + }); +}); diff --git a/apps/identity/test/unit/directory.service.spec.ts b/apps/identity/test/unit/directory.service.spec.ts new file mode 100644 index 0000000..b9452b1 --- /dev/null +++ b/apps/identity/test/unit/directory.service.spec.ts @@ -0,0 +1,46 @@ +import { randomUUID } from 'node:crypto'; +import { ConfigService } from '@nestjs/config'; +import { expect } from 'chai'; +import { DirectoryJobClient } from '../../src/modules/directory/directory-job.client'; +import { DirectoryQueryDto } from '../../src/modules/directory/directory.dto'; +import { DirectoryService } from '../../src/modules/directory/directory.service'; +import { PrismaService } from '../../src/prisma/prisma.service'; + +describe('Directory category filtering', () => { + it('intersects category companies with requested ids before counting and paging', async () => { + const matching = randomUUID(); + const other = randomUUID(); + const excluded = randomUUID(); + const whereClauses: unknown[] = []; + const company = { + id: matching, name: 'Matched', logoKey: null, universityPartner: true, ratingStats: null, + }; + const db = { + company: { + count: ({ where }: { where: unknown }) => { whereClauses.push(where); return Promise.resolve(1); }, + findMany: ({ where }: { where: unknown }) => { whereClauses.push(where); return Promise.resolve([company]); }, + }, + $transaction: (queries: Promise[]) => Promise.all(queries), + } as unknown as PrismaService; + const jobs = { companyIds: async () => new Set([matching, excluded]) } as unknown as DirectoryJobClient; + const service = new DirectoryService(db, new ConfigService({}), jobs); + const query = Object.assign(new DirectoryQueryDto(), { + category: 'TECH_IT' as const, ids: `${matching},${other}`, partner: true, page: 1, page_size: 20, + }); + const result = await service.list(query); + expect(result.meta.total).to.equal(1); + expect(result.data.map((item) => item.id)).to.deep.equal([matching]); + expect(whereClauses).to.deep.equal([ + { status: 'VERIFIED', id: { in: [matching] }, universityPartner: true }, + { status: 'VERIFIED', id: { in: [matching] }, universityPartner: true }, + ]); + }); + + it('returns an empty page without querying Identity when Job has no matching companies', async () => { + const db = { company: { count: () => { throw new Error('unexpected query'); } } } as unknown as PrismaService; + const jobs = { companyIds: async () => new Set() } as unknown as DirectoryJobClient; + const service = new DirectoryService(db, new ConfigService({}), jobs); + const result = await service.list(Object.assign(new DirectoryQueryDto(), { category: 'TECH_IT' as const })); + expect(result).to.deep.equal({ data: [], meta: { page: 1, page_size: 20, total: 0 } }); + }); +}); diff --git a/apps/job/src/modules/internal-jobs/directory-company-ids.controller.ts b/apps/job/src/modules/internal-jobs/directory-company-ids.controller.ts new file mode 100644 index 0000000..1ee174a --- /dev/null +++ b/apps/job/src/modules/internal-jobs/directory-company-ids.controller.ts @@ -0,0 +1,28 @@ +import { InternalCallers, ServiceTokenGuard, ServiceTokenPolicy } from '@internpath/common'; +import type { JobCategory } from '@internpath/contracts'; +import { Controller, Get, Query, UseGuards } from '@nestjs/common'; +import { IsEnum, IsOptional, IsUUID } from 'class-validator'; +import { JobCategory as JobCategoryEnum } from '../../../generated/client'; +import { DirectoryCompanyIdsService } from './directory-company-ids.service'; + +class CompanyIdsQuery { + @IsEnum(JobCategoryEnum) + category!: JobCategory; + + @IsOptional() + @IsUUID() + after?: string; +} + +@Controller('internal/v1/directory/company-ids') +@UseGuards(ServiceTokenGuard) +@ServiceTokenPolicy({ audience: 'job', secretEnvByCaller: { identity: 'JOB_SERVICE_SECRET_IDENTITY' } }) +@InternalCallers('identity') +export class DirectoryCompanyIdsController { + constructor(private readonly service: DirectoryCompanyIdsService) {} + + @Get() + list(@Query() query: CompanyIdsQuery) { + return this.service.list(query.category, query.after?.toLowerCase()); + } +} diff --git a/apps/job/src/modules/internal-jobs/directory-company-ids.service.ts b/apps/job/src/modules/internal-jobs/directory-company-ids.service.ts new file mode 100644 index 0000000..d2bf29d --- /dev/null +++ b/apps/job/src/modules/internal-jobs/directory-company-ids.service.ts @@ -0,0 +1,23 @@ +import type { DirectoryCompanyIdsResponse, JobCategory } from '@internpath/contracts'; +import { Injectable } from '@nestjs/common'; +import { Prisma } from '../../../generated/client'; +import { PrismaService } from '../../prisma/prisma.service'; + +export const DIRECTORY_COMPANY_IDS_PAGE_SIZE = 1000; + +@Injectable() +export class DirectoryCompanyIdsService { + constructor(private readonly db: PrismaService) {} + + async list(category: JobCategory, after?: string): Promise { + const rows = await this.db.$queryRaw>` + SELECT DISTINCT company_id FROM jobs + WHERE status = 'PUBLISHED' AND category = ${category}::job_category + ${after ? Prisma.sql`AND company_id > ${after}::uuid` : Prisma.empty} + ORDER BY company_id ASC LIMIT ${DIRECTORY_COMPANY_IDS_PAGE_SIZE + 1} + `; + const hasMore = rows.length > DIRECTORY_COMPANY_IDS_PAGE_SIZE; + const ids = rows.slice(0, DIRECTORY_COMPANY_IDS_PAGE_SIZE).map((row) => row.company_id); + return { company_ids: ids, next_cursor: hasMore ? ids.at(-1)! : null }; + } +} diff --git a/apps/job/src/modules/internal-jobs/internal-jobs.module.ts b/apps/job/src/modules/internal-jobs/internal-jobs.module.ts index 049d89b..7ad9ea8 100644 --- a/apps/job/src/modules/internal-jobs/internal-jobs.module.ts +++ b/apps/job/src/modules/internal-jobs/internal-jobs.module.ts @@ -1,6 +1,8 @@ import { ServiceTokenGuard } from '@internpath/common'; import { Module } from '@nestjs/common'; import { PrismaModule } from '../../prisma/prisma.module'; +import { DirectoryCompanyIdsController } from './directory-company-ids.controller'; +import { DirectoryCompanyIdsService } from './directory-company-ids.service'; import { InternalJobsController } from './internal-jobs.controller'; import { InternalJobsService } from './internal-jobs.service'; import { LifecycleReservationClient } from './lifecycle-reservation.client'; @@ -9,10 +11,11 @@ import { QuotaService } from './quota.service'; @Module({ imports: [PrismaModule], - controllers: [InternalJobsController], + controllers: [InternalJobsController, DirectoryCompanyIdsController], providers: [ ServiceTokenGuard, InternalJobsService, + DirectoryCompanyIdsService, QuotaService, LifecycleReservationClient, QuotaReconciliationService, diff --git a/apps/job/test/integration/internal-jobs.spec.ts b/apps/job/test/integration/internal-jobs.spec.ts index 681dfb8..9a1a00b 100644 --- a/apps/job/test/integration/internal-jobs.spec.ts +++ b/apps/job/test/integration/internal-jobs.spec.ts @@ -37,7 +37,8 @@ describe('Internal Job API (HTTP and real PostgreSQL)', function () { before(async function () { await dbReachableOrSkip(this); db = await createTestDatabase(); - config = new ConfigService({ JOB_DATABASE_URL: db.url, JOB_SERVICE_SECRET_LIFECYCLE: secret }); + config = new ConfigService({ JOB_DATABASE_URL: db.url, JOB_SERVICE_SECRET_LIFECYCLE: secret, + JOB_SERVICE_SECRET_IDENTITY: secret }); const module = await Test.createTestingModule({ imports: [ConfigModule.forRoot({ isGlobal: true, ignoreEnvFile: true }), InternalJobsModule], }) @@ -58,6 +59,26 @@ describe('Internal Job API (HTTP and real PostgreSQL)', function () { }); const http = () => request(app.getHttpServer()); + const directory = (category: string, after?: string) => http() + .get(`/internal/v1/directory/company-ids?category=${category}${after ? `&after=${after}` : ''}`) + .auth(signServiceToken({ issuer: 'identity', audience: 'job', secret }), { type: 'bearer' }); + + it('returns distinct company ids from published jobs in the requested category', async () => { + const first = await seedJob(db.prisma, 'PUBLISHED'); + await seedJob(db.prisma, 'PUBLISHED', { companyId: first.companyId }); + const second = await seedJob(db.prisma, 'PUBLISHED', { category: 'BUSINESS_MARKETING' }); + await seedJob(db.prisma, 'CLOSED', { category: 'TECH_IT' }); + const result = await directory('TECH_IT').expect(200); + expect(result.body.company_ids).to.include(first.companyId); + expect(result.body.company_ids).not.to.include(second.companyId); + expect(result.body.company_ids.filter((id: string) => id === first.companyId)).to.have.length(1); + expect(result.body.next_cursor).to.equal(null); + const after = await directory('TECH_IT', first.companyId).expect(200); + expect(after.body.company_ids).not.to.include(first.companyId); + await directory('INVALID').expect(400); + await http().get('/internal/v1/directory/company-ids?category=TECH_IT').expect(401); + await http().get('/internal/v1/directory/company-ids?category=TECH_IT').auth(token(), { type: 'bearer' }).expect(401); + }); const get = (id: string) => http().get(path(id)).auth(token(), { type: 'bearer' }); const post = (jobId: string, operation: string, applicationId: string, extra = {}) => http() diff --git a/apps/job/test/unit/directory-company-ids.service.spec.ts b/apps/job/test/unit/directory-company-ids.service.spec.ts new file mode 100644 index 0000000..fababa5 --- /dev/null +++ b/apps/job/test/unit/directory-company-ids.service.spec.ts @@ -0,0 +1,15 @@ +import { randomUUID } from 'node:crypto'; +import { expect } from 'chai'; +import { DirectoryCompanyIdsService, DIRECTORY_COMPANY_IDS_PAGE_SIZE } from '../../src/modules/internal-jobs/directory-company-ids.service'; +import { PrismaService } from '../../src/prisma/prisma.service'; + +describe('Directory company IDs paging', () => { + it('uses the last returned company as cursor when another page exists', async () => { + const rows = Array.from({ length: DIRECTORY_COMPANY_IDS_PAGE_SIZE + 1 }, () => ({ company_id: randomUUID() })); + const db = { $queryRaw: async () => rows } as unknown as PrismaService; + const result = await new DirectoryCompanyIdsService(db).list('TECH_IT'); + expect(result.company_ids).to.have.length(DIRECTORY_COMPANY_IDS_PAGE_SIZE); + expect(result.next_cursor).to.equal(rows[DIRECTORY_COMPANY_IDS_PAGE_SIZE - 1].company_id); + expect(result.company_ids).not.to.include(rows[DIRECTORY_COMPANY_IDS_PAGE_SIZE].company_id); + }); +}); diff --git a/apps/web/src/app/admin/advisors/page.tsx b/apps/web/src/app/admin/advisors/page.tsx new file mode 100644 index 0000000..ece4e6d --- /dev/null +++ b/apps/web/src/app/admin/advisors/page.tsx @@ -0,0 +1,6 @@ +import { Suspense } from 'react'; +import { AdminAdvisors } from '@/components/admin/identity/admin-advisors'; + +export default function AdvisorsPage() { + return กำลังโหลด…

}>
; +} diff --git a/apps/web/src/app/admin/companies/page.tsx b/apps/web/src/app/admin/companies/page.tsx new file mode 100644 index 0000000..30ab434 --- /dev/null +++ b/apps/web/src/app/admin/companies/page.tsx @@ -0,0 +1,3 @@ +import { AdminCompanies } from '@/components/admin/identity/admin-companies'; + +export default function CompaniesPage() { return ; } diff --git a/apps/web/src/app/admin/identity-audit/page.tsx b/apps/web/src/app/admin/identity-audit/page.tsx new file mode 100644 index 0000000..92c7dc2 --- /dev/null +++ b/apps/web/src/app/admin/identity-audit/page.tsx @@ -0,0 +1,3 @@ +import { IdentityAuditLog } from '@/components/admin/identity/identity-audit-log'; + +export default function IdentityAuditPage() { return ; } diff --git a/apps/web/src/app/admin/users/page.tsx b/apps/web/src/app/admin/users/page.tsx new file mode 100644 index 0000000..d70ba50 --- /dev/null +++ b/apps/web/src/app/admin/users/page.tsx @@ -0,0 +1,3 @@ +import { AdminUsers } from '@/components/admin/identity/admin-users'; + +export default function UsersPage() { return ; } diff --git a/apps/web/src/components/admin/admin-nav-icons.ts b/apps/web/src/components/admin/admin-nav-icons.ts index 808cd8e..aac84b2 100644 --- a/apps/web/src/components/admin/admin-nav-icons.ts +++ b/apps/web/src/components/admin/admin-nav-icons.ts @@ -24,6 +24,7 @@ export const ADMIN_NAV_ICONS: Record = { 'บริษัท': Building2, 'อาจารย์ที่ปรึกษา': GraduationCap, 'ผู้ใช้': Users, + 'Audit log (Identity)': ScrollText, 'ใบสมัครที่รอดำเนินการ': FileText, 'รายงานปัญหา': TriangleAlert, 'ใบรับรอง': Award, diff --git a/apps/web/src/components/admin/admin-nav.ts b/apps/web/src/components/admin/admin-nav.ts index 312d2a1..d458d2d 100644 --- a/apps/web/src/components/admin/admin-nav.ts +++ b/apps/web/src/components/admin/admin-nav.ts @@ -17,9 +17,10 @@ export const ADMIN_NAV: AdminNavGroup[] = [ { title: 'บัญชีและองค์กร', owner: 'SA', items: [ - { label: 'บริษัท', href: null }, - { label: 'อาจารย์ที่ปรึกษา', href: null }, - { label: 'ผู้ใช้', href: null }, + { label: 'บริษัท', href: '/admin/companies' }, + { label: 'อาจารย์ที่ปรึกษา', href: '/admin/advisors' }, + { label: 'ผู้ใช้', href: '/admin/users' }, + { label: 'Audit log (Identity)', href: '/admin/identity-audit' }, ], }, { diff --git a/apps/web/src/components/admin/identity/admin-advisors.tsx b/apps/web/src/components/admin/identity/admin-advisors.tsx new file mode 100644 index 0000000..9881c53 --- /dev/null +++ b/apps/web/src/components/admin/identity/admin-advisors.tsx @@ -0,0 +1,96 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { useSearchParams } from 'next/navigation'; +import type { AdminAdvisorListItem, Paginated } from '@internpath/contracts'; +import { useAuth } from '@/auth/session'; +import { FilterSelect, Notice } from '@/components/admin/filter-fields'; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const statusOptions: Array<[string, string]> = [['PENDING_APPROVAL', 'รออนุมัติ'], ['ACTIVE', 'ใช้งานอยู่'], ['', 'ทั้งหมด']]; + +export function AdminAdvisors() { + const { request } = useAuth(); + const params = useSearchParams(); + const [status, setStatus] = useState('PENDING_APPROVAL'); + const [page, setPage] = useState(1); + const [result, setResult] = useState | null>(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [notice, setNotice] = useState(''); + const [reload, setReload] = useState(0); + const [busy, setBusy] = useState(false); + const [rejectId, setRejectId] = useState(null); + const [reason, setReason] = useState(''); + const [studentId, setStudentId] = useState(params.get('student') ?? ''); + const [advisorId, setAdvisorId] = useState(''); + + useEffect(() => { + let active = true; + setLoading(true); + const query = new URLSearchParams({ page: String(page) }); + if (status) query.set('status', status); + request>(`/admin/advisors?${query}`) + .then((data) => { if (active) { setResult(data); setError(''); } }) + .catch((cause) => { if (active) setError(cause instanceof Error ? cause.message : 'โหลดรายชื่อไม่สำเร็จ'); }) + .finally(() => { if (active) setLoading(false); }); + return () => { active = false; }; + }, [request, status, page, reload]); + + async function decide(id: string, action: 'approve' | 'reject') { + if (action === 'reject' && !reason.trim()) { setError('กรุณาระบุเหตุผลที่ปฏิเสธ'); return; } + setBusy(true); setError(''); setNotice(''); + try { + await request(`/admin/advisors/${id}/actions/${action}`, { method: 'POST', body: action === 'reject' ? { reason: reason.trim() } : {} }); + setNotice(action === 'approve' ? 'อนุมัติอาจารย์แล้ว' : 'ปฏิเสธบัญชีอาจารย์แล้ว'); + setRejectId(null); setReason(''); setReload((value) => value + 1); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'ดำเนินการไม่สำเร็จ'); } + finally { setBusy(false); } + } + + async function moveStudent(event: React.FormEvent) { + event.preventDefault(); + if (!UUID.test(studentId.trim()) || !UUID.test(advisorId.trim())) { setError('รหัสนักศึกษาและอาจารย์ต้องเป็น UUID'); return; } + if (studentId.trim() === advisorId.trim()) { setError('กรุณาเลือกบัญชีคนละรายการ'); return; } + setBusy(true); setError(''); setNotice(''); + try { + await request(`/admin/students/${studentId.trim()}/advisor`, { method: 'POST', body: { advisor_id: advisorId.trim() } }); + setNotice('ย้ายนักศึกษาไปยังอาจารย์คนใหม่แล้ว'); setStudentId(''); setAdvisorId(''); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'ย้ายอาจารย์ไม่สำเร็จ'); } + finally { setBusy(false); } + } + + const lastPage = Math.max(1, Math.ceil((result?.meta.total ?? 0) / 20)); + return
+

อาจารย์ที่ปรึกษา

พิจารณาบัญชีที่ยืนยันอีเมลแล้ว และย้ายนักศึกษาเมื่อจำเป็น

+ {error && {error}} + {notice && {notice}} +
+

บัญชีอาจารย์

+ { setStatus(value); setPage(1); }} />
+ {loading ?

กำลังโหลด…

: !result?.data.length ? +

ไม่มีอาจารย์ในสถานะนี้

: +
{result.data.map((item) =>
+

{item.full_name}

+

{item.email}{item.department ? ` · ${item.department}` : ''}

+

{item.status} · {new Date(item.created_at).toLocaleDateString('th-TH')}

+ {item.status === 'PENDING_APPROVAL' &&
+ + +
}
+ {rejectId === item.id &&
setReason(event.target.value)} maxLength={1000} placeholder="เหตุผลที่ปฏิเสธ" className="min-w-60 flex-1 rounded-lg border border-border px-3 py-2 text-sm" /> + +
} +
)}
} +
{page} / {lastPage}
+
+

ย้ายอาจารย์ของนักศึกษา

+

ค้นหารหัสบัญชีจากหน้า ผู้ใช้ ระบบรับเฉพาะอาจารย์ที่ใช้งานอยู่ในมหาวิทยาลัยเดียวกัน

+
void moveStudent(event)} className="mt-4 flex flex-wrap items-end gap-3"> + + + +
+
+
; +} diff --git a/apps/web/src/components/admin/identity/admin-companies.tsx b/apps/web/src/components/admin/identity/admin-companies.tsx new file mode 100644 index 0000000..576ccff --- /dev/null +++ b/apps/web/src/components/admin/identity/admin-companies.tsx @@ -0,0 +1,118 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import type { AdminCompanyDetail, AdminCompanyListItem, Paginated } from '@internpath/contracts'; +import { useAuth } from '@/auth/session'; +import { FilterSelect, Notice } from '@/components/admin/filter-fields'; + +type Action = 'verify' | 'need-more-info' | 'reject' | 'suspend' | 'unsuspend'; +const statusOptions: Array<[string, string]> = [['PENDING', 'รอตรวจ'], ['NEED_MORE_INFO', 'รอเอกสารเพิ่ม'], ['VERIFIED', 'ผ่านการตรวจ'], ['REJECTED', 'ปฏิเสธ'], ['SUSPENDED', 'ระงับ'], ['', 'ทั้งหมด']]; +const actionLabels: Record = { verify: 'อนุมัติ', 'need-more-info': 'ขอข้อมูลเพิ่ม', reject: 'ปฏิเสธ', suspend: 'ระงับ', unsuspend: 'ยกเลิกการระงับ' }; +const availableActions: Record = { PENDING: ['verify', 'need-more-info', 'reject'], VERIFIED: ['suspend'], SUSPENDED: ['unsuspend'] }; + +export function AdminCompanies() { + const { request } = useAuth(); + const [status, setStatus] = useState('PENDING'); + const [page, setPage] = useState(1); + const [reload, setReload] = useState(0); + const [result, setResult] = useState | null>(null); + const [selectedId, setSelectedId] = useState(null); + const [detail, setDetail] = useState(null); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [action, setAction] = useState(null); + const [reason, setReason] = useState(''); + const [ownerId, setOwnerId] = useState(''); + const [error, setError] = useState(''); + const [notice, setNotice] = useState(''); + + useEffect(() => { + let active = true; + setLoading(true); + const query = new URLSearchParams({ page: String(page) }); + if (status) query.set('status', status); + request>(`/admin/companies?${query}`) + .then((data) => { if (active) { setResult(data); setError(''); } }) + .catch((cause) => { if (active) setError(cause instanceof Error ? cause.message : 'โหลดบริษัทไม่สำเร็จ'); }) + .finally(() => { if (active) setLoading(false); }); + return () => { active = false; }; + }, [request, status, page, reload]); + + useEffect(() => { + if (!selectedId) { setDetail(null); return; } + let active = true; + request(`/admin/companies/${selectedId}`) + .then((data) => { if (active) { setDetail(data); setError(''); } }) + .catch((cause) => { if (active) { setDetail(null); setError(cause instanceof Error ? cause.message : 'โหลดรายละเอียดไม่สำเร็จ'); } }); + return () => { active = false; }; + }, [request, selectedId, reload]); + + async function runAction() { + if (!selectedId || !action) return; + if (['need-more-info', 'reject', 'suspend'].includes(action) && !reason.trim()) { setError('กรุณาระบุเหตุผล'); return; } + setBusy(true); setError(''); setNotice(''); + try { + await request(`/admin/companies/${selectedId}/actions/${action}`, { method: 'POST', body: reason.trim() ? { reason: reason.trim() } : {} }); + setNotice(`${actionLabels[action]}บริษัทแล้ว`); setAction(null); setReason(''); setReload((value) => value + 1); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'ดำเนินการไม่สำเร็จ'); } + finally { setBusy(false); } + } + + async function updateFlag(path: string, body: unknown, success: string) { + if (!selectedId) return; + setBusy(true); setError(''); setNotice(''); + try { + await request(`/admin/companies/${selectedId}/${path}`, { method: 'PUT', body }); + setNotice(success); setReload((value) => value + 1); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'บันทึกไม่สำเร็จ'); } + finally { setBusy(false); } + } + + async function appointOwner(event: React.FormEvent) { + event.preventDefault(); + if (!selectedId) return; + setBusy(true); setError(''); setNotice(''); + try { + await request(`/admin/companies/${selectedId}/owner`, { method: 'POST', body: { user_id: ownerId.trim() } }); + setNotice('แต่งตั้ง Owner แล้ว'); setOwnerId(''); setReload((value) => value + 1); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'แต่งตั้ง Owner ไม่สำเร็จ'); } + finally { setBusy(false); } + } + + const lastPage = Math.max(1, Math.ceil((result?.meta.total ?? 0) / 20)); + return
+

บริษัท

ตรวจเอกสาร อนุมัติสถานะ และจัดการสิทธิ์ของบริษัท

+ {error && {error}}{notice && {notice}} +
+
+

รายชื่อบริษัท

{ setStatus(value); setPage(1); }} />
+ {loading ?

กำลังโหลด…

: !result?.data.length ?

ไม่มีบริษัทในสถานะนี้

: +
{result.data.map((item) => )}
} +
{page} / {lastPage}
+
+
+ {!selectedId ?

เลือกบริษัทเพื่อดูรายละเอียดและดำเนินการ

: !detail ?

กำลังโหลดรายละเอียด…

:
+

{detail.name}

{detail.status} · เลขทะเบียน {detail.registration_no} · {detail.email_domain}

+ {detail.review_note &&

หมายเหตุ: {detail.review_note}

} +

{detail.website && เว็บไซต์บริษัท}{detail.phone && ` · โทร ${detail.phone}`}

+

เอกสาร

{detail.documents.length ?
    {detail.documents.map((doc) =>
  • {doc.doc_type} ({Math.ceil(doc.size_bytes / 1024)} KB)
  • )}
:

ยังไม่มีเอกสาร

}
+

สมาชิก HR

{detail.members.length ?
    {detail.members.map((member) =>
  • + {member.full_name} · {member.email} · {member.member_role} + {member.user_id} + {!detail.members.some((entry) => entry.member_role === 'OWNER') && } +
  • )}
:

ยังไม่มีสมาชิก

}
+

พิจารณาสถานะ

{(availableActions[detail.status] ?? []).map((choice) => )}
+ {action &&

{actionLabels[action]}บริษัทนี้

setReason(event.target.value)} maxLength={1000} placeholder={['need-more-info', 'reject', 'suspend'].includes(action) ? 'เหตุผล (จำเป็น)' : 'หมายเหตุ (ถ้ามี)'} className="w-full rounded-lg border border-border px-3 py-2 text-sm" /> +
}
+

ป้ายและสิทธิ์พิเศษ

+ + +
+ {!detail.members.some((member) => member.member_role === 'OWNER') &&
void appointOwner(event)} className="border-t border-border pt-4">

แต่งตั้ง Owner

ใช้รหัสสมาชิก HR ของบริษัทนี้

setOwnerId(event.target.value)} required placeholder="รหัสผู้ใช้ (UUID)" className="min-w-60 flex-1 rounded-lg border border-border px-3 py-2 font-mono text-xs" />
} +
} +
+
+
; +} diff --git a/apps/web/src/components/admin/identity/admin-users.tsx b/apps/web/src/components/admin/identity/admin-users.tsx new file mode 100644 index 0000000..f9d0b54 --- /dev/null +++ b/apps/web/src/components/admin/identity/admin-users.tsx @@ -0,0 +1,81 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import type { AdminUserListItem, Paginated } from '@internpath/contracts'; +import { useAuth } from '@/auth/session'; +import { FilterSelect, Notice } from '@/components/admin/filter-fields'; + +const roles: Array<[string, string]> = [['', 'ทุกบทบาท'], ['STUDENT', 'นักศึกษา'], ['ADVISOR', 'อาจารย์'], ['COMPANY_HR', 'HR'], ['PLATFORM_ADMIN', 'Admin']]; +const statuses: Array<[string, string]> = [['', 'ทุกสถานะ'], ['ACTIVE', 'ใช้งานอยู่'], ['PENDING_EMAIL', 'รอยืนยันอีเมล'], ['PENDING_APPROVAL', 'รออนุมัติ'], ['SUSPENDED', 'ถูกระงับ']]; + +export function AdminUsers() { + const { request } = useAuth(); + const [q, setQ] = useState(''); + const [search, setSearch] = useState(''); + const [role, setRole] = useState(''); + const [status, setStatus] = useState(''); + const [page, setPage] = useState(1); + const [reload, setReload] = useState(0); + const [result, setResult] = useState | null>(null); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [actionId, setActionId] = useState(null); + const [reason, setReason] = useState(''); + const [error, setError] = useState(''); + const [notice, setNotice] = useState(''); + + useEffect(() => { + let active = true; + setLoading(true); + const query = new URLSearchParams({ page: String(page) }); + if (q) query.set('q', q); + if (role) query.set('role', role); + if (status) query.set('status', status); + request>(`/admin/users?${query}`) + .then((data) => { if (active) { setResult(data); setError(''); } }) + .catch((cause) => { if (active) setError(cause instanceof Error ? cause.message : 'โหลดรายชื่อผู้ใช้ไม่สำเร็จ'); }) + .finally(() => { if (active) setLoading(false); }); + return () => { active = false; }; + }, [request, q, role, status, page, reload]); + + async function changeStatus(item: AdminUserListItem) { + const action = item.status === 'SUSPENDED' ? 'unsuspend' : 'suspend'; + if (action === 'suspend' && !reason.trim()) { setError('กรุณาระบุเหตุผลที่ระงับบัญชี'); return; } + setBusy(true); setError(''); setNotice(''); + try { + await request(`/admin/users/${item.id}/actions/${action}`, { method: 'POST', body: action === 'suspend' ? { reason: reason.trim() } : {} }); + setNotice(action === 'suspend' ? 'ระงับบัญชีแล้ว' : 'ยกเลิกการระงับบัญชีแล้ว'); + setReason(''); setActionId(null); setReload((value) => value + 1); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'เปลี่ยนสถานะไม่สำเร็จ'); } + finally { setBusy(false); } + } + + const lastPage = Math.max(1, Math.ceil((result?.meta.total ?? 0) / 20)); + return
+

ผู้ใช้

ค้นหาบัญชี ตรวจสถานะ และจัดการการระงับบัญชี

+ {error && {error}}{notice && {notice}} +
+
{ event.preventDefault(); setQ(search.trim()); setPage(1); }} className="flex min-w-64 flex-1 items-end gap-2"> + + +
+ { setRole(value); setPage(1); }} /> + { setStatus(value); setPage(1); }} /> +
+
+ {loading ?

กำลังโหลด…

: !result?.data.length ?

ไม่พบบัญชีที่ตรงกับตัวกรอง

: +
{result.data.map((item) =>
+

{item.full_name}

+

{item.email}

{item.role} · {item.status}{item.student_code ? ` · ${item.student_code}` : ''}

+

{item.id}

+ {item.advisor_id &&

อาจารย์: {item.advisor_id}

}
+
{item.role === 'STUDENT' && item.status === 'ACTIVE' && ย้ายอาจารย์} + {(item.status === 'ACTIVE' || item.status === 'SUSPENDED') && }
+ {actionId === item.id &&
setReason(event.target.value)} maxLength={1000} placeholder="เหตุผลที่ระงับบัญชี" className="min-w-60 flex-1 rounded-lg border border-border px-3 py-2 text-sm" /> + +
} +
)}
} +
{page} / {lastPage}
+
+
; +} diff --git a/apps/web/src/components/admin/identity/identity-audit-log.tsx b/apps/web/src/components/admin/identity/identity-audit-log.tsx new file mode 100644 index 0000000..4c3eb4d --- /dev/null +++ b/apps/web/src/components/admin/identity/identity-audit-log.tsx @@ -0,0 +1,120 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import type { Paginated } from '@internpath/contracts'; +import { useAuth } from '@/auth/session'; +import { Notice } from '@/components/admin/filter-fields'; + +type AuditEntry = { + id: string; + admin_id: string; + action: string; + target_type: string; + target_id: string; + before: unknown; + after: unknown; + reason: string | null; + correlation_id: string; + occurred_at: string; +}; + +const PAGE_SIZE = 20; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function JsonValue({ label, value }: { label: string; value: unknown }) { + return
+

{label}

+
+      {value === null || value === undefined ? '—' : JSON.stringify(value, null, 2)}
+    
+
; +} + +export function IdentityAuditLog() { + const { request } = useAuth(); + const [actionText, setActionText] = useState(''); + const [action, setAction] = useState(''); + const [targetTypeText, setTargetTypeText] = useState(''); + const [targetType, setTargetType] = useState(''); + const [targetIdText, setTargetIdText] = useState(''); + const [targetId, setTargetId] = useState(''); + const [adminIdText, setAdminIdText] = useState(''); + const [adminId, setAdminId] = useState(''); + const [page, setPage] = useState(1); + const [result, setResult] = useState | null>(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [openId, setOpenId] = useState(null); + + useEffect(() => { + let active = true; + const query = new URLSearchParams({ page: String(page), page_size: String(PAGE_SIZE) }); + if (action) query.set('action', action); + if (targetType) query.set('target_type', targetType); + if (targetId) query.set('target_id', targetId); + if (adminId) query.set('admin_id', adminId); + setLoading(true); + setError(''); + request>(`/admin/audit-logs?${query}`) + .then((data) => { if (active) setResult(data); }) + .catch((cause) => { if (active) { setResult(null); setError(cause instanceof Error ? cause.message : 'โหลด Audit log ไม่สำเร็จ'); } }) + .finally(() => { if (active) setLoading(false); }); + return () => { active = false; }; + }, [request, action, targetType, targetId, adminId, page]); + + function submit(event: React.FormEvent) { + event.preventDefault(); + const nextTargetId = targetIdText.trim(); + const nextAdminId = adminIdText.trim(); + if ((nextTargetId && !UUID.test(nextTargetId)) || (nextAdminId && !UUID.test(nextAdminId))) { + setError('รหัสเป้าหมายและรหัสผู้ดูแลต้องเป็น UUID'); + return; + } + setError(''); + setAction(actionText.trim()); + setTargetType(targetTypeText.trim()); + setTargetId(nextTargetId); + setAdminId(nextAdminId); + setPage(1); + } + + const lastPage = Math.max(1, Math.ceil((result?.meta.total ?? 0) / PAGE_SIZE)); + return
+

Audit log ของ Identity

+

ดูการเปลี่ยนแปลงบัญชี อาจารย์ และบริษัท โดยเรียงรายการใหม่ก่อน

+
+ {[ + { label: 'การกระทำ', value: actionText, set: setActionText, max: 100 }, + { label: 'ชนิดเป้าหมาย', value: targetTypeText, set: setTargetTypeText, max: 50 }, + { label: 'รหัสเป้าหมาย', value: targetIdText, set: setTargetIdText, max: 36 }, + { label: 'รหัสผู้ดูแล', value: adminIdText, set: setAdminIdText, max: 36 }, + ].map((field) => )} + +
+ {error && {error}} +
+ {loading ?

กำลังโหลด…

: !result?.data.length ? +

ไม่พบรายการที่ตรงกับตัวกรอง

: +
{result.data.map((entry) =>
+
+

{entry.action} · {entry.target_type}

+

เป้าหมาย {entry.target_id} · ผู้ดูแล {entry.admin_id}

+

{new Date(entry.occurred_at).toLocaleString('th-TH')} · Correlation ID {entry.correlation_id}

+ {entry.reason &&

เหตุผล: {entry.reason}

} +
+ {openId === entry.id &&
+ +
} +
)}
} + +
+
; +} diff --git a/apps/web/src/components/companies/company-list.tsx b/apps/web/src/components/companies/company-list.tsx index 42d2081..2796ceb 100644 --- a/apps/web/src/components/companies/company-list.tsx +++ b/apps/web/src/components/companies/company-list.tsx @@ -9,6 +9,7 @@ import { Notice } from '@/components/admin/filter-fields'; import { Avatar } from '@/components/ui/avatar'; import { RatingSummary } from '@/components/ui/rating'; import { ApiError } from '@/lib/api'; +import { CATEGORIES } from '@/lib/categories'; import { listCompanies } from '@/lib/directory'; const PAGE_SIZE = 12; @@ -20,6 +21,8 @@ export function CompanyList() { const { request } = useAuth(); const q = searchParams.get('q')?.trim() ?? ''; const partner = searchParams.get('partner') === 'true'; + const categoryParam = searchParams.get('category'); + const category = CATEGORIES.find((item) => item.id === categoryParam)?.id; const pageParam = Number(searchParams.get('page')); const page = Number.isInteger(pageParam) && pageParam >= 1 ? pageParam : 1; @@ -33,13 +36,12 @@ export function CompanyList() { let cancelled = false; setResult(null); setError(null); - // เส้นทางสาธารณะ (ไม่ต้องล็อกอิน) — `request` ส่ง token เมื่อมี (ดูหมายเหตุใน lib/directory.ts เรื่องฉบับชั่วคราวของ Identity) - listCompanies(request, { q: q || undefined, partner }, page, PAGE_SIZE).then( + listCompanies(request, { q: q || undefined, category, partner }, page, PAGE_SIZE).then( (data) => { if (!cancelled) setResult(data); }, (cause) => { if (!cancelled) setError(cause instanceof ApiError ? cause.message : 'โหลดรายชื่อบริษัทไม่สำเร็จ กรุณาลองใหม่'); }, ); return () => { cancelled = true; }; - }, [request, q, partner, page]); + }, [request, q, category, partner, page]); function update(changes: Record, keepPage = false) { const next = new URLSearchParams(searchParams.toString()); @@ -62,6 +64,14 @@ export function CompanyList() { setText(event.target.value)} placeholder="ค้นหาชื่อบริษัท" className="w-full rounded-lg border border-border bg-surface px-3 py-2 text-base outline-none focus:border-primary" /> +