From dd9b5e5813eb1dc525126f17c77092ffd46cf64d Mon Sep 17 00:00:00 2001 From: kevin li Date: Mon, 16 Nov 2026 22:55:17 -0500 Subject: [PATCH 1/2] [#651] Add Career job board tRPC router Adds the jobBoard router: job search, job and company views, people in process, and member-owned applications with dated history. Community views never expose private applications or notes. Ping preferences and digest opt-ins follow in a second PR after #650. Co-Authored-By: Claude Fable 5.2 --- .forge/features/career-job-router/spec.md | 70 +++++ .forge/features/career-job-router/srd.md | 106 +++++++ .forge/features/career-job-router/status.md | 55 ++++ .../features/career-job-router/test-cases.md | 70 +++++ docs/DATABASE-USAGE.md | 6 + packages/api/src/root.ts | 3 + packages/api/src/routers/job-board.ts | 257 +++++++++++++++ .../src/tests/integration/job-board.test.ts | 292 ++++++++++++++++++ .../tests/job-board/router-contract.test.ts | 25 ++ .../__snapshots__/api-surface.test.ts.snap | 8 + packages/api/src/utils/job-board/access.ts | 27 ++ .../api/src/utils/job-board/applications.ts | 262 ++++++++++++++++ packages/api/src/utils/job-board/community.ts | 97 ++++++ packages/api/src/utils/job-board/search.ts | 159 ++++++++++ packages/consts/src/job-board.ts | 3 + packages/validators/src/audit.ts | 3 + packages/validators/src/job-board.ts | 75 +++-- .../validators/src/tests/job-board.test.ts | 34 ++ 18 files changed, 1530 insertions(+), 22 deletions(-) create mode 100644 .forge/features/career-job-router/spec.md create mode 100644 .forge/features/career-job-router/srd.md create mode 100644 .forge/features/career-job-router/status.md create mode 100644 .forge/features/career-job-router/test-cases.md create mode 100644 packages/api/src/routers/job-board.ts create mode 100644 packages/api/src/tests/integration/job-board.test.ts create mode 100644 packages/api/src/tests/job-board/router-contract.test.ts create mode 100644 packages/api/src/utils/job-board/access.ts create mode 100644 packages/api/src/utils/job-board/applications.ts create mode 100644 packages/api/src/utils/job-board/community.ts create mode 100644 packages/api/src/utils/job-board/search.ts diff --git a/.forge/features/career-job-router/spec.md b/.forge/features/career-job-router/spec.md new file mode 100644 index 000000000..68b943023 --- /dev/null +++ b/.forge/features/career-job-router/spec.md @@ -0,0 +1,70 @@ +# Career Job Router Spec + +Status: Agreed with Kevin on 2026-11-16. Dev-lead review happens on the PR. + +## User-facing purpose + +Members get one place in Blade to explore scraped job listings, track their own +applications with dates, and find other members going through the same hiring +process. This slice (#651, part of #633) provides the data those pages need; the +pages themselves are #655 and #656. + +## Users / actors + +- Members: signed-in users with a member profile. +- Signed-in users without a member profile: no access. +- Officers: unchanged here. They already manage Career Discord channels and + roles through the existing platform configuration console (#648). + +## User-visible interface + +No pages in this slice. It supplies: + +- Explore: search, sort and filter listings by track, company, category, + location and posted date. Closed listings are hidden unless asked for. +- A job view: listing details, where it was found, members in process for it, + and the viewer's own progress. +- A company view: that company's listings, each with its members in process. +- People in process: members by company, role and stage. +- My applications: the member's own tracker with notes, visibility and a dated + timeline. + +## Scope + +### In scope + +- Save a listing, set stage, optional round and optional interview label, + update or remove it. +- An optional date for each stage change, so progress logged later is dated + correctly (applied 10/22, interview 11/01). Defaults to the time of saving and + cannot be in the future. +- Community visibility by default, with a private setting. + +### Out of scope + +- Ping preferences and digest opt-ins. They follow in a second PR once the + matching services in #650 merge. +- Editing or deleting individual timeline entries. +- Blade pages, cron, ingestion and Discord delivery. + +## Vocabulary + +- `community application`: one other signed-in members can see. +- `private application`: one only its owner can see. +- `progress`: a change to stage, round or interview label. + +## Acceptance criteria + +- A user without a member profile cannot read or change anything. +- Other members see a community application's name, picture, Discord username, + stage, round and interview label, and never its notes. +- A private application appears in no view except its owner's. +- Each progress change adds one dated timeline entry; editing notes or + visibility adds none. +- A member can change or remove only their own applications. + +## Open questions + +- Should a `saved` (bookmarked, not yet applied) application appear to other + members? #633 says stages are visible by default, so it currently does. +- Location filters widen each other (a city or U.S. remote). Confirm with #655. diff --git a/.forge/features/career-job-router/srd.md b/.forge/features/career-job-router/srd.md new file mode 100644 index 000000000..303052705 --- /dev/null +++ b/.forge/features/career-job-router/srd.md @@ -0,0 +1,106 @@ +# Career Job Router SRD + +Status: Implemented for PR 1 of #651. References: #633, #646, #647, #648, #650. + +## Technical purpose + +Add the `jobBoard` tRPC namespace over the Career job tables. A separate router +rather than more `career.*` procedures: `career` is Guild companies and +employment history, and the consts, validators and schema for this feature are +already named `job-board`. + +## Relevant principles + +`docs/API-AND-PERMISSIONS.md` and the `forge-api` skill: guard first, validators +from `@forge/validators`, typed return shapes, extracted logic in +`utils//`, transactions for multi-table writes. + +## Access policy + +- Unauthenticated: none. +- Signed-in without a member profile: `FORBIDDEN` from every procedure + (`requireJobBoardMember`). +- Member: all eight procedures. Writes are scoped to the caller's `Member.id`; + another member's application answers `NOT_FOUND`. +- Officer: no additional access. Officers do not see private applications. +- No `permProcedure`, so nothing is added to `utils/audit/coverage.ts`. + +## Architecture / data flow + +- `routers/job-board.ts`: procedures only. +- `utils/job-board/access.ts`: the member guard. +- `utils/job-board/search.ts`: filter and sort building, listing columns, + locations and sources. +- `utils/job-board/community.ts`: the single projection for other members' + applications. It applies `visibility = 'community'` and never selects + `privateNotes`. +- `utils/job-board/applications.ts`: save, update and remove. + +## tRPC/API behavior + +| Procedure | Kind | Notes | +| --------------------- | -------- | ---------------------------------------------------------------- | +| `searchJobs` | query | Paged. Inactive excluded unless `includeInactive`. | +| `getJob` | query | Listing, locations, sources, people in process, own application. | +| `getCompany` | query | By company key; up to 200 listings, open first, with applicants. | +| `listPeopleInProcess` | query | Paged community applications with member identity. | +| `listMyApplications` | query | Own applications with notes, visibility and timeline. | +| `saveApplication` | mutation | `CONFLICT` if already tracking; `NOT_FOUND` for an unknown job. | +| `updateApplication` | mutation | Partial. Rechecks round and label against the stored stage. | +| `removeApplication` | mutation | Deletes the row; history cascades. | + +Listings never expose delivery state, identity keys or raw source data. + +Application writes: + +- Save and update write `JobApplication` and a `JobApplicationHistory` snapshot + in one transaction. History is written on the initial save and when stage, + round or interview label changes, not for notes or visibility. +- `occurredAt` is stored as `JobApplicationHistory.changedAt`. Sending it + without a progress change is `BAD_REQUEST`. +- Leaving `interviewing` clears round and label, as the table checks require. +- Removal writes the audit event `job_board.application.removed` inside the + transaction before the delete. The event carries the member and no job + details, because officers read the audit log and the application may be + private. + +## Validation + +`applicationSaveInputSchema` and `applicationUpdateInputSchema` gain +`interviewLabel` (trimmed, at most `MAX_APPLICATION_INTERVIEW_LABEL_LENGTH`, +only while interviewing) and `occurredAt` (not in the future). Other inputs +reuse the #646 schemas unchanged. + +## Data / migration / compatibility + +No schema or migration change. `changedAt` already accepts an explicit value. +One audit action key is added to the catalog. No existing procedure is renamed +or removed. + +## Discord integration + +None. Member identity includes `Member.discordUser` (a username) for display +only; it is never used for mentions. + +## Configurability review + +Would this require a developer change next year? + +- Answer: No. Stages, tracks, categories and limits come from `JOB_BOARD`. +- If yes, why is hard-coding acceptable or what admin-configurable path is planned? N/A. + +## React / frontend constraints + +None in this slice. + +## Testing / verification strategy + +- `packages/validators/src/tests/job-board.test.ts`: label and date rules. +- `packages/api/src/tests/integration/job-board.test.ts`: access, privacy, + history and ownership against disposable PostgreSQL. +- `packages/api/src/tests/job-board/router-contract.test.ts` and the API surface + snapshot pin the procedure names. + +## Open questions + +- See spec.md. Search returns rows only once #649's ingestion lands. diff --git a/.forge/features/career-job-router/status.md b/.forge/features/career-job-router/status.md new file mode 100644 index 000000000..a753ea675 --- /dev/null +++ b/.forge/features/career-job-router/status.md @@ -0,0 +1,55 @@ +# Career Job Router Status + +Current phase: PR 1 implemented, validated locally and opened as a draft PR. + +## Decision log + +- 2026-11-16: Kevin split #651. PR 1 is job search, job and company views, + applications with history, people in process and privacy. Ping preferences + and digest opt-ins wait for #650. +- 2026-11-16: New `jobBoard` router instead of extending `career`. +- 2026-11-16: Stage changes take an optional date, not in the future, defaulting + to the time of saving. Timeline entries are not editable. +- 2026-11-16: Community views show name, profile picture, Discord username, + stage, round and interview label. +- Implementation choices to confirm in review: no new officer procedure because + `discordConfig.list` and `discordConfig.update` already cover the Career keys; + a missing member profile is `FORBIDDEN`; location filters widen each other; + the removal audit event carries no job details. + +## Open questions + +- Should `saved` applications be visible to other members? +- Confirm location filter behavior with the #655 owner. + +## Task list + +- [x] Reverse-prompt scope and decisions with Kevin. +- [x] Extend application validators with interview label and stage date. +- [x] Add the `jobBoard` router, access guard, search, community projection and + application mutations. +- [x] Add validator, integration and contract tests; update the API surface snapshot. +- [x] Commit and open the draft PR for Kevin's review. +- [ ] PR 2: ping preferences and digest opt-ins after #650. + +## Validation / commands + +- `pnpm --filter @forge/validators exec vitest run src/tests/audit.test.ts src/tests/job-board.test.ts`: + 39 passed. +- `pnpm with-env vitest run src/tests/integration/job-board.test.ts src/tests/job-board src/tests/root/api-surface.test.ts src/tests/audit/coverage.test.ts` + in `packages/api` with `NODE_ENV=test`: 19 passed, including 5 integration + tests on disposable local PostgreSQL. Snapshot gained the eight `jobBoard.*` paths. +- `src/tests/root/version-pins.test.ts` fails on this checkout because + `pnpm-lock.yaml` has no `overrides:` block; the lockfile is unchanged by this work. +- Root `pnpm lint`: passed, 31 tasks, warnings only. Root `pnpm typecheck`: + passed, 33 tasks. +- Root `pnpm format`: fails in 24 packages on this Windows checkout's CRLF line + endings in untouched files (same limitation as #647). A Prettier check of + every file changed here passes. + +## Links + +- PRs: +- Issues: https://github.com/KnightHacks/forge/issues/651, + https://github.com/KnightHacks/forge/issues/633 +- Discord/thread context: diff --git a/.forge/features/career-job-router/test-cases.md b/.forge/features/career-job-router/test-cases.md new file mode 100644 index 000000000..a3e075748 --- /dev/null +++ b/.forge/features/career-job-router/test-cases.md @@ -0,0 +1,70 @@ +# Career Job Router Test Cases + +Status: Implemented. Kept to the key rules, per the small-slice testing guidance. + +## Scope + +Member access, privacy of applications and notes, dated history, ownership, and +the default search filter. Preferences, digests, UI and ingestion are excluded. + +## Test placement plan + +- `pnpm --filter @forge/validators exec vitest run src/tests/job-board.test.ts` +- `pnpm --filter @forge/api with-env vitest run src/tests/integration/job-board.test.ts src/tests/job-board src/tests/root/api-surface.test.ts` + (the integration file needs a local PostgreSQL and skips without one) + +## Test cases + +### TC-001: Search hides closed listings by default + +Setup: one active and one inactive job for the same company. + +Action: search by company, then with `includeInactive`. + +Expected observations: one job, then two; unknown company or other track returns none. + +### TC-002: Progress is dated, notes edits are not + +Setup: a member saves a job as applied on a past date. + +Action: move to interviewing round 1 with a label and a later past date, then edit notes only. + +Expected observations: two history entries carrying the supplied dates; the notes edit adds none; moving to offer adds a third and clears round and label. + +### TC-003: Community views show identity and no notes + +Setup: one community application with notes, one private application. + +Action: read the job view, company view and people-in-process list as the private owner. + +Expected observations: only the community application, with name, Discord username and stage; no notes anywhere. The owner's own list and job view show their private application and notes. + +### TC-004: Stage date and interview label input rules + +Action: parse a label while interviewing and while applied; parse a past and a future date. + +Expected observations: label kept only while interviewing; future date rejected. + +## Negative / regression cases + +### TC-NEG-001: No member profile + +Action: a signed-in user without a member profile searches or saves. + +Expected observations: `FORBIDDEN`. + +### TC-NEG-002: Duplicate and misplaced input + +Action: save the same job twice; set a round on an application that is not interviewing. + +Expected observations: `CONFLICT`; `BAD_REQUEST`. + +### TC-NEG-003: Another member's application + +Action: update and remove someone else's application, then the owner removes it. + +Expected observations: `NOT_FOUND` for the other member; the owner's removal deletes the row and its history and writes one audit event with no job details. + +## Open questions + +- None beyond spec.md. diff --git a/docs/DATABASE-USAGE.md b/docs/DATABASE-USAGE.md index 82f086f17..252850dad 100644 --- a/docs/DATABASE-USAGE.md +++ b/docs/DATABASE-USAGE.md @@ -218,6 +218,12 @@ Do not return raw application rows: private notes are always private, including when application visibility is community. No end-user row authorization is implied by these foreign keys. +`JobApplicationHistory` rows are written by the `jobBoard` application mutations +in the same transaction as the `JobApplication` change, one per change to stage, +round or interview label. `changedAt` is when the member says the change +happened, which may be earlier than when the row was saved; order timelines by +it and do not treat it as a write timestamp. + ### Identifier fingerprints `Job.identityHash`, `JobSource.boardKeyHash` and `JobObservation.externalIdHash` are diff --git a/packages/api/src/root.ts b/packages/api/src/root.ts index aa9f84171..5cfd3fb68 100644 --- a/packages/api/src/root.ts +++ b/packages/api/src/root.ts @@ -16,6 +16,7 @@ import { hackathonEventRouter } from "./routers/hackathon-event"; import { hackerRouter } from "./routers/hacker"; import { hackerTeamRouter } from "./routers/hacker-team"; import { issuesRouter } from "./routers/issues"; +import { jobBoardRouter } from "./routers/job-board"; import { judgingRouter } from "./routers/judging"; import { mcpActivityRouter } from "./routers/mcp-activity"; import { memberRouter } from "./routers/member"; @@ -53,6 +54,7 @@ export interface AppRouterShape { hacker: typeof hackerRouter; health: typeof healthProcedure; issues: typeof issuesRouter; + jobBoard: typeof jobBoardRouter; judging: typeof judgingRouter; mcpActivity: typeof mcpActivityRouter; member: typeof memberRouter; @@ -90,6 +92,7 @@ const appRouterRecord: AppRouterRecord = { hacker: hackerRouter, health: healthProcedure, issues: issuesRouter, + jobBoard: jobBoardRouter, judging: judgingRouter, mcpActivity: mcpActivityRouter, member: memberRouter, diff --git a/packages/api/src/routers/job-board.ts b/packages/api/src/routers/job-board.ts new file mode 100644 index 000000000..248e00edf --- /dev/null +++ b/packages/api/src/routers/job-board.ts @@ -0,0 +1,257 @@ +import type { TRPCRouterRecord } from "@trpc/server"; +import { TRPCError } from "@trpc/server"; + +import { and, count, desc, eq, ilike, inArray } from "@forge/db"; +import { db } from "@forge/db/client"; +import { Job, JobApplication } from "@forge/db/schemas/job-board"; +import { + applicationIdInputSchema, + applicationSaveInputSchema, + applicationUpdateInputSchema, + companyViewInputSchema, + jobIdInputSchema, + jobSearchInputSchema, + peopleInProcessInputSchema, +} from "@forge/validators"; + +import type { CommunityApplication } from "../utils/job-board/community"; +import { protectedProcedure } from "../trpc"; +import { requireJobBoardMember } from "../utils/job-board/access"; +import { + listApplicationHistory, + removeApplication, + saveApplication, + updateApplication, +} from "../utils/job-board/applications"; +import { + countCommunityApplications, + listCommunityApplications, +} from "../utils/job-board/community"; +import { + containsPattern, + jobSearchConditions, + jobSearchOrder, + jobSummaryColumns, + listJobLocations, + listJobSources, +} from "../utils/job-board/search"; + +/** A company page is one screen, not a paged list; the largest boards exceed this. */ +const COMPANY_VIEW_MAX_LISTINGS = 200; + +async function withLocations(jobs: Row[]) { + const locations = await listJobLocations(jobs.map((job) => job.id)); + return jobs.map((job) => ({ + ...job, + locations: locations.get(job.id) ?? [], + })); +} + +export const jobBoardRouter = { + /** Explore: filtered, sorted, paged listings. Inactive ones are opt-in. */ + searchJobs: protectedProcedure + .input(jobSearchInputSchema) + .query(async ({ ctx, input }) => { + await requireJobBoardMember(ctx.session.user.id); + const where = jobSearchConditions(input); + + const [jobs, [totals]] = await Promise.all([ + db + .select(jobSummaryColumns) + .from(Job) + .where(where) + .orderBy(...jobSearchOrder(input.sort)) + .limit(input.limit) + .offset((input.page - 1) * input.limit), + db.select({ total: count() }).from(Job).where(where), + ]); + + return { + jobs: await withLocations(jobs), + limit: input.limit, + page: input.page, + total: totals?.total ?? 0, + }; + }), + + /** One listing, the members in process for it, and the caller's own progress. */ + getJob: protectedProcedure + .input(jobIdInputSchema) + .query(async ({ ctx, input }) => { + const member = await requireJobBoardMember(ctx.session.user.id); + const [job] = await db + .select({ ...jobSummaryColumns, description: Job.description }) + .from(Job) + .where(eq(Job.id, input.jobId)) + .limit(1); + if (!job) { + throw new TRPCError({ + code: "NOT_FOUND", + message: "That job does not exist.", + }); + } + + const [[listing], sources, peopleInProcess, [mine]] = await Promise.all([ + withLocations([job]), + listJobSources(job.id), + listCommunityApplications(eq(JobApplication.jobId, job.id)), + db + .select({ + id: JobApplication.id, + interviewLabel: JobApplication.interviewLabel, + privateNotes: JobApplication.privateNotes, + round: JobApplication.round, + stage: JobApplication.stage, + visibility: JobApplication.visibility, + }) + .from(JobApplication) + .where( + and( + eq(JobApplication.jobId, job.id), + eq(JobApplication.memberId, member.id), + ), + ) + .limit(1), + ]); + + return { + job: { ...job, locations: listing?.locations ?? [], sources }, + myApplication: mine ?? null, + peopleInProcess, + }; + }), + + /** A company's listings, each with the members in process for that role. */ + getCompany: protectedProcedure + .input(companyViewInputSchema) + .query(async ({ ctx, input }) => { + await requireJobBoardMember(ctx.session.user.id); + const jobs = await db + .select(jobSummaryColumns) + .from(Job) + .where( + and( + eq(Job.companyKey, input.company), + input.track ? eq(Job.track, input.track) : undefined, + ), + ) + // Open roles first; closed ones stay for the members still tracking them. + .orderBy(desc(Job.active), ...jobSearchOrder("newest")) + .limit(COMPANY_VIEW_MAX_LISTINGS); + const [newest] = jobs; + if (!newest) { + throw new TRPCError({ + code: "NOT_FOUND", + message: "No jobs are listed for that company.", + }); + } + + const jobIds = jobs.map((job) => job.id); + const [listings, applicants] = await Promise.all([ + withLocations(jobs), + listCommunityApplications(inArray(JobApplication.jobId, jobIds)), + ]); + const applicantsByJob = new Map(); + for (const applicant of applicants) { + const group = applicantsByJob.get(applicant.jobId) ?? []; + group.push(applicant); + applicantsByJob.set(applicant.jobId, group); + } + + return { + companyKey: input.company, + companyLabel: newest.companyLabel, + listings: listings.map((listing) => ({ + ...listing, + peopleInProcess: applicantsByJob.get(listing.id) ?? [], + })), + }; + }), + + /** Browse members by company, role and stage to find others in a process. */ + listPeopleInProcess: protectedProcedure + .input(peopleInProcessInputSchema) + .query(async ({ ctx, input }) => { + await requireJobBoardMember(ctx.session.user.id); + const filter = and( + input.company ? eq(Job.companyKey, input.company) : undefined, + input.role ? ilike(Job.title, containsPattern(input.role)) : undefined, + input.stage ? eq(JobApplication.stage, input.stage) : undefined, + input.track ? eq(Job.track, input.track) : undefined, + ); + + const [people, total] = await Promise.all([ + listCommunityApplications(filter, { + limit: input.limit, + offset: (input.page - 1) * input.limit, + }), + countCommunityApplications(filter), + ]); + + return { limit: input.limit, page: input.page, people, total }; + }), + + /** The caller's own tracker, including private applications and notes. */ + listMyApplications: protectedProcedure.query(async ({ ctx }) => { + const member = await requireJobBoardMember(ctx.session.user.id); + const applications = await db + .select({ + createdAt: JobApplication.createdAt, + id: JobApplication.id, + interviewLabel: JobApplication.interviewLabel, + job: jobSummaryColumns, + privateNotes: JobApplication.privateNotes, + round: JobApplication.round, + stage: JobApplication.stage, + updatedAt: JobApplication.updatedAt, + visibility: JobApplication.visibility, + }) + .from(JobApplication) + .innerJoin(Job, eq(Job.id, JobApplication.jobId)) + .where(eq(JobApplication.memberId, member.id)) + .orderBy(desc(JobApplication.updatedAt), desc(JobApplication.id)); + + return await Promise.all( + applications.map(async (application) => ({ + ...application, + history: await listApplicationHistory(db, application.id), + })), + ); + }), + + saveApplication: protectedProcedure + .input(applicationSaveInputSchema) + .mutation(async ({ ctx, input }) => { + const member = await requireJobBoardMember(ctx.session.user.id); + return await db.transaction( + async (tx) => + await saveApplication({ database: tx, input, memberId: member.id }), + ); + }), + + updateApplication: protectedProcedure + .input(applicationUpdateInputSchema) + .mutation(async ({ ctx, input }) => { + const member = await requireJobBoardMember(ctx.session.user.id); + return await db.transaction( + async (tx) => + await updateApplication({ database: tx, input, memberId: member.id }), + ); + }), + + removeApplication: protectedProcedure + .input(applicationIdInputSchema) + .mutation(async ({ ctx, input }) => { + const member = await requireJobBoardMember(ctx.session.user.id); + await db.transaction( + async (tx) => + await removeApplication({ + actor: ctx.session.user, + applicationId: input.applicationId, + database: tx, + memberId: member.id, + }), + ); + return { applicationId: input.applicationId }; + }), +} satisfies TRPCRouterRecord; diff --git a/packages/api/src/tests/integration/job-board.test.ts b/packages/api/src/tests/integration/job-board.test.ts new file mode 100644 index 000000000..a8a846076 --- /dev/null +++ b/packages/api/src/tests/integration/job-board.test.ts @@ -0,0 +1,292 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import type { Session } from "@forge/auth/server"; +import type { DisposableDatabase } from "@forge/db/testing"; +import { eq } from "@forge/db"; +import { + canRunDatabaseTests, + provisionDisposableDatabase, +} from "@forge/db/testing"; + +type DatabaseClient = typeof import("@forge/db/client").db; +type JobBoardSchemas = typeof import("@forge/db/schemas/job-board"); + +const ALEX = { + memberId: "20000000-0000-4000-8000-0000000000a1", + userId: "10000000-0000-4000-8000-0000000000a1", +}; +const BLAKE = { + memberId: "20000000-0000-4000-8000-0000000000b1", + userId: "10000000-0000-4000-8000-0000000000b1", +}; +const NO_PROFILE_USER = "10000000-0000-4000-8000-0000000000c1"; + +/** + * The rules here are privacy and ownership filters written in SQL, plus a + * two-table write that must be one transaction. A mocked `db` verifies none of + * it. Skips without a loopback `DATABASE_URL`, like the other integration files. + */ +describe.runIf(canRunDatabaseTests())("job board router", () => { + let disposable: DisposableDatabase | undefined; + let client: DatabaseClient; + let jobBoard: JobBoardSchemas; + let alex: Awaited>; + let blake: Awaited>; + let openJobId: string; + + async function callerFor(userId: string) { + const trpc = await import("../../trpc"); + const { jobBoardRouter } = await import("../../routers/job-board"); + const router = trpc.createTRPCRouter({ jobBoard: jobBoardRouter }); + + return trpc.createCallerFactory(router)({ + headers: new Headers(), + session: { user: { id: userId, name: "Member" } } as Session, + source: "job-board-integration", + }).jobBoard; + } + + function memberRow(actor: typeof ALEX, name: string) { + return { + age: 21, + discordUser: name.toLowerCase(), + dob: "2003-01-01", + email: `${name}@knighthacks.org`, + firstName: name, + gradDate: "2027-05-01", + id: actor.memberId, + lastName: "Member", + levelOfStudy: "Undergraduate University (3+ year)" as const, + school: "University of Central Florida" as const, + shirtSize: "M" as const, + userId: actor.userId, + }; + } + + async function insertJob(title: string, active: boolean) { + const [job] = await client + .insert(jobBoard.Job) + .values({ + active, + applyUrl: "https://example.test/apply", + companyKey: "acme", + companyLabel: "Acme", + identityKey: `test:${title}`, + inactiveAt: active ? null : new Date(), + title, + track: "internship", + }) + .returning({ id: jobBoard.Job.id }); + if (!job) throw new Error("Job fixture was not inserted"); + return job.id; + } + + // Search params are typed as raw URL values, so every key is required and + // `unknown`. Tests name only the filters they exercise. + const NO_FILTERS = { + category: undefined, + cityKey: undefined, + company: undefined, + includeInactive: undefined, + limit: undefined, + page: undefined, + postedWithin: undefined, + query: undefined, + remoteUs: undefined, + sort: undefined, + state: undefined, + track: undefined, + }; + + function search( + caller: typeof alex, + filters: Partial> = {}, + ) { + return caller.searchJobs({ ...NO_FILTERS, ...filters }); + } + + beforeAll(async () => { + disposable = await provisionDisposableDatabase("forge_api"); + // eslint-disable-next-line no-restricted-properties + process.env.DATABASE_URL = disposable.url; + + ({ db: client } = await import("@forge/db/client")); + jobBoard = await import("@forge/db/schemas/job-board"); + const auth = await import("@forge/db/schemas/auth"); + const knightHacks = await import("@forge/db/schemas/knight-hacks"); + + await client.insert(auth.User).values([ + { discordUserId: "discord-alex", id: ALEX.userId, name: "Alex" }, + { discordUserId: "discord-blake", id: BLAKE.userId, name: "Blake" }, + { discordUserId: "discord-none", id: NO_PROFILE_USER, name: "None" }, + ]); + await client + .insert(knightHacks.Member) + .values([memberRow(ALEX, "Alex"), memberRow(BLAKE, "Blake")]); + + openJobId = await insertJob("SWE Intern", true); + await insertJob("Data Intern", false); + alex = await callerFor(ALEX.userId); + blake = await callerFor(BLAKE.userId); + }, 120_000); + + afterAll(async () => { + await client.$client.end().catch(() => undefined); + await disposable?.drop(); + }, 30_000); + + it("rejects a signed-in user who has no member profile", async () => { + const outsider = await callerFor(NO_PROFILE_USER); + await expect(search(outsider)).rejects.toMatchObject({ + code: "FORBIDDEN", + }); + await expect( + outsider.saveApplication({ jobId: openJobId }), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + it("hides inactive jobs from search unless asked, and filters by company", async () => { + const byDefault = await search(alex, { company: "acme" }); + expect(byDefault.jobs.map((job) => job.id)).toEqual([openJobId]); + expect(byDefault.total).toBe(1); + + const withInactive = await search(alex, { includeInactive: true }); + expect(withInactive.total).toBe(2); + expect((await search(alex, { company: "globex" })).total).toBe(0); + expect((await search(alex, { track: "new_grad" })).total).toBe(0); + + await client.insert(jobBoard.JobLocation).values({ + jobId: openJobId, + kind: "remote_us", + sourceText: "Remote - United States", + }); + const remote = await search(alex, { query: "swe", remoteUs: true }); + expect(remote.jobs).toMatchObject([ + { id: openJobId, locations: [{ kind: "remote_us" }] }, + ]); + expect((await search(alex, { state: "WA" })).total).toBe(0); + }); + + it("writes a dated history entry for each progress change and none for a notes edit", async () => { + const saved = await alex.saveApplication({ + jobId: openJobId, + occurredAt: new Date("2026-10-22T12:00:00Z"), + privateNotes: "Referred by Sam", + stage: "applied", + }); + await expect( + alex.saveApplication({ jobId: openJobId }), + ).rejects.toMatchObject({ code: "CONFLICT" }); + + await alex.updateApplication({ + applicationId: saved.id, + interviewLabel: "Behavioral", + occurredAt: new Date("2026-11-01T12:00:00Z"), + round: 1, + stage: "interviewing", + }); + const noted = await alex.updateApplication({ + applicationId: saved.id, + privateNotes: "Onsite next", + }); + + expect( + noted.history.map(({ changedAt, interviewLabel, round, stage }) => ({ + changedAt: changedAt.toISOString(), + interviewLabel, + round, + stage, + })), + ).toEqual([ + { + changedAt: "2026-10-22T12:00:00.000Z", + interviewLabel: null, + round: null, + stage: "applied", + }, + { + changedAt: "2026-11-01T12:00:00.000Z", + interviewLabel: "Behavioral", + round: 1, + stage: "interviewing", + }, + ]); + + // Moving on from interviewing clears the round and label with it. + const offered = await alex.updateApplication({ + applicationId: saved.id, + stage: "offer", + }); + expect(offered).toMatchObject({ interviewLabel: null, round: null }); + expect(offered.history).toHaveLength(3); + await expect( + alex.updateApplication({ applicationId: saved.id, round: 2 }), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + }); + + it("shows community applications without notes and keeps private ones out of every view", async () => { + const hidden = await blake.saveApplication({ + jobId: openJobId, + privateNotes: "Do not share", + stage: "applied", + visibility: "private", + }); + + const views = [ + (await blake.getJob({ jobId: openJobId })).peopleInProcess, + (await blake.getCompany({ company: "acme" })).listings.flatMap( + (listing) => listing.peopleInProcess, + ), + (await blake.listPeopleInProcess({})).people, + ]; + for (const people of views) { + expect(people.map((person) => person.memberId)).toEqual([ALEX.memberId]); + expect(people[0]).toMatchObject({ + discordUser: "alex", + firstName: "Alex", + stage: "offer", + }); + expect(JSON.stringify(people)).not.toMatch(/Onsite next|privateNotes/); + } + + const mine = await blake.listMyApplications(); + expect(mine).toMatchObject([ + { id: hidden.id, privateNotes: "Do not share", visibility: "private" }, + ]); + expect( + (await blake.getJob({ jobId: openJobId })).myApplication, + ).toMatchObject({ id: hidden.id, privateNotes: "Do not share" }); + }); + + it("lets only the owner update or remove an application, and audits the removal without naming the job", async () => { + const [mine] = await alex.listMyApplications(); + if (!mine) throw new Error("Alex's application is missing"); + + await expect( + blake.updateApplication({ applicationId: mine.id, stage: "rejected" }), + ).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect( + blake.removeApplication({ applicationId: mine.id }), + ).rejects.toMatchObject({ code: "NOT_FOUND" }); + + await alex.removeApplication({ applicationId: mine.id }); + expect(await alex.listMyApplications()).toEqual([]); + const history = await client + .select({ id: jobBoard.JobApplicationHistory.id }) + .from(jobBoard.JobApplicationHistory) + .where(eq(jobBoard.JobApplicationHistory.applicationId, mine.id)); + expect(history).toEqual([]); + + const audit = await import("@forge/db/schemas/audit"); + const events = await client + .select({ + actorUserId: audit.AdminAuditEvent.actorUserId, + metadata: audit.AdminAuditEvent.metadata, + }) + .from(audit.AdminAuditEvent) + .where( + eq(audit.AdminAuditEvent.actionKey, "job_board.application.removed"), + ); + expect(events).toEqual([{ actorUserId: ALEX.userId, metadata: {} }]); + }); +}); diff --git a/packages/api/src/tests/job-board/router-contract.test.ts b/packages/api/src/tests/job-board/router-contract.test.ts new file mode 100644 index 000000000..bc9152e3d --- /dev/null +++ b/packages/api/src/tests/job-board/router-contract.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it, vi } from "vitest"; + +import { jobBoardRouter } from "../../routers/job-board"; + +vi.mock("@forge/db/client", () => ({ db: {} })); +vi.mock("../../utils/profile-picture/storage", () => ({ + profilePictureStorageClient: {}, +})); + +describe("job board router contract", () => { + it("exposes job, community and own-application procedures", () => { + expect(Object.keys(jobBoardRouter).sort()).toEqual( + [ + "getCompany", + "getJob", + "listMyApplications", + "listPeopleInProcess", + "removeApplication", + "saveApplication", + "searchJobs", + "updateApplication", + ].sort(), + ); + }); +}); diff --git a/packages/api/src/tests/root/__snapshots__/api-surface.test.ts.snap b/packages/api/src/tests/root/__snapshots__/api-surface.test.ts.snap index c1908e256..33ae1d2dd 100644 --- a/packages/api/src/tests/root/__snapshots__/api-surface.test.ts.snap +++ b/packages/api/src/tests/root/__snapshots__/api-surface.test.ts.snap @@ -228,6 +228,14 @@ exports[`client-facing API surface > exposes exactly the documented procedure pa "issues.restore", "issues.update", "issues.updateTemplate", + "jobBoard.getCompany", + "jobBoard.getJob", + "jobBoard.listMyApplications", + "jobBoard.listPeopleInProcess", + "jobBoard.removeApplication", + "jobBoard.saveApplication", + "jobBoard.searchJobs", + "jobBoard.updateApplication", "judging.addDeliberationProject", "judging.archiveRoom", "judging.assignPresentation", diff --git a/packages/api/src/utils/job-board/access.ts b/packages/api/src/utils/job-board/access.ts new file mode 100644 index 000000000..f0ead3d9e --- /dev/null +++ b/packages/api/src/utils/job-board/access.ts @@ -0,0 +1,27 @@ +import { TRPCError } from "@trpc/server"; + +import { eq } from "@forge/db"; +import { db } from "@forge/db/client"; +import { Member } from "@forge/db/schemas/knight-hacks"; + +/** + * The job board is for members: a signed-in account without a member profile + * may not read listings or other members' progress. Every job board procedure + * calls this before doing any work. + */ +export async function requireJobBoardMember(userId: string) { + const [member] = await db + .select({ id: Member.id }) + .from(Member) + .where(eq(Member.userId, userId)) + .limit(1); + + if (!member) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Create a member profile to use the job board.", + }); + } + + return member; +} diff --git a/packages/api/src/utils/job-board/applications.ts b/packages/api/src/utils/job-board/applications.ts new file mode 100644 index 000000000..16e80b4a9 --- /dev/null +++ b/packages/api/src/utils/job-board/applications.ts @@ -0,0 +1,262 @@ +import { TRPCError } from "@trpc/server"; + +import type { + ApplicationSaveInput, + ApplicationUpdateInput, +} from "@forge/validators"; +import { and, asc, eq } from "@forge/db"; +import { + Job, + JobApplication, + JobApplicationHistory, +} from "@forge/db/schemas/job-board"; +import { stageAllowsRound } from "@forge/validators"; + +import type { AuditActor } from "../audit/service"; +import type { TransactionDb, WriteDb } from "../db"; +import { + loadMemberAuditIdentity, + memberAuditSubject, +} from "../audit/member-subject"; +import { createAdminAuditEvent } from "../audit/service"; + +/** The owner's view of an application: the only shape that carries notes. */ +const ownApplicationColumns = { + createdAt: JobApplication.createdAt, + id: JobApplication.id, + interviewLabel: JobApplication.interviewLabel, + jobId: JobApplication.jobId, + privateNotes: JobApplication.privateNotes, + round: JobApplication.round, + stage: JobApplication.stage, + updatedAt: JobApplication.updatedAt, + visibility: JobApplication.visibility, +} as const; + +function notFound() { + // Also the answer for another member's application, so its existence and + // visibility are not revealed. + return new TRPCError({ + code: "NOT_FOUND", + message: "That application does not exist.", + }); +} + +export async function listApplicationHistory( + database: WriteDb, + applicationId: string, +) { + return await database + .select({ + changedAt: JobApplicationHistory.changedAt, + id: JobApplicationHistory.id, + interviewLabel: JobApplicationHistory.interviewLabel, + round: JobApplicationHistory.round, + stage: JobApplicationHistory.stage, + }) + .from(JobApplicationHistory) + .where(eq(JobApplicationHistory.applicationId, applicationId)) + .orderBy( + asc(JobApplicationHistory.changedAt), + asc(JobApplicationHistory.id), + ); +} + +async function withHistory( + database: WriteDb, + application: Row, +) { + return { + ...application, + history: await listApplicationHistory(database, application.id), + }; +} + +/** Starts tracking a job. The first history entry is written with the row. */ +export async function saveApplication({ + database, + input, + memberId, +}: { + database: TransactionDb; + input: ApplicationSaveInput; + memberId: string; +}) { + const [job] = await database + .select({ id: Job.id }) + .from(Job) + .where(eq(Job.id, input.jobId)) + .limit(1); + if (!job) { + throw new TRPCError({ + code: "NOT_FOUND", + message: "That job does not exist.", + }); + } + + // `DO NOTHING` rather than catching the unique violation: a failed statement + // would abort the transaction this runs in. + const [application] = await database + .insert(JobApplication) + .values({ + interviewLabel: input.interviewLabel, + jobId: input.jobId, + memberId, + privateNotes: input.privateNotes, + round: input.round, + stage: input.stage, + visibility: input.visibility, + }) + .onConflictDoNothing({ + target: [JobApplication.memberId, JobApplication.jobId], + }) + .returning(ownApplicationColumns); + if (!application) { + throw new TRPCError({ + code: "CONFLICT", + message: "You are already tracking this job.", + }); + } + + await database.insert(JobApplicationHistory).values({ + applicationId: application.id, + changedAt: input.occurredAt, + interviewLabel: application.interviewLabel, + round: application.round, + stage: application.stage, + }); + + return await withHistory(database, application); +} + +/** + * Updates the caller's application. A change to stage, round or interview + * label is progress and gets a dated history entry in the same transaction; + * a notes-only or visibility-only edit does not. + */ +export async function updateApplication({ + database, + input, + memberId, +}: { + database: TransactionDb; + input: ApplicationUpdateInput; + memberId: string; +}) { + const [current] = await database + .select(ownApplicationColumns) + .from(JobApplication) + .where( + and( + eq(JobApplication.id, input.applicationId), + eq(JobApplication.memberId, memberId), + ), + ) + .limit(1) + .for("update"); + if (!current) throw notFound(); + + const stage = input.stage ?? current.stage; + const interviewing = stageAllowsRound(stage); + // The validator can only check these against a stage it was sent. This is + // the same rule against the stored one. + if (!interviewing && (input.round != null || input.interviewLabel != null)) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Rounds and interview labels apply only while interviewing.", + }); + } + + // Leaving `interviewing` clears both, which the table's checks require. + const round = interviewing + ? input.round !== undefined + ? input.round + : current.round + : null; + const interviewLabel = interviewing + ? input.interviewLabel !== undefined + ? input.interviewLabel + : current.interviewLabel + : null; + const progressed = + stage !== current.stage || + round !== current.round || + interviewLabel !== current.interviewLabel; + + if (input.occurredAt && !progressed) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: + "A date applies only when the stage, round, or interview label changes.", + }); + } + + const [application] = await database + .update(JobApplication) + // `updatedAt` refreshes itself through `$onUpdate`. + .set({ + interviewLabel, + privateNotes: input.privateNotes, + round, + stage, + visibility: input.visibility, + }) + .where(eq(JobApplication.id, current.id)) + .returning(ownApplicationColumns); + if (!application) throw notFound(); + + if (progressed) { + await database.insert(JobApplicationHistory).values({ + applicationId: application.id, + changedAt: input.occurredAt, + interviewLabel, + round, + stage, + }); + } + + return await withHistory(database, application); +} + +/** Stops tracking a job. Its history is removed with it. */ +export async function removeApplication({ + actor, + applicationId, + database, + memberId, +}: { + actor: AuditActor; + applicationId: string; + database: TransactionDb; + memberId: string; +}) { + const [application] = await database + .select({ id: JobApplication.id }) + .from(JobApplication) + .where( + and( + eq(JobApplication.id, applicationId), + eq(JobApplication.memberId, memberId), + ), + ) + .limit(1) + .for("update"); + if (!application) throw notFound(); + + // The audit log is read by officers, and a private application is private + // from them too: the event names the member and nothing about the job. + await createAdminAuditEvent( + { + actionKey: "job_board.application.removed", + actor, + subjects: [ + memberAuditSubject(await loadMemberAuditIdentity(actor.id, database)), + ], + }, + database, + ); + + await database + .delete(JobApplication) + .where(eq(JobApplication.id, application.id)); +} diff --git a/packages/api/src/utils/job-board/community.ts b/packages/api/src/utils/job-board/community.ts new file mode 100644 index 000000000..f8dfe86d5 --- /dev/null +++ b/packages/api/src/utils/job-board/community.ts @@ -0,0 +1,97 @@ +import type { SQL } from "@forge/db"; +import { and, asc, count, desc, eq } from "@forge/db"; +import { db } from "@forge/db/client"; +import { Job, JobApplication } from "@forge/db/schemas/job-board"; +import { Member } from "@forge/db/schemas/knight-hacks"; + +import { + PROFILE_PICTURE_BUCKET_NAME, + resolveProfilePictureObjectName, +} from "../profile-picture/security"; +import { profilePictureStorageClient } from "../profile-picture/storage"; + +/** + * The only way another member's application leaves the API. + * + * The visibility filter is applied here rather than by each caller, and + * `privateNotes` is not selected at all, so a new community view cannot forget + * either rule. Notes stay private even on a community-visible application. + */ +const communityColumns = { + applicationId: JobApplication.id, + companyKey: Job.companyKey, + companyLabel: Job.companyLabel, + discordUser: Member.discordUser, + firstName: Member.firstName, + interviewLabel: JobApplication.interviewLabel, + jobId: JobApplication.jobId, + jobTitle: Job.title, + lastName: Member.lastName, + memberId: Member.id, + profilePictureReference: Member.profilePictureUrl, + round: JobApplication.round, + stage: JobApplication.stage, + track: Job.track, + updatedAt: JobApplication.updatedAt, + userId: Member.userId, +} as const; + +function communityWhere(filter: SQL | undefined) { + return and(eq(JobApplication.visibility, "community"), filter); +} + +async function profilePictureUrl(reference: string | null, userId: string) { + if (!reference) return null; + const objectName = resolveProfilePictureObjectName(reference, userId); + if (!objectName) return null; + + try { + return await profilePictureStorageClient.presignedUrl( + "GET", + PROFILE_PICTURE_BUCKET_NAME, + objectName, + 60 * 60, + ); + } catch { + return null; + } +} + +export async function listCommunityApplications( + filter: SQL | undefined, + page?: { limit: number; offset: number }, +) { + const query = db + .select(communityColumns) + .from(JobApplication) + .innerJoin(Job, eq(Job.id, JobApplication.jobId)) + .innerJoin(Member, eq(Member.id, JobApplication.memberId)) + .where(communityWhere(filter)) + .orderBy(desc(JobApplication.updatedAt), asc(JobApplication.id)); + const rows = await (page + ? query.limit(page.limit).offset(page.offset) + : query); + + return await Promise.all( + rows.map(async ({ profilePictureReference, userId, ...row }) => ({ + ...row, + profilePictureUrl: await profilePictureUrl( + profilePictureReference, + userId, + ), + })), + ); +} + +export async function countCommunityApplications(filter: SQL | undefined) { + const [row] = await db + .select({ total: count() }) + .from(JobApplication) + .innerJoin(Job, eq(Job.id, JobApplication.jobId)) + .where(communityWhere(filter)); + return row?.total ?? 0; +} + +export type CommunityApplication = Awaited< + ReturnType +>[number]; diff --git a/packages/api/src/utils/job-board/search.ts b/packages/api/src/utils/job-board/search.ts new file mode 100644 index 000000000..301769d4f --- /dev/null +++ b/packages/api/src/utils/job-board/search.ts @@ -0,0 +1,159 @@ +import type { SQL } from "@forge/db"; +import type { JobSearchInput } from "@forge/validators"; +import { JOB_BOARD } from "@forge/consts"; +import { + and, + asc, + desc, + eq, + exists, + gte, + ilike, + inArray, + or, + sql, +} from "@forge/db"; +import { db } from "@forge/db/client"; +import { + Job, + JobLocation, + JobObservation, + JobSource, +} from "@forge/db/schemas/job-board"; + +import { getUsCity } from "../career/us-cities"; + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** `%` and `_` are typed by members as text, not as wildcards. */ +export function containsPattern(text: string) { + return `%${text.replace(/[\\%_]/g, "\\$&")}%`; +} + +function locationCondition(input: JobSearchInput): SQL | undefined { + // Location filters widen each other: a member who picks Orlando and U.S. + // remote wants jobs in either, not jobs that are somehow both. + const matches: SQL[] = []; + if (input.cityKey) matches.push(eq(JobLocation.cityKey, input.cityKey)); + if (input.state) matches.push(eq(JobLocation.state, input.state)); + if (input.remoteUs) matches.push(eq(JobLocation.kind, "remote_us")); + if (matches.length === 0) return undefined; + + return exists( + db + .select({ id: JobLocation.id }) + .from(JobLocation) + .where(and(eq(JobLocation.jobId, Job.id), or(...matches))), + ); +} + +export function jobSearchConditions( + input: JobSearchInput, + now = new Date(), +): SQL | undefined { + const conditions: (SQL | undefined)[] = [locationCondition(input)]; + + if (!input.includeInactive) conditions.push(eq(Job.active, true)); + if (input.track) conditions.push(eq(Job.track, input.track)); + if (input.category) conditions.push(eq(Job.category, input.category)); + if (input.company) conditions.push(eq(Job.companyKey, input.company)); + if (input.postedWithin) { + // A job with no source posted date fails this comparison and drops out. + const days = JOB_BOARD.JOB_POSTED_WITHIN_DAYS[input.postedWithin]; + conditions.push(gte(Job.postedAt, new Date(now.getTime() - days * DAY_MS))); + } + if (input.query) { + const pattern = containsPattern(input.query); + conditions.push( + or(ilike(Job.title, pattern), ilike(Job.companyLabel, pattern)), + ); + } + + return and(...conditions); +} + +// Every ordering ends on the primary key so pages never repeat or skip a job +// when two rows tie on the visible sort column. +export function jobSearchOrder(sort: JOB_BOARD.JobSort): SQL[] { + switch (sort) { + case "company": + return [asc(Job.companyKey), asc(Job.title), asc(Job.id)]; + case "recently_posted": + return [ + sql`${Job.postedAt} DESC NULLS LAST`, + desc(Job.firstSeenAt), + asc(Job.id), + ]; + case "newest": + return [desc(Job.firstSeenAt), asc(Job.id)]; + } +} + +/** What members may see of a listing. Delivery and identity state stay out. */ +export const jobSummaryColumns = { + active: Job.active, + applyUrl: Job.applyUrl, + category: Job.category, + companyId: Job.companyId, + companyKey: Job.companyKey, + companyLabel: Job.companyLabel, + compensation: Job.compensation, + firstSeenAt: Job.firstSeenAt, + id: Job.id, + inactiveAt: Job.inactiveAt, + postedAt: Job.postedAt, + title: Job.title, + track: Job.track, + workArrangement: Job.workArrangement, +} as const; + +export async function listJobLocations(jobIds: readonly string[]) { + const byJob = new Map(); + if (jobIds.length === 0) return byJob; + + const rows = await db + .select({ + cityKey: JobLocation.cityKey, + jobId: JobLocation.jobId, + kind: JobLocation.kind, + sourceText: JobLocation.sourceText, + state: JobLocation.state, + }) + .from(JobLocation) + .where(inArray(JobLocation.jobId, [...jobIds])) + .orderBy(asc(JobLocation.sourceText), asc(JobLocation.id)); + + for (const { jobId, ...location } of rows) { + const locations = byJob.get(jobId) ?? []; + locations.push({ + ...location, + cityName: location.cityKey + ? (getUsCity(location.cityKey)?.name ?? null) + : null, + }); + byJob.set(jobId, locations); + } + return byJob; +} + +export interface JobLocationView { + cityKey: string | null; + cityName: string | null; + kind: JOB_BOARD.JobLocationKind; + sourceText: string; + state: string | null; +} + +/** Where a listing was found, so members can judge and follow the source. */ +export async function listJobSources(jobId: string) { + return await db + .select({ + label: JobSource.label, + provider: JobSource.provider, + sourceUrl: JobObservation.sourceUrl, + }) + .from(JobObservation) + .innerJoin(JobSource, eq(JobSource.id, JobObservation.sourceId)) + .where(eq(JobObservation.jobId, jobId)) + .orderBy(asc(JobSource.label), asc(JobObservation.id)); +} diff --git a/packages/consts/src/job-board.ts b/packages/consts/src/job-board.ts index 7b930a38b..c4f081c9e 100644 --- a/packages/consts/src/job-board.ts +++ b/packages/consts/src/job-board.ts @@ -162,6 +162,9 @@ export const APPLICATION_ROUND_STAGES = [ export const MAX_APPLICATION_ROUND = 10; +/** Free-text description of an interview round, such as "Behavioral". */ +export const MAX_APPLICATION_INTERVIEW_LABEL_LENGTH = 120; + export const APPLICATION_VISIBILITIES = ["community", "private"] as const; export type ApplicationVisibility = (typeof APPLICATION_VISIBILITIES)[number]; diff --git a/packages/validators/src/audit.ts b/packages/validators/src/audit.ts index 1647a648e..97e2b2c30 100644 --- a/packages/validators/src/audit.ts +++ b/packages/validators/src/audit.ts @@ -291,6 +291,9 @@ export const AUDIT_ACTION_CATALOG = { "deletedObjectCount", "filesCleaned", ]), + // Self-service, and deliberately without metadata: a member's application + // may be private, so the event does not say which job it was for. + "job_board.application.removed": policy("members", "Removed job application"), "member.profile_picture.replaced": policy( "members", "Replaced member profile picture", diff --git a/packages/validators/src/job-board.ts b/packages/validators/src/job-board.ts index 8a1d0c971..8cf65b632 100644 --- a/packages/validators/src/job-board.ts +++ b/packages/validators/src/job-board.ts @@ -140,9 +140,53 @@ const applicationNotesSchema = z ) .transform((value) => (value.trim().length > 0 ? value : null)); +const applicationInterviewLabelSchema = z + .string() + .trim() + .max( + JOB_BOARD.MAX_APPLICATION_INTERVIEW_LABEL_LENGTH, + `Use ${JOB_BOARD.MAX_APPLICATION_INTERVIEW_LABEL_LENGTH} characters or fewer.`, + ) + .transform((value) => (value.length > 0 ? value : null)); + +/** + * When the stage change actually happened, for progress logged after the fact. + * Omit it to use the time of saving. + */ +const applicationOccurredAtSchema = z.coerce + .date() + .refine( + (value) => value.getTime() <= Date.now(), + "Use a date that is not in the future.", + ); + +const INTERVIEW_ONLY_FIELDS = [ + ["round", "Rounds apply only while interviewing."], + ["interviewLabel", "Interview labels apply only while interviewing."], +] as const; + +/** Rejects a round or interview label on a stage that is known not to allow one. */ +function checkInterviewOnlyFields( + input: { + interviewLabel?: string | null; + round?: number | null; + stage?: JOB_BOARD.ApplicationStage; + }, + context: z.RefinementCtx, +) { + if (input.stage === undefined || stageAllowsRound(input.stage)) return; + for (const [field, message] of INTERVIEW_ONLY_FIELDS) { + if (input[field] != null) { + context.addIssue({ code: "custom", message, path: [field] }); + } + } +} + export const applicationSaveInputSchema = z .object({ + interviewLabel: applicationInterviewLabelSchema.nullable().optional(), jobId: z.string().uuid(), + occurredAt: applicationOccurredAtSchema.optional(), privateNotes: applicationNotesSchema.nullable().optional(), round: applicationRoundSchema.nullable().optional(), stage: applicationStageSchema.default("saved"), @@ -151,28 +195,24 @@ export const applicationSaveInputSchema = z ), }) .strict() - .superRefine((input, context) => { - if (input.round != null && !stageAllowsRound(input.stage)) { - context.addIssue({ - code: "custom", - message: "Rounds apply only while interviewing.", - path: ["round"], - }); - } - }) + .superRefine(checkInterviewOnlyFields) .transform((input) => ({ ...input, + interviewLabel: input.interviewLabel ?? null, privateNotes: input.privateNotes ?? null, round: input.round ?? null, })); /** - * Partial update. When `stage` is omitted the API checks `round` against the - * stored stage, so this schema can only reject combinations it can see. + * Partial update. When `stage` is omitted the API checks `round` and + * `interviewLabel` against the stored stage, so this schema can only reject + * combinations it can see. */ export const applicationUpdateInputSchema = z .object({ applicationId: z.string().uuid(), + interviewLabel: applicationInterviewLabelSchema.nullable().optional(), + occurredAt: applicationOccurredAtSchema.optional(), privateNotes: applicationNotesSchema.nullable().optional(), round: applicationRoundSchema.nullable().optional(), stage: applicationStageSchema.optional(), @@ -181,6 +221,7 @@ export const applicationUpdateInputSchema = z .strict() .superRefine((input, context) => { const changesSomething = + input.interviewLabel !== undefined || input.privateNotes !== undefined || input.round !== undefined || input.stage !== undefined || @@ -192,17 +233,7 @@ export const applicationUpdateInputSchema = z path: [], }); } - if ( - input.stage !== undefined && - input.round != null && - !stageAllowsRound(input.stage) - ) { - context.addIssue({ - code: "custom", - message: "Rounds apply only while interviewing.", - path: ["round"], - }); - } + checkInterviewOnlyFields(input, context); }); export const applicationIdInputSchema = z diff --git a/packages/validators/src/tests/job-board.test.ts b/packages/validators/src/tests/job-board.test.ts index 4c65bca9c..8cb3e8252 100644 --- a/packages/validators/src/tests/job-board.test.ts +++ b/packages/validators/src/tests/job-board.test.ts @@ -156,6 +156,7 @@ describe("alert targets", () => { describe("application input", () => { it("defaults to a saved, community-visible application", () => { expect(applicationSaveInputSchema.parse({ jobId })).toEqual({ + interviewLabel: null, jobId, privateNotes: null, round: null, @@ -184,6 +185,39 @@ describe("application input", () => { expect(result.error?.issues[0]?.path).toEqual(["round"]); }); + it("accepts an interview label only while interviewing", () => { + expect( + applicationSaveInputSchema.parse({ + interviewLabel: " Behavioral ", + jobId, + stage: "interviewing", + }).interviewLabel, + ).toBe("Behavioral"); + const result = applicationUpdateInputSchema.safeParse({ + applicationId, + interviewLabel: "Behavioral", + stage: "applied", + }); + expect(result.error?.issues[0]?.path).toEqual(["interviewLabel"]); + }); + + it("accepts a past stage date and rejects a future one", () => { + expect( + applicationSaveInputSchema.parse({ + jobId, + occurredAt: "2026-10-22", + stage: "applied", + }).occurredAt, + ).toEqual(new Date("2026-10-22")); + expect( + applicationSaveInputSchema.safeParse({ + jobId, + occurredAt: new Date(Date.now() + 86_400_000), + stage: "applied", + }).success, + ).toBe(false); + }); + it("clears a round when leaving interviewing", () => { expect( applicationSaveInputSchema.safeParse({ From 42c8bc31be0dd3f7c51ba2e6e0a3cb8c32e681a7 Mon Sep 17 00:00:00 2001 From: kevin li Date: Mon, 16 Nov 2026 23:03:34 -0500 Subject: [PATCH 2/2] [#651] Hide saved applications from other members A saved application is a bookmark, not part of a hiring process, so the community projection now excludes it whatever its visibility. Co-Authored-By: Claude Fable 5.2 --- .forge/features/career-job-router/spec.md | 4 ++-- .forge/features/career-job-router/status.md | 3 ++- .../api/src/tests/integration/job-board.test.ts | 14 ++++++++++++-- packages/api/src/utils/job-board/community.ts | 11 +++++++++-- 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/.forge/features/career-job-router/spec.md b/.forge/features/career-job-router/spec.md index 68b943023..b5444bd4b 100644 --- a/.forge/features/career-job-router/spec.md +++ b/.forge/features/career-job-router/spec.md @@ -59,12 +59,12 @@ No pages in this slice. It supplies: - Other members see a community application's name, picture, Discord username, stage, round and interview label, and never its notes. - A private application appears in no view except its owner's. +- A `saved` application (bookmarked, not yet applied) appears in no view except + its owner's, whatever its visibility. - Each progress change adds one dated timeline entry; editing notes or visibility adds none. - A member can change or remove only their own applications. ## Open questions -- Should a `saved` (bookmarked, not yet applied) application appear to other - members? #633 says stages are visible by default, so it currently does. - Location filters widen each other (a city or U.S. remote). Confirm with #655. diff --git a/.forge/features/career-job-router/status.md b/.forge/features/career-job-router/status.md index a753ea675..dfea61fd6 100644 --- a/.forge/features/career-job-router/status.md +++ b/.forge/features/career-job-router/status.md @@ -12,6 +12,8 @@ Current phase: PR 1 implemented, validated locally and opened as a draft PR. to the time of saving. Timeline entries are not editable. - 2026-11-16: Community views show name, profile picture, Discord username, stage, round and interview label. +- 2026-11-16: Kevin decided `saved` applications are never shown to other + members; someone who has not applied is not in a process. - Implementation choices to confirm in review: no new officer procedure because `discordConfig.list` and `discordConfig.update` already cover the Career keys; a missing member profile is `FORBIDDEN`; location filters widen each other; @@ -19,7 +21,6 @@ Current phase: PR 1 implemented, validated locally and opened as a draft PR. ## Open questions -- Should `saved` applications be visible to other members? - Confirm location filter behavior with the #655 owner. ## Task list diff --git a/packages/api/src/tests/integration/job-board.test.ts b/packages/api/src/tests/integration/job-board.test.ts index a8a846076..b91df3bf1 100644 --- a/packages/api/src/tests/integration/job-board.test.ts +++ b/packages/api/src/tests/integration/job-board.test.ts @@ -224,10 +224,20 @@ describe.runIf(canRunDatabaseTests())("job board router", () => { ).rejects.toMatchObject({ code: "BAD_REQUEST" }); }); - it("shows community applications without notes and keeps private ones out of every view", async () => { - const hidden = await blake.saveApplication({ + it("shows community applications without notes and keeps saved and private ones out of every view", async () => { + // A bookmark is community-visible by default but is not yet an application. + const bookmarked = await blake.saveApplication({ jobId: openJobId, privateNotes: "Do not share", + }); + const beforeApplying = await alex.listPeopleInProcess({}); + expect(beforeApplying.people.map((person) => person.memberId)).toEqual([ + ALEX.memberId, + ]); + expect(beforeApplying.total).toBe(1); + + const hidden = await blake.updateApplication({ + applicationId: bookmarked.id, stage: "applied", visibility: "private", }); diff --git a/packages/api/src/utils/job-board/community.ts b/packages/api/src/utils/job-board/community.ts index f8dfe86d5..387908ada 100644 --- a/packages/api/src/utils/job-board/community.ts +++ b/packages/api/src/utils/job-board/community.ts @@ -1,5 +1,5 @@ import type { SQL } from "@forge/db"; -import { and, asc, count, desc, eq } from "@forge/db"; +import { and, asc, count, desc, eq, ne } from "@forge/db"; import { db } from "@forge/db/client"; import { Job, JobApplication } from "@forge/db/schemas/job-board"; import { Member } from "@forge/db/schemas/knight-hacks"; @@ -16,6 +16,9 @@ import { profilePictureStorageClient } from "../profile-picture/storage"; * The visibility filter is applied here rather than by each caller, and * `privateNotes` is not selected at all, so a new community view cannot forget * either rule. Notes stay private even on a community-visible application. + * + * A `saved` application is a bookmark, not part of anyone's process, so it is + * never shown to other members whatever its visibility. */ const communityColumns = { applicationId: JobApplication.id, @@ -37,7 +40,11 @@ const communityColumns = { } as const; function communityWhere(filter: SQL | undefined) { - return and(eq(JobApplication.visibility, "community"), filter); + return and( + eq(JobApplication.visibility, "community"), + ne(JobApplication.stage, "saved"), + filter, + ); } async function profilePictureUrl(reference: string | null, userId: string) {