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
28 changes: 20 additions & 8 deletions apps/lifecycle/src/common/auth/category-scope.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AppException, type JwtClaims } from '@internpath/common';
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import type { JobCategory } from '../../../generated/client';
import { mapWithConcurrency } from '../async/concurrency';
import { JobInternalClient } from '../../internal/job-client.service';
Expand All @@ -15,6 +15,8 @@ const CATEGORY_LOOKUP_CONCURRENCY = 5;
*/
@Injectable()
export class CategoryScopeService {
private readonly logger = new Logger(CategoryScopeService.name);

constructor(
private readonly db: PrismaService,
private readonly job: JobInternalClient,
Expand Down Expand Up @@ -52,22 +54,32 @@ export class CategoryScopeService {
}
}

/** `job_id` ของบริษัทที่อยู่ในสายงานของผู้เรียก (`null` = ไม่จำกัด) — เติมสายงานที่ยังว่างของประกาศที่มีใบสมัครก่อน */
async jobIdsInScope(user: JwtClaims, companyId: string, correlationId?: string): Promise<string[] | null> {
/**
* `job_id` ของบริษัทที่อยู่ในสายงานของผู้เรียก (`null` = ไม่จำกัด) — เติมสายงานที่ยังว่างของประกาศที่มีใบสมัครก่อน
* - `category` (`?category=`): HR Member ขอสายที่ไม่ใช่ของตน ⇒ `[]` (รายการว่าง ไม่ error); Owner กรองได้ทุกสาย (PM ตัดสิน 2026-11-21)
* - ถามสายงานจาก Job ไม่สำเร็จ ⇒ ตัดประกาศนั้นออก + log warn (ไม่ทำให้รายการพังทั้งหน้า — PM ตัดสิน 2026-11-21)
*/
async jobIdsInScope(user: JwtClaims, companyId: string, correlationId?: string, category?: JobCategory): Promise<string[] | null> {
const scope = this.scopeOf(user);
if (scope === null) return null;
if (scope.length === 0) return [];
const allowed = category ? (scope === null || scope.includes(category) ? [category] : []) : scope;
if (allowed === null) return null;
if (allowed.length === 0) return [];
const applied = await this.db.application.findMany({ where: { companyId }, distinct: ['jobId'], select: { jobId: true } });
const ids = applied.map((row) => row.jobId);
const known = await this.db.jobSnapshot.findMany({ where: { jobId: { in: ids } }, select: { jobId: true, category: true } });
const byId = new Map(known.map((row) => [row.jobId, row.category]));
const missing = ids.filter((id) => !byId.get(id));
await mapWithConcurrency(missing, CATEGORY_LOOKUP_CONCURRENCY, async (id) => {
byId.set(id, await this.categoryOf(id, correlationId));
try {
byId.set(id, await this.categoryOf(id, correlationId));
} catch {
this.logger.warn(`ถามสายงานของประกาศ ${id} จาก Job ไม่สำเร็จ — ตัดออกจากรายการใบสมัคร`);
byId.set(id, null);
}
});
return ids.filter((id) => {
const category = byId.get(id);
return !!category && scope.includes(category);
const jobCategory = byId.get(id);
return !!jobCategory && allowed.includes(jobCategory);
});
}
}
8 changes: 6 additions & 2 deletions apps/lifecycle/src/modules/advisor/advisor.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ export class AdvisorController {

/** รายชื่อนักศึกษาในความดูแล + ตัวกรองชั้นปี/กำลังฝึก/ฝึกเสร็จแล้ว (ต้องประกาศก่อน `students/:id/overview`) */
@Get('students')
students(@CurrentUser() user: JwtClaims, @Query() query: AdvisorStudentsQueryDto): Promise<Paginated<AdvisorTrainingStudentItem>> {
return this.service.students(user, query);
students(
@CurrentUser() user: JwtClaims,
@Query() query: AdvisorStudentsQueryDto,
@Headers('x-correlation-id') cid?: string,
): Promise<Paginated<AdvisorTrainingStudentItem>> {
return this.service.students(user, query, cid);
}

@Get('students/:id/overview')
Expand Down
4 changes: 2 additions & 2 deletions apps/lifecycle/src/modules/advisor/advisor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class AdvisorService {
* ชื่อ/รหัส/สาขา/ชั้นปีดึงสดจาก Identity `students/summaries` ทุกครั้ง **ห้ามเก็บ `full_name` ลง DB/cache/Event/log**
* ตัวกรองชั้นปี/คำค้นอยู่ที่ Identity จึงกรองหลังดึงสรุป แล้วแบ่งหน้า (รายชื่อในความดูแลของอาจารย์หนึ่งคนมีจำนวนจำกัด)
*/
async students(user: JwtClaims, query: AdvisorStudentsQueryDto): Promise<Paginated<AdvisorTrainingStudentItem>> {
async students(user: JwtClaims, query: AdvisorStudentsQueryDto, correlationId?: string): Promise<Paginated<AdvisorTrainingStudentItem>> {
const page = query.page ?? 1;
const pageSize = query.page_size ?? 20;
const links = await this.db.studentAdvisorLink.findMany({
Expand Down Expand Up @@ -99,7 +99,7 @@ export class AdvisorService {

const summaries = new Map<string, { full_name: string; student_code: string; major: string; year_level: number }>();
for (let i = 0; i < candidates.length; i += STUDENT_NAMES_BATCH_MAX) {
for (const row of await this.identity.getStudentSummaries(candidates.slice(i, i + STUDENT_NAMES_BATCH_MAX))) summaries.set(row.user_id, row);
for (const row of await this.identity.getStudentSummaries(candidates.slice(i, i + STUDENT_NAMES_BATCH_MAX), correlationId)) summaries.set(row.user_id, row);
}
const q = query.q?.trim().toLocaleLowerCase('th-TH');
const matched = candidates.filter((id) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,11 +201,16 @@ export class CertificatesService {

// ---------- เพิกถอน ----------

/** `POST /hr/certificates/{id}/actions/revoke` — เฉพาะใบที่บริษัทตนออก (UAT-23 ข้อ 2: บริษัทอื่น ⇒ 403) */
/**
* `POST /hr/certificates/{id}/actions/revoke` — เฉพาะใบที่บริษัทตนออก (UAT-23 ข้อ 2: บริษัทอื่น ⇒ 403)
* • HR Member นอกสายงานของประกาศ ⇒ 403 `FORBIDDEN_ROLE` (`FORBIDDEN_CATEGORY`) แบบเดียวกับตอนออกใบ (PM ตัดสิน 2026-11-21)
*/
async revokeByHr(user: JwtClaims, certificateId: string, reason: string | undefined, correlationId?: string, now = new Date()) {
const cert = await this.db.certificate.findUnique({ where: { id: certificateId } });
if (!cert) throw certificateNotFound();
assertCompanyOwnership(user, cert.companyId);
const app = await this.db.application.findUniqueOrThrow({ where: { id: cert.applicationId }, select: { jobId: true } });
await this.scope.assertInScope(user, app, correlationId);
return this.revoke(cert, user.sub, 'COMPANY_HR', reason, correlationId, now);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,12 @@ export class HrApplicationsController {
constructor(private readonly service: HrApplicationsService) {}

@Get()
list(@CurrentUser() user: JwtClaims, @Query() query: HrApplicationsQueryDto): Promise<Paginated<HrApplicationItem>> {
return this.service.list(user, query);
list(
@CurrentUser() user: JwtClaims,
@Query() query: HrApplicationsQueryDto,
@Headers('x-correlation-id') cid?: string,
): Promise<Paginated<HrApplicationItem>> {
return this.service.list(user, query, cid);
}

@Get(':id')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
HrRejectRequest,
HrStartRequest,
HrTerminateRequest,
JobCategory,
} from '@internpath/contracts';
import { Transform } from 'class-transformer';
import { IsDateString, IsIn, IsOptional, IsString, IsUUID, Matches, MaxLength } from 'class-validator';
Expand All @@ -24,7 +25,10 @@ const DateOnly = (): PropertyDecorator => (target, key) => {
/** หมายเหตุประกอบผลประเมิน — เอกสารไม่กำหนด ใช้ขอบเขตเดียวกับข้อความยาวของ 1.4 */
export const EVALUATION_NOTE_MAX = APPLICATION_LIMITS.STATEMENT_MAX;

/** GET /hr/applications — `?job_id=&status=` + Pagination มาตรฐาน */
/** ค่าของ `?category=` (ตรงกับ enum `job_category`) */
export const JOB_CATEGORIES: readonly JobCategory[] = ['TECH_IT', 'BUSINESS_MARKETING', 'CORPORATE_SERVICES'];

/** GET /hr/applications — `?job_id=&status=&category=` + Pagination มาตรฐาน */
export class HrApplicationsQueryDto extends PageQueryDto implements HrApplicationsQuery {
@IsOptional()
@IsUUID()
Expand All @@ -33,6 +37,10 @@ export class HrApplicationsQueryDto extends PageQueryDto implements HrApplicatio
@IsOptional()
@IsIn(APPLICATION_STATUSES)
status?: ApplicationStatus;

@IsOptional()
@IsIn(JOB_CATEGORIES)
category?: JobCategory;
}

/** ช่วงฝึก ≥ 30 วันตรวจใน Guard `periodMin30Days` ⇒ `422 INVALID_PERIOD_MIN_30_DAYS` */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ export class HrApplicationsService {

// ---------- GET ----------

async list(user: JwtClaims, query: HrApplicationsQueryDto): Promise<Paginated<HrApplicationItem>> {
async list(user: JwtClaims, query: HrApplicationsQueryDto, correlationId?: string): Promise<Paginated<HrApplicationItem>> {
const companyId = requireCompany(user);
const page = query.page ?? 1;
const pageSize = query.page_size ?? 20;
// HR Member เห็นเฉพาะประกาศในสายงานของตน (Owner = ทุกสายงาน)
const scopedJobIds = await this.scope.jobIdsInScope(user, companyId);
// HR Member เห็นเฉพาะประกาศในสายงานของตน (Owner = ทุกสายงาน) • `?category=` กรองเพิ่ม (Member ขอสายอื่น ⇒ รายการว่าง)
const scopedJobIds = await this.scope.jobIdsInScope(user, companyId, correlationId, query.category);
const where = {
companyId,
...(query.job_id ? { jobId: query.job_id } : {}),
Expand Down Expand Up @@ -104,7 +104,7 @@ export class HrApplicationsService {
correlationId?: string,
now = new Date(),
): Promise<HrApplicationDetail> {
const app = await this.companyApplication(user, applicationId);
const app = await this.companyApplication(user, applicationId, correlationId);
const [names, actions, profile, evaluation, certificate, minDays] = await Promise.all([
loadSnapshotNames(this.db, [app]),
this.stateMachine.availableActions(app, 'COMPANY_HR', now),
Expand All @@ -130,7 +130,7 @@ export class HrApplicationsService {

/** `accept` `{start_date, end_date}` — Guard: ไม่ Freeze, ไม่ยืนยันที่อื่น (403), ช่วง ≥ 30 วัน (422) → reserve โควตา (409 QUOTA_FULL) */
async accept(user: JwtClaims, applicationId: string, body: HrAcceptDto, correlationId?: string): Promise<HrApplicationDetail> {
await this.companyApplication(user, applicationId);
await this.companyApplication(user, applicationId, correlationId);
await this.execute(user, applicationId, {
trigger: 'accept',
input: { startDate: toDateOnly(body.start_date), endDate: toDateOnly(body.end_date) },
Expand All @@ -146,7 +146,7 @@ export class HrApplicationsService {
reason: string | undefined,
correlationId?: string,
): Promise<HrApplicationDetail> {
await this.companyApplication(user, applicationId);
await this.companyApplication(user, applicationId, correlationId);
await this.execute(user, applicationId, { trigger: action, reason }, correlationId);
return this.detail(user, applicationId, correlationId);
}
Expand All @@ -162,7 +162,7 @@ export class HrApplicationsService {
correlationId?: string,
now = new Date(),
): Promise<HrApplicationDetail & HrStartResponse> {
const app = await this.companyApplication(user, applicationId);
const app = await this.companyApplication(user, applicationId, correlationId);
const actualStart = toDateOnly(body.actual_start_date);
const startDate = body.start_date ? toDateOnly(body.start_date) : app.startDate;
const endDate = body.end_date ? toDateOnly(body.end_date) : app.endDate;
Expand Down Expand Up @@ -201,7 +201,7 @@ export class HrApplicationsService {
correlationId?: string,
now = new Date(),
): Promise<HrApplicationDetail> {
const app = await this.companyApplication(user, applicationId);
const app = await this.companyApplication(user, applicationId, correlationId);
if (body.actual_end_date) {
const actualEnd = toDateOnly(body.actual_end_date);
if (daysBetween(bangkokToday(now), actualEnd) > 0) throw validationFailed('actual_end_date', 'IN_FUTURE');
Expand All @@ -223,7 +223,7 @@ export class HrApplicationsService {
* `round = 2` เฉพาะจาก `REEVALUATION_REQUESTED` (data-schema §8.1) นอกนั้น `round = 1`
*/
async evaluate(user: JwtClaims, applicationId: string, body: HrEvaluateDto, correlationId?: string): Promise<HrApplicationDetail> {
await this.companyApplication(user, applicationId);
await this.companyApplication(user, applicationId, correlationId);
const reason = body.reason || undefined;
await this.execute(user, applicationId, {
trigger: 'evaluate',
Expand Down Expand Up @@ -265,11 +265,11 @@ export class HrApplicationsService {
}

/** ไม่มี ⇒ 404 • บริษัทอื่น ⇒ 403 `NOT_OWNER_OF_RESOURCE` (UAT-29 ข้อ 2) • HR Member นอกสายงาน ⇒ 403 `FORBIDDEN_ROLE` (`FORBIDDEN_CATEGORY`) */
private async companyApplication(user: JwtClaims, applicationId: string): Promise<Application> {
private async companyApplication(user: JwtClaims, applicationId: string, correlationId?: string): Promise<Application> {
const app = await this.db.application.findUnique({ where: { id: applicationId } });
if (!app) throw applicationNotFound();
assertCompanyOwnership(user, app.companyId);
await this.scope.assertInScope(user, app);
await this.scope.assertInScope(user, app, correlationId);
return app;
}

Expand Down
11 changes: 11 additions & 0 deletions apps/lifecycle/test/db/certificates.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,17 @@ describe('Lifecycle 1.7 — E-Certificate (HTTP + Postgres จริง)', funct

// ------------------------------------------------------------------
describe('เพิกถอน (UAT-23)', () => {
it('HR Member นอกสายงานของประกาศ ⇒ 403 FORBIDDEN_CATEGORY ใบยัง VALID; ในสายงานเพิกถอนได้ (PM ตัดสิน 2026-11-21)', async () => {
const { certificate } = await issued();
const outside = bearer({ role: 'COMPANY_HR', sub: hrUser, company_id: companyId, company_role: 'MEMBER', company_categories: ['BUSINESS_MARKETING'] });
const res = await revokeHr(certificate.id, undefined, outside).expect(403);
expect(res.body.error.code).to.equal('FORBIDDEN_ROLE');
expect(res.body.error.details[0].issue).to.equal('FORBIDDEN_CATEGORY');
expect((await prisma.certificate.findUniqueOrThrow({ where: { id: certificate.id } })).status).to.equal('VALID');
const inside = bearer({ role: 'COMPANY_HR', sub: hrUser, company_id: companyId, company_role: 'MEMBER', company_categories: ['TECH_IT'] });
await revokeHr(certificate.id, undefined, inside).expect(200);
});

it('HR เพิกถอนใบของบริษัทตน ⇒ REVOKED + status_history + E13; ไม่มี admin_audit_log', async () => {
const { application, certificate } = await issued();
const res = await revokeHr(certificate.id, { reason: ' ข้อมูลไม่ถูกต้อง ' }).expect(200);
Expand Down
42 changes: 42 additions & 0 deletions apps/lifecycle/test/db/hr-applications.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,48 @@ describe('Lifecycle 1.5 — ใบสมัครฝั่ง HR (HTTP + Postgre
await http().get(`/v1/hr/applications/${orphan.id}`).set('Authorization', memberOf(ALL_CATEGORIES)).expect(403);
expect(await ids(owner())).to.include.members([withJob.id, orphan.id]);
});

it('?category=: Member กรองในสายตน; ขอสายอื่น ⇒ รายการว่าง 200; Owner กรองได้ทุกสาย; ค่าผิด ⇒ 400 (PM ตัดสิน 2026-11-21)', async () => {
const tech = await seedIn('TECH_IT');
const biz = await seedIn('BUSINESS_MARKETING');
const corp = await seedIn('CORPORATE_SERVICES');
const member = memberOf(['TECH_IT', 'CORPORATE_SERVICES']);
expect(await ids(member, '?category=TECH_IT')).to.deep.equal([tech.id]);
expect(await ids(member, '?category=CORPORATE_SERVICES')).to.deep.equal([corp.id]);
const other = await http().get('/v1/hr/applications?category=BUSINESS_MARKETING').set('Authorization', member).expect(200);
expect(other.body.data).to.deep.equal([]);
expect(other.body.meta.total).to.equal(0);
expect(await ids(owner(), '?category=BUSINESS_MARKETING')).to.deep.equal([biz.id]);
expect(await ids(owner(), `?category=TECH_IT&job_id=${biz.jobId}`)).to.deep.equal([]);
expect(await ids(owner(), `?category=TECH_IT&job_id=${tech.jobId}`)).to.deep.equal([tech.id]);
const bad = await http().get('/v1/hr/applications?category=HR').set('Authorization', owner()).expect(400);
expect(bad.body.error.code).to.equal('VALIDATION_FAILED');
});

it('Job ล่มตอนถามสายงานของประกาศที่ยังไม่รู้สาย ⇒ รายการยัง 200 โดยตัดประกาศนั้นออก (ไม่พังทั้งหน้า) + ส่ง correlation id ต่อ', async () => {
const tech = await seedIn('TECH_IT');
const unknown = job.addJob({ company_id: companyId, category: 'TECH_IT' });
await prisma.jobSnapshot.create({ data: { jobId: unknown.job_id, companyId, title: 'x', status: 'PUBLISHED' } });
const pending = await prisma.application.create({ data: { jobId: unknown.job_id, companyId, studentUserId: randomUUID(), advisorUserId: advisorId, resumeId, status: 'PENDING' } });

job.unavailable = true;
const res = await http().get('/v1/hr/applications').set('Authorization', memberOf(['TECH_IT'])).set('x-correlation-id', 'cid-category-list').expect(200);
expect(res.body.data.map((r: { id: string }) => r.id)).to.deep.equal([tech.id]);
expect(job.getJobCorrelationIds).to.include('cid-category-list');
expect((await prisma.jobSnapshot.findUniqueOrThrow({ where: { jobId: unknown.job_id } })).category).to.equal(null);

job.unavailable = false;
expect(await ids(memberOf(['TECH_IT']))).to.deep.equal([tech.id, pending.id].sort());
});

it('รายละเอียดส่ง correlation id ต่อให้ Job ตอนเติมสายงาน', async () => {
const unknown = job.addJob({ company_id: companyId, category: 'TECH_IT' });
await prisma.jobSnapshot.create({ data: { jobId: unknown.job_id, companyId, title: 'x', status: 'PUBLISHED' } });
const app = await prisma.application.create({ data: { jobId: unknown.job_id, companyId, studentUserId: randomUUID(), advisorUserId: advisorId, resumeId, status: 'PENDING' } });
await http().get(`/v1/hr/applications/${app.id}`).set('Authorization', memberOf(['TECH_IT'])).set('x-correlation-id', 'cid-category-detail').expect(200);
expect(job.getJobCorrelationIds).to.include('cid-category-detail');
expect(job.getJobCorrelationIds).to.not.include(undefined);
});
});

describe('GET /hr/applications และ /hr/applications/{id}', () => {
Expand Down
Loading
Loading