-
Notifications
You must be signed in to change notification settings - Fork 0
feat(api,web): target_companies table, CRUD, and settings watchlist (#260) #312
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import { randomUUID } from 'node:crypto'; | ||
| import type { BoardType, CreateTargetCompanyBody, TargetCompany } from '@/types'; | ||
| import { getPool } from '@/lib/postgres'; | ||
|
|
||
| type TargetCompanyRow = { | ||
| id: string; | ||
| user_id: string; | ||
| company: string; | ||
| board_type: string; | ||
| board_token: string; | ||
| enabled: boolean; | ||
| created_at: string; | ||
| updated_at: string; | ||
| }; | ||
|
|
||
| function poolOrThrow() { | ||
| const pool = getPool(); | ||
| if (!pool) { | ||
| throw new Error('Postgres is not configured. Set DATABASE_URL to enable the database-backed store.'); | ||
| } | ||
| return pool; | ||
| } | ||
|
|
||
| function mapRow(row: TargetCompanyRow): TargetCompany { | ||
| return { | ||
| id: row.id, | ||
| userId: row.user_id, | ||
| company: row.company, | ||
| boardType: row.board_type as BoardType, | ||
| boardToken: row.board_token, | ||
| enabled: row.enabled, | ||
| createdAt: row.created_at, | ||
| updatedAt: row.updated_at, | ||
| }; | ||
| } | ||
|
|
||
| export async function listTargetCompanies(userId: string): Promise<TargetCompany[]> { | ||
| const { rows } = await poolOrThrow().query<TargetCompanyRow>( | ||
| 'select * from target_companies where user_id = $1 order by created_at desc', | ||
| [userId], | ||
| ); | ||
| return rows.map(mapRow); | ||
| } | ||
|
|
||
| export async function listEnabledTargetCompanies(userId: string): Promise<TargetCompany[]> { | ||
| const { rows } = await poolOrThrow().query<TargetCompanyRow>( | ||
| 'select * from target_companies where user_id = $1 and enabled = true order by created_at desc', | ||
| [userId], | ||
| ); | ||
| return rows.map(mapRow); | ||
| } | ||
|
|
||
| export async function createTargetCompany(userId: string, body: CreateTargetCompanyBody): Promise<TargetCompany> { | ||
| const { rows } = await poolOrThrow().query<TargetCompanyRow>( | ||
| 'insert into target_companies (id, user_id, company, board_type, board_token) values ($1,$2,$3,$4,$5) returning *', | ||
| [randomUUID(), userId, body.company, body.boardType, body.boardToken], | ||
| ); | ||
| const saved = rows[0]; | ||
| if (!saved) { | ||
| throw new Error('Failed to create target company'); | ||
| } | ||
| return mapRow(saved); | ||
| } | ||
|
|
||
| export async function setTargetCompanyEnabled( | ||
| userId: string, | ||
| id: string, | ||
| enabled: boolean, | ||
| ): Promise<TargetCompany | undefined> { | ||
| const { rows } = await poolOrThrow().query<TargetCompanyRow>( | ||
| 'update target_companies set enabled = $1 where user_id = $2 and id::text = $3 returning *', | ||
| [enabled, userId, id], | ||
| ); | ||
| const row = rows[0]; | ||
| return row ? mapRow(row) : undefined; | ||
| } | ||
|
|
||
| export async function deleteTargetCompany(userId: string, id: string): Promise<boolean> { | ||
| const { rowCount } = await poolOrThrow().query( | ||
| 'delete from target_companies where user_id = $1 and id::text = $2', | ||
| [userId, id], | ||
| ); | ||
| return (rowCount ?? 0) > 0; | ||
| } | ||
|
|
||
| export async function clearUserTargetCompanies(userId: string): Promise<void> { | ||
| await poolOrThrow().query('delete from target_companies where user_id = $1', [userId]); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { mkdtemp, rm } from 'node:fs/promises'; | ||
| import { tmpdir } from 'node:os'; | ||
| import { join } from 'node:path'; | ||
| import test from 'node:test'; | ||
| import { | ||
| clearUserTargetCompanies, | ||
| createTargetCompany, | ||
| deleteTargetCompany, | ||
| listEnabledTargetCompanies, | ||
| listTargetCompanies, | ||
| resetTargetCompanyStoreForTests, | ||
| setTargetCompanyEnabled, | ||
| } from './target-company-store'; | ||
|
|
||
| const USER = 'user_tc_store_test'; | ||
|
|
||
| test('target companies round-trip CRUD and stay user-scoped', async () => { | ||
| const originalCwd = process.cwd(); | ||
| const tempDir = await mkdtemp(join(tmpdir(), 'jobops-tc-store-')); | ||
| try { | ||
| process.chdir(tempDir); | ||
| resetTargetCompanyStoreForTests(); | ||
|
|
||
| assert.equal((await listTargetCompanies(USER)).length, 0); | ||
|
|
||
| const created = await createTargetCompany(USER, { | ||
| company: ' Stripe ', | ||
| boardType: 'greenhouse', | ||
| boardToken: 'stripe', | ||
| }); | ||
| assert.equal(created.company, ' Stripe '); | ||
| assert.equal(created.boardType, 'greenhouse'); | ||
| assert.equal(created.boardToken, 'stripe'); | ||
| assert.equal(created.enabled, true); | ||
| assert.ok(created.id); | ||
|
|
||
| assert.equal((await listTargetCompanies(USER)).length, 1); | ||
| assert.equal((await listTargetCompanies('user_other')).length, 0); | ||
|
|
||
| // Toggle enabled off | ||
| const toggled = await setTargetCompanyEnabled(USER, created.id, false); | ||
| assert.ok(toggled); | ||
| assert.equal(toggled!.enabled, false); | ||
|
|
||
| // listEnabled should exclude it | ||
| assert.equal((await listEnabledTargetCompanies(USER)).length, 0); | ||
|
|
||
| // Toggle back on | ||
| const reEnabled = await setTargetCompanyEnabled(USER, created.id, true); | ||
| assert.ok(reEnabled); | ||
| assert.equal(reEnabled!.enabled, true); | ||
| assert.equal((await listEnabledTargetCompanies(USER)).length, 1); | ||
|
|
||
| // Cannot delete another user's entry | ||
| assert.equal(await deleteTargetCompany('user_other', created.id), false); | ||
| assert.equal(await deleteTargetCompany(USER, created.id), true); | ||
| assert.equal((await listTargetCompanies(USER)).length, 0); | ||
| } finally { | ||
| process.chdir(originalCwd); | ||
| await rm(tempDir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
|
|
||
| test('setTargetCompanyEnabled returns undefined for unknown id', async () => { | ||
| const originalCwd = process.cwd(); | ||
| const tempDir = await mkdtemp(join(tmpdir(), 'jobops-tc-store-undef-')); | ||
| try { | ||
| process.chdir(tempDir); | ||
| resetTargetCompanyStoreForTests(); | ||
|
|
||
| const result = await setTargetCompanyEnabled(USER, 'does-not-exist', false); | ||
| assert.equal(result, undefined); | ||
| } finally { | ||
| process.chdir(originalCwd); | ||
| await rm(tempDir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
|
|
||
| test('clearUserTargetCompanies removes only the target user records', async () => { | ||
| const originalCwd = process.cwd(); | ||
| const tempDir = await mkdtemp(join(tmpdir(), 'jobops-tc-store-clear-')); | ||
| try { | ||
| process.chdir(tempDir); | ||
| resetTargetCompanyStoreForTests(); | ||
|
|
||
| await createTargetCompany(USER, { company: 'Stripe', boardType: 'greenhouse', boardToken: 'stripe' }); | ||
| await createTargetCompany('other_user', { company: 'Linear', boardType: 'ashby', boardToken: 'linear' }); | ||
|
|
||
| assert.equal((await listTargetCompanies(USER)).length, 1); | ||
| assert.equal((await listTargetCompanies('other_user')).length, 1); | ||
|
|
||
| await clearUserTargetCompanies(USER); | ||
|
|
||
| assert.equal((await listTargetCompanies(USER)).length, 0); | ||
| assert.equal((await listTargetCompanies('other_user')).length, 1); | ||
| } finally { | ||
| process.chdir(originalCwd); | ||
| await rm(tempDir, { recursive: true, force: true }); | ||
| } | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| import { randomUUID } from 'node:crypto'; | ||
| import { mkdir, readFile, writeFile } from 'node:fs/promises'; | ||
| import { join } from 'node:path'; | ||
| import type { CreateTargetCompanyBody, TargetCompany } from '@/types'; | ||
| import { hasPostgresConnection } from '@/lib/postgres'; | ||
| import * as postgresStore from '@/data/target-company-store.postgres'; | ||
|
|
||
| let cache: TargetCompany[] | null = null; | ||
| let loadPromise: Promise<TargetCompany[]> | null = null; | ||
| let mutationQueue: Promise<void> = Promise.resolve(); | ||
|
|
||
| function clone<T>(value: T): T { | ||
| return JSON.parse(JSON.stringify(value)) as T; | ||
| } | ||
|
|
||
| function dataDir() { | ||
| return join(process.cwd(), 'data'); | ||
| } | ||
|
|
||
| function dataFile() { | ||
| return join(dataDir(), 'target-companies.json'); | ||
| } | ||
|
|
||
| async function load(): Promise<TargetCompany[]> { | ||
| await mkdir(dataDir(), { recursive: true }); | ||
| try { | ||
| const raw = await readFile(dataFile(), 'utf8'); | ||
| const parsed = JSON.parse(raw) as unknown; | ||
| if (!Array.isArray(parsed)) { | ||
| throw new Error('Invalid target-company store contents'); | ||
| } | ||
| cache = parsed as TargetCompany[]; | ||
| } catch { | ||
| cache = []; | ||
| await persist(); | ||
| } | ||
| return cache; | ||
| } | ||
|
|
||
| async function ensureLoaded(): Promise<TargetCompany[]> { | ||
| if (cache) { | ||
| return cache; | ||
| } | ||
| loadPromise ??= load(); | ||
| return loadPromise; | ||
| } | ||
|
|
||
| async function persist() { | ||
| if (!cache) { | ||
| return; | ||
| } | ||
| await mkdir(dataDir(), { recursive: true }); | ||
| await writeFile(dataFile(), `${JSON.stringify(cache, null, 2)}\n`, 'utf8'); | ||
| } | ||
|
|
||
| async function runExclusive<T>(operation: () => Promise<T>): Promise<T> { | ||
| const previous = mutationQueue; | ||
| let release!: () => void; | ||
| mutationQueue = new Promise<void>((resolve) => { | ||
| release = resolve; | ||
| }); | ||
| await previous; | ||
| try { | ||
| return await operation(); | ||
| } finally { | ||
| release(); | ||
| } | ||
| } | ||
|
|
||
| export async function listTargetCompanies(userId: string): Promise<TargetCompany[]> { | ||
| if (hasPostgresConnection()) { | ||
| return postgresStore.listTargetCompanies(userId); | ||
| } | ||
| const all = await ensureLoaded(); | ||
| return clone( | ||
| all | ||
| .filter((entry) => entry.userId === userId) | ||
| .sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt)), | ||
| ); | ||
| } | ||
|
|
||
| export async function listEnabledTargetCompanies(userId: string): Promise<TargetCompany[]> { | ||
| if (hasPostgresConnection()) { | ||
| return postgresStore.listEnabledTargetCompanies(userId); | ||
| } | ||
| const all = await ensureLoaded(); | ||
| return clone( | ||
| all | ||
| .filter((entry) => entry.userId === userId && entry.enabled) | ||
| .sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt)), | ||
| ); | ||
| } | ||
|
|
||
| export async function createTargetCompany(userId: string, body: CreateTargetCompanyBody): Promise<TargetCompany> { | ||
| if (hasPostgresConnection()) { | ||
| return postgresStore.createTargetCompany(userId, body); | ||
| } | ||
| return runExclusive(async () => { | ||
| const all = await ensureLoaded(); | ||
| const duplicate = all.find( | ||
| (e) => e.userId === userId && e.boardType === body.boardType && e.boardToken === body.boardToken, | ||
| ); | ||
| if (duplicate) { | ||
| throw new Error('This board is already tracked.'); | ||
| } | ||
| const now = new Date().toISOString(); | ||
| const entry: TargetCompany = { | ||
| id: randomUUID(), | ||
| userId, | ||
| company: body.company, | ||
| boardType: body.boardType, | ||
| boardToken: body.boardToken, | ||
| enabled: true, | ||
| createdAt: now, | ||
| updatedAt: now, | ||
| }; | ||
| all.unshift(entry); | ||
| await persist(); | ||
| return clone(entry); | ||
| }); | ||
| } | ||
|
|
||
| export async function setTargetCompanyEnabled( | ||
| userId: string, | ||
| id: string, | ||
| enabled: boolean, | ||
| ): Promise<TargetCompany | undefined> { | ||
| if (hasPostgresConnection()) { | ||
| return postgresStore.setTargetCompanyEnabled(userId, id, enabled); | ||
| } | ||
| return runExclusive(async () => { | ||
| const all = await ensureLoaded(); | ||
| const entry = all.find((e) => e.id === id && e.userId === userId); | ||
| if (!entry) return undefined; | ||
| entry.enabled = enabled; | ||
| entry.updatedAt = new Date().toISOString(); | ||
| await persist(); | ||
| return clone(entry); | ||
| }); | ||
| } | ||
|
|
||
| export async function deleteTargetCompany(userId: string, id: string): Promise<boolean> { | ||
| if (hasPostgresConnection()) { | ||
| return postgresStore.deleteTargetCompany(userId, id); | ||
| } | ||
| return runExclusive(async () => { | ||
| const all = await ensureLoaded(); | ||
| const before = all.length; | ||
| cache = all.filter((entry) => !(entry.id === id && entry.userId === userId)); | ||
| await persist(); | ||
| return cache.length < before; | ||
| }); | ||
| } | ||
|
|
||
| export async function clearUserTargetCompanies(userId: string): Promise<void> { | ||
| if (hasPostgresConnection()) { | ||
| return postgresStore.clearUserTargetCompanies(userId); | ||
| } | ||
| return runExclusive(async () => { | ||
| const all = await ensureLoaded(); | ||
| cache = all.filter((entry) => entry.userId !== userId); | ||
| await persist(); | ||
| }); | ||
| } | ||
|
|
||
| export function resetTargetCompanyStoreForTests() { | ||
| cache = null; | ||
| loadPromise = null; | ||
| mutationQueue = Promise.resolve(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.