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
2 changes: 2 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { outreachRouter } from '@/routes/outreach';
import { telemetryRouter } from '@/routes/telemetry';
import { discoveryRouter, discoverySweepRouter } from '@/routes/discovery';
import { savedSearchesRouter } from '@/routes/saved-searches';
import { targetCompaniesRouter } from '@/routes/target-companies';

const mutatingMethods = new Set(['POST', 'PATCH', 'PUT', 'DELETE']);

Expand Down Expand Up @@ -129,6 +130,7 @@ export function createApp(dependencies: AppDependencies = {}) {
app.use('/api/telemetry', strictLimiter, telemetryRouter);
app.use('/api/discovery', strictLimiter, discoveryRouter);
app.use('/api/saved-searches', savedSearchesRouter);
app.use('/api/target-companies', targetCompaniesRouter);
// Mounted before '/api/n8n' so this more specific path wins; it inherits the
// shared-API-key exemption (path starts with /api/n8n) and uses the n8n secret.
app.use('/api/n8n/discover', discoverySweepRouter);
Expand Down
88 changes: 88 additions & 0 deletions apps/api/src/data/target-company-store.postgres.ts
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]);
}
101 changes: 101 additions & 0 deletions apps/api/src/data/target-company-store.test.ts
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 });
}
});
170 changes: 170 additions & 0 deletions apps/api/src/data/target-company-store.ts
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> {
Comment thread
Taleef7 marked this conversation as resolved.
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();
}
2 changes: 2 additions & 0 deletions apps/api/src/routes/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { clearUserData, seedDemoData } from '@/data/job-store';
import { clearUserReports, seedDemoReports } from '@/data/report-store';
import { deleteUserProfile } from '@/data/profile-store';
import { clearUserSavedSearches } from '@/data/saved-search-store';
import { clearUserTargetCompanies } from '@/data/target-company-store';
import { requireUser } from '@/lib/auth';

export const demoRouter = Router();
Expand All @@ -29,6 +30,7 @@ demoRouter.post('/clear', async (request, response, next) => {
await clearUserReports(userId);
await deleteUserProfile(userId);
await clearUserSavedSearches(userId);
await clearUserTargetCompanies(userId);
response.json({ ok: true });
} catch (error) {
next(error);
Expand Down
Loading
Loading