@profullstack/gov-contracts 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
1
+ /**
2
+ * SAM.gov contract opportunities (federal). Datamart provider us.sam.opportunities.
3
+ *
4
+ * With SAM_API_KEY (a free key from a SAM.gov account) the official Get
5
+ * Opportunities v2 API is used. Without one, the public, unauthenticated
6
+ * search that sam.gov's own pages read (robots.txt does not disallow /api/),
7
+ * at a few queries every six hours, one request at a time with a delay.
8
+ * Read only: SAM.gov has no submission API and we would not use one.
9
+ */
10
+ import { htmlToText, fetchBytes, http, pdfText } from '../http.js';
11
+ import { prefilter } from '../fit.js';
12
+
13
+ export const ID = 'us.sam.opportunities';
14
+ const SEARCH = 'https://sam.gov/api/prod/sgs/v1/search/';
15
+ const DETAIL = (id) => `https://sam.gov/api/prod/opps/v2/opportunities/${id}`;
16
+ const RESOURCES = (id) => `https://sam.gov/api/prod/opps/v3/opportunities/${id}/resources`;
17
+ const FILE = (rid) => `https://sam.gov/api/prod/opps/v3/opportunities/resources/files/${rid}/download`;
18
+ export const noticeUrl = (id) => `https://sam.gov/opp/${id}/view`;
19
+
20
+ /** Queries matching the niche focus (software, security, automation, hardware rental). */
21
+ export const QUERIES = [
22
+ 'software development',
23
+ 'cybersecurity',
24
+ 'information technology services',
25
+ 'automation artificial intelligence',
26
+ 'case management system',
27
+ 'cloud hosting',
28
+ 'GPU computing',
29
+ ];
30
+
31
+ /** Notice types worth bidding on: solicitation, combined synopsis, presolicitation, sources sought, special notice. */
32
+ const KEEP_TYPES = new Set(['o', 'k', 'p', 'r', 's']);
33
+
34
+ const today = () => new Date().toISOString().slice(0, 10);
35
+
36
+ /** sam.gov answers 406 to a bare `Accept: application/json`; the browser's list works. */
37
+ const ACCEPT = { accept: 'application/json, text/plain, */*' };
38
+
39
+ function agencyFrom(org) {
40
+ if (!Array.isArray(org)) return null;
41
+ const names = org.map((o) => o?.name).filter(Boolean);
42
+ if (!names.length) return null;
43
+ return names.length > 1 ? `${names[0]} / ${names[names.length - 1]}` : names[0];
44
+ }
45
+
46
+ /** Map one public-search result to a solicitation, or null when it is not open and biddable. */
47
+ export function fromSearch(r) {
48
+ if (!r || r.isCanceled || r.isActive === false) return null;
49
+ if (!KEEP_TYPES.has(r.type?.code)) return null;
50
+ const due = r.responseDate ? String(r.responseDate).slice(0, 10) : null;
51
+ if (due && due < today()) return null;
52
+ if (!due) {
53
+ // Special notices and sources sought without a deadline: keep only recent ones.
54
+ const posted = Date.parse(r.publishDate || '');
55
+ if (!posted || Date.now() - posted > 30 * 86400_000) return null;
56
+ }
57
+ const description = htmlToText(r.descriptions?.[0]?.content || '').slice(0, 6000);
58
+ const s = {
59
+ source: 'sam',
60
+ ext_id: r._id,
61
+ number: r.solicitationNumber || null,
62
+ title: String(r.title || '').trim(),
63
+ agency: agencyFrom(r.organizationHierarchy),
64
+ level: 'federal',
65
+ region: 'US',
66
+ url: noticeUrl(r._id),
67
+ notice_type: r.type?.value || null,
68
+ posted_at: r.publishDate || null,
69
+ due_at: r.responseDate || null,
70
+ description,
71
+ };
72
+ if (!s.title) return null;
73
+ s.prefilter = prefilter(s);
74
+ return s;
75
+ }
76
+
77
+ /** Map one official v2 API record. */
78
+ export function fromApi(r) {
79
+ const due = r.responseDeadLine ? String(r.responseDeadLine).slice(0, 10) : null;
80
+ if (r.active === 'No' || (due && due < today())) return null;
81
+ const s = {
82
+ source: 'sam',
83
+ ext_id: r.noticeId,
84
+ number: r.solicitationNumber || null,
85
+ title: String(r.title || '').trim(),
86
+ agency: r.fullParentPathName ? r.fullParentPathName.split('.').filter(Boolean).slice(0, 1).concat(r.fullParentPathName.split('.').slice(-1)).join(' / ') : null,
87
+ level: 'federal',
88
+ region: 'US',
89
+ url: r.uiLink || noticeUrl(r.noticeId),
90
+ notice_type: r.type || null,
91
+ posted_at: r.postedDate || null,
92
+ due_at: r.responseDeadLine || null,
93
+ naics: r.naicsCode || null,
94
+ set_aside: r.typeOfSetAsideDescription || null,
95
+ contacts: (r.pointOfContact || []).map((c) => ({ name: c.fullName, email: c.email, phone: c.phone, role: c.type })),
96
+ description: '',
97
+ };
98
+ s.prefilter = prefilter(s);
99
+ return s.title ? s : null;
100
+ }
101
+
102
+ /** One ingest pass. Returns solicitations (deduped by id). */
103
+ export async function ingest({ fetcher = http(), queries = QUERIES, size = 25, apiKey = process.env.SAM_API_KEY } = {}) {
104
+ const out = new Map();
105
+ if (apiKey) {
106
+ const fmt = (d) => `${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}/${d.getFullYear()}`;
107
+ const to = new Date();
108
+ const from = new Date(Date.now() - 30 * 86400_000);
109
+ for (const ncode of ['541511', '541512', '541513', '541519', '518210']) {
110
+ const u = new URL('https://api.sam.gov/opportunities/v2/search');
111
+ Object.entries({ api_key: apiKey, postedFrom: fmt(from), postedTo: fmt(to), ncode, limit: '200' }).forEach(([k, v]) => u.searchParams.set(k, v));
112
+ const doc = await fetcher.json(u.toString(), ACCEPT);
113
+ for (const r of doc.opportunitiesData || []) {
114
+ const s = fromApi(r);
115
+ if (s) out.set(s.ext_id, s);
116
+ }
117
+ }
118
+ return [...out.values()];
119
+ }
120
+ for (const q of queries) {
121
+ const u = new URL(SEARCH);
122
+ Object.entries({ index: 'opp', page: '0', size: String(size), mode: 'search', is_active: 'true', sort: '-modifiedDate', q }).forEach(([k, v]) => u.searchParams.set(k, v));
123
+ const doc = await fetcher.json(u.toString(), ACCEPT);
124
+ for (const r of doc?._embedded?.results || []) {
125
+ const s = fromSearch(r);
126
+ if (s && !out.has(s.ext_id)) out.set(s.ext_id, s);
127
+ }
128
+ }
129
+ return [...out.values()];
130
+ }
131
+
132
+ /**
133
+ * Read a notice in full: its description, NAICS, set-aside and contacts, and the
134
+ * text of up to `maxFiles` public PDF/text attachments.
135
+ */
136
+ export async function readDocs(sol, { fetcher = http(), maxFiles = 3 } = {}) {
137
+ const docs = [];
138
+ const fields = {};
139
+ try {
140
+ const d = await fetcher.json(DETAIL(sol.ext_id), ACCEPT);
141
+ const body = Array.isArray(d.description) ? d.description.map((x) => x?.body || '').join('\n') : String(d.description || '');
142
+ const text = htmlToText(body);
143
+ if (text) docs.push({ kind: 'notice', name: 'Notice description', url: sol.url, text: text.slice(0, 60_000), bytes: text.length });
144
+ const n = d.data2?.naics?.[0]?.code?.[0];
145
+ if (n) fields.naics = String(n);
146
+ if (d.data2?.solicitation?.setAside) fields.set_aside = String(d.data2.solicitation.setAside);
147
+ const poc = d.data2?.pointOfContact;
148
+ if (Array.isArray(poc) && poc.length) fields.contacts = poc.map((c) => ({ name: c.fullName, email: c.email, phone: c.phone, role: c.type }));
149
+ } catch (e) {
150
+ docs.push({ kind: 'notice', name: 'Notice description', url: sol.url, error: String(e?.message || e).slice(0, 300) });
151
+ }
152
+ try {
153
+ const r = await fetcher.json(RESOURCES(sol.ext_id), ACCEPT);
154
+ const files = (r?._embedded?.opportunityAttachmentList || []).flatMap((l) => l.attachments || []).filter((a) => a.accessLevel === 'public');
155
+ for (const a of files.filter((x) => x.type === 'link').slice(0, 5)) docs.push({ kind: 'link', name: a.name || 'Link', url: a.uri });
156
+ let read = 0;
157
+ for (const a of files.filter((x) => x.type === 'file')) {
158
+ const name = a.name || 'attachment';
159
+ const doc = { kind: 'file', name, url: FILE(a.resourceId), bytes: a.size || null };
160
+ if (read >= maxFiles || !/\.(pdf|txt)$/i.test(name) || (a.size && a.size > 4_000_000)) {
161
+ docs.push(doc);
162
+ continue;
163
+ }
164
+ read++;
165
+ try {
166
+ const f = await fetchBytes(doc.url);
167
+ doc.text = /\.txt$/i.test(name) ? f.bytes.toString('utf8').slice(0, 60_000) : await pdfText(f.bytes);
168
+ doc.bytes = f.bytes.length;
169
+ } catch (e) {
170
+ doc.error = String(e?.message || e).slice(0, 300);
171
+ }
172
+ docs.push(doc);
173
+ }
174
+ } catch (e) {
175
+ docs.push({ kind: 'link', name: 'Attachments', url: sol.url, error: String(e?.message || e).slice(0, 300) });
176
+ }
177
+ return { docs, fields };
178
+ }
package/src/store.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * State: one SQLite file (node:sqlite). Solicitations, the documents read for
3
+ * them, fit scores, proposal drafts, the human intervention queue, CoinPay
4
+ * accounts and sessions. On c0mpute Apps it lives in /data, which is
5
+ * snapshotted and restored on redeploy or failover.
6
+ */
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
9
+ import { mkdirSync } from 'node:fs';
10
+ import { dirname } from 'node:path';
11
+
12
+ let db;
13
+
14
+ export function openDb(path = process.env.DB_PATH || './data/gov-contracts.db') {
15
+ if (db) return db;
16
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
17
+ db = new DatabaseSync(path);
18
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
19
+ db.exec(`
20
+ CREATE TABLE IF NOT EXISTS solicitations (
21
+ id TEXT PRIMARY KEY, -- <source>:<external id>
22
+ source TEXT NOT NULL,
23
+ ext_id TEXT NOT NULL,
24
+ number TEXT,
25
+ title TEXT NOT NULL,
26
+ agency TEXT,
27
+ level TEXT, -- federal | state | county | city
28
+ region TEXT,
29
+ url TEXT,
30
+ notice_type TEXT,
31
+ posted_at TEXT,
32
+ due_at TEXT, -- ISO date or datetime
33
+ naics TEXT,
34
+ set_aside TEXT,
35
+ description TEXT,
36
+ contacts TEXT, -- JSON array
37
+ prefilter INTEGER NOT NULL DEFAULT 0,
38
+ status TEXT NOT NULL DEFAULT 'new', -- new | read | scored | drafted | skipped | closed | error
39
+ fit_score INTEGER,
40
+ fit TEXT, -- JSON from the fit step
41
+ error TEXT,
42
+ first_seen TEXT NOT NULL,
43
+ updated_at TEXT NOT NULL
44
+ );
45
+ CREATE INDEX IF NOT EXISTS sol_status ON solicitations(status);
46
+ CREATE INDEX IF NOT EXISTS sol_due ON solicitations(due_at);
47
+ CREATE INDEX IF NOT EXISTS sol_fit ON solicitations(fit_score);
48
+
49
+ CREATE TABLE IF NOT EXISTS documents (
50
+ id TEXT PRIMARY KEY,
51
+ solicitation_id TEXT NOT NULL REFERENCES solicitations(id) ON DELETE CASCADE,
52
+ name TEXT,
53
+ url TEXT,
54
+ kind TEXT, -- notice | file | link
55
+ bytes INTEGER,
56
+ text TEXT,
57
+ error TEXT,
58
+ fetched_at TEXT NOT NULL
59
+ );
60
+ CREATE INDEX IF NOT EXISTS doc_sol ON documents(solicitation_id);
61
+
62
+ CREATE TABLE IF NOT EXISTS proposals (
63
+ id TEXT PRIMARY KEY,
64
+ solicitation_id TEXT NOT NULL REFERENCES solicitations(id) ON DELETE CASCADE,
65
+ version INTEGER NOT NULL,
66
+ status TEXT NOT NULL DEFAULT 'draft',
67
+ body TEXT NOT NULL, -- JSON: cover_letter, technical_approach, pricing, forms, compliance, questions
68
+ markdown TEXT NOT NULL,
69
+ provider TEXT,
70
+ model TEXT,
71
+ created_at TEXT NOT NULL,
72
+ UNIQUE (solicitation_id, version)
73
+ );
74
+
75
+ CREATE TABLE IF NOT EXISTS interventions (
76
+ id TEXT PRIMARY KEY,
77
+ key TEXT NOT NULL UNIQUE, -- dedupe: kind + subject
78
+ kind TEXT NOT NULL, -- submit_proposal | register_vendor | sign_or_certify | set_price | decide_bid | configure_source
79
+ solicitation_id TEXT REFERENCES solicitations(id) ON DELETE CASCADE,
80
+ proposal_id TEXT,
81
+ title TEXT NOT NULL,
82
+ body TEXT NOT NULL, -- markdown: why + numbered steps
83
+ open_url TEXT,
84
+ copy_text TEXT,
85
+ priority INTEGER NOT NULL DEFAULT 50,
86
+ due_at TEXT,
87
+ status TEXT NOT NULL DEFAULT 'open', -- open | done | dismissed
88
+ note TEXT,
89
+ resolved_by TEXT,
90
+ resolved_at TEXT,
91
+ created_at TEXT NOT NULL
92
+ );
93
+ CREATE INDEX IF NOT EXISTS iv_status ON interventions(status, priority);
94
+
95
+ CREATE TABLE IF NOT EXISTS accounts (
96
+ id TEXT PRIMARY KEY,
97
+ coinpay_sub TEXT NOT NULL UNIQUE,
98
+ name TEXT,
99
+ created_at TEXT NOT NULL
100
+ );
101
+ CREATE TABLE IF NOT EXISTS sessions (
102
+ hash TEXT PRIMARY KEY,
103
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
104
+ created_at TEXT NOT NULL
105
+ );
106
+ CREATE TABLE IF NOT EXISTS runs (
107
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
108
+ job TEXT NOT NULL,
109
+ ok INTEGER NOT NULL,
110
+ detail TEXT,
111
+ at TEXT NOT NULL
112
+ );
113
+ `);
114
+ return db;
115
+ }
116
+
117
+ export const now = () => new Date().toISOString();
118
+ const j = (v) => (v == null ? null : JSON.stringify(v));
119
+ const pj = (v, d = null) => {
120
+ if (v == null) return d;
121
+ try { return JSON.parse(v); } catch { return d; }
122
+ };
123
+ const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
124
+
125
+ /* ------------------------------------------------------------ solicitations -- */
126
+
127
+ function solRow(r) {
128
+ if (!r) return null;
129
+ return { ...r, contacts: pj(r.contacts, []), fit: pj(r.fit) };
130
+ }
131
+
132
+ /**
133
+ * Insert or refresh a solicitation. Returns 'new', 'updated' or 'same'.
134
+ * A refresh keeps the pipeline state (status, fit) unless the notice changed
135
+ * its due date or description, which sends it back to be read again.
136
+ */
137
+ export function upsertSolicitation(s) {
138
+ const d = openDb();
139
+ const id = `${s.source}:${s.ext_id}`;
140
+ const prev = d.prepare('SELECT * FROM solicitations WHERE id = ?').get(id);
141
+ const t = now();
142
+ if (!prev) {
143
+ d.prepare(`INSERT INTO solicitations (id, source, ext_id, number, title, agency, level, region, url, notice_type, posted_at, due_at, naics, set_aside, description, contacts, prefilter, status, first_seen, updated_at)
144
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
145
+ id, s.source, String(s.ext_id), s.number ?? null, s.title, s.agency ?? null, s.level ?? null, s.region ?? null, s.url ?? null,
146
+ s.notice_type ?? null, s.posted_at ?? null, s.due_at ?? null, s.naics ?? null, s.set_aside ?? null, s.description ?? null,
147
+ j(s.contacts || []), s.prefilter ?? 0, s.prefilter > 0 ? 'new' : 'skipped', t, t,
148
+ );
149
+ return 'new';
150
+ }
151
+ const changed = (s.due_at ?? null) !== prev.due_at || ((s.description ?? null) !== null && s.description !== prev.description);
152
+ if (!changed && prev.title === s.title) return 'same';
153
+ d.prepare(`UPDATE solicitations SET number = ?, title = ?, agency = ?, url = ?, notice_type = ?, due_at = ?, naics = COALESCE(?, naics), set_aside = COALESCE(?, set_aside),
154
+ description = COALESCE(?, description), contacts = ?, prefilter = ?, updated_at = ? WHERE id = ?`).run(
155
+ s.number ?? prev.number, s.title, s.agency ?? prev.agency, s.url ?? prev.url, s.notice_type ?? prev.notice_type, s.due_at ?? prev.due_at,
156
+ s.naics ?? null, s.set_aside ?? null, s.description ?? null, j(s.contacts || pj(prev.contacts, [])), s.prefilter ?? prev.prefilter, t, id,
157
+ );
158
+ return 'updated';
159
+ }
160
+
161
+ /** Normalized title, for matching the same bid seen in two sources. */
162
+ export const titleKey = (t) => String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
163
+
164
+ /** An open solicitation from a feed (not a digest) with the same title, if any. */
165
+ export function findFeedTwin(title) {
166
+ const k = titleKey(title);
167
+ if (!k) return null;
168
+ const rows = openDb().prepare("SELECT id, title FROM solicitations WHERE source != 'digest' AND (due_at IS NULL OR due_at >= ?)").all(now().slice(0, 10));
169
+ return rows.find((r) => titleKey(r.title) === k) || null;
170
+ }
171
+
172
+ export function getSolicitation(id) {
173
+ return solRow(openDb().prepare('SELECT * FROM solicitations WHERE id = ?').get(id));
174
+ }
175
+
176
+ export function setSolicitation(id, fields) {
177
+ const keys = Object.keys(fields);
178
+ if (!keys.length) return;
179
+ const vals = keys.map((k) => (k === 'fit' || k === 'contacts' ? j(fields[k]) : fields[k]));
180
+ openDb().prepare(`UPDATE solicitations SET ${keys.map((k) => `${k} = ?`).join(', ')}, updated_at = ? WHERE id = ?`).run(...vals, now(), id);
181
+ }
182
+
183
+ /** Open = not past due (or no due date). `q` matches title, agency, number and description. */
184
+ export function searchSolicitations({ q, status, level, source, minFit, open = true, limit = 50, offset = 0, order = 'fit' } = {}) {
185
+ const where = [];
186
+ const args = [];
187
+ if (q) {
188
+ where.push('(title LIKE ? OR agency LIKE ? OR number LIKE ? OR description LIKE ?)');
189
+ const like = `%${String(q).slice(0, 100)}%`;
190
+ args.push(like, like, like, like);
191
+ }
192
+ if (status) { where.push('status = ?'); args.push(status); }
193
+ if (level) { where.push('level = ?'); args.push(level); }
194
+ if (source) { where.push('source = ?'); args.push(source); }
195
+ if (minFit != null) { where.push('fit_score >= ?'); args.push(Number(minFit)); }
196
+ if (open) { where.push("(due_at IS NULL OR due_at >= ?)"); args.push(now().slice(0, 10)); }
197
+ const ord = order === 'due' ? 'due_at IS NULL, due_at ASC' : order === 'new' ? 'first_seen DESC' : 'fit_score IS NULL, fit_score DESC, prefilter DESC, due_at ASC';
198
+ const sql = `SELECT id, source, number, title, agency, level, region, url, notice_type, due_at, naics, set_aside, prefilter, status, fit_score, fit, first_seen
199
+ FROM solicitations ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY ${ord} LIMIT ? OFFSET ?`;
200
+ const rows = openDb().prepare(sql).all(...args, Math.min(Number(limit) || 50, 200), Math.max(0, Number(offset) || 0));
201
+ return rows.map(solRow);
202
+ }
203
+
204
+ /** Next items for a pipeline step, soonest due first. */
205
+ export function dueFor(status, limit = 5) {
206
+ return openDb().prepare(`SELECT * FROM solicitations WHERE status = ? AND (due_at IS NULL OR due_at >= ?)
207
+ ORDER BY prefilter DESC, due_at IS NULL, due_at ASC LIMIT ?`).all(status, now().slice(0, 10), limit).map(solRow);
208
+ }
209
+
210
+ export function stats() {
211
+ const d = openDb();
212
+ const today = now().slice(0, 10);
213
+ const by = (col) => Object.fromEntries(d.prepare(`SELECT ${col} AS k, COUNT(*) AS n FROM solicitations WHERE due_at IS NULL OR due_at >= ? GROUP BY ${col}`).all(today).map((r) => [r.k ?? 'unknown', r.n]));
214
+ return {
215
+ open_solicitations: d.prepare('SELECT COUNT(*) AS n FROM solicitations WHERE due_at IS NULL OR due_at >= ?').get(today).n,
216
+ total_seen: d.prepare('SELECT COUNT(*) AS n FROM solicitations').get().n,
217
+ by_status: by('status'),
218
+ by_source: by('source'),
219
+ by_level: by('level'),
220
+ drafts: d.prepare('SELECT COUNT(*) AS n FROM proposals').get().n,
221
+ interventions_open: d.prepare("SELECT COUNT(*) AS n FROM interventions WHERE status = 'open'").get().n,
222
+ last_runs: d.prepare('SELECT job, ok, detail, at FROM runs WHERE id IN (SELECT MAX(id) FROM runs GROUP BY job) ORDER BY job').all().map((r) => ({ ...r, ok: !!r.ok, detail: pj(r.detail, r.detail) })),
223
+ };
224
+ }
225
+
226
+ export function logRun(job, ok, detail) {
227
+ const d = openDb();
228
+ d.prepare('INSERT INTO runs (job, ok, detail, at) VALUES (?,?,?,?)').run(job, ok ? 1 : 0, j(detail), now());
229
+ d.prepare('DELETE FROM runs WHERE id NOT IN (SELECT id FROM runs ORDER BY id DESC LIMIT 2000)').run();
230
+ }
231
+
232
+ /* ---------------------------------------------------------------- documents -- */
233
+
234
+ export function saveDocument(solicitationId, doc) {
235
+ const id = sha(`${solicitationId}|${doc.kind || 'file'}|${doc.name || ''}|${doc.url || ''}`).slice(0, 24);
236
+ openDb().prepare(`INSERT INTO documents (id, solicitation_id, name, url, kind, bytes, text, error, fetched_at) VALUES (?,?,?,?,?,?,?,?,?)
237
+ ON CONFLICT (id) DO UPDATE SET name = excluded.name, kind = excluded.kind, bytes = excluded.bytes, text = excluded.text, error = excluded.error, fetched_at = excluded.fetched_at`).run(
238
+ id, solicitationId, doc.name ?? null, doc.url ?? null, doc.kind ?? 'file', doc.bytes ?? null, doc.text ?? null, doc.error ?? null, now(),
239
+ );
240
+ return id;
241
+ }
242
+
243
+ export function documentsFor(solicitationId, { withText = true } = {}) {
244
+ const cols = withText ? '*' : 'id, solicitation_id, name, url, kind, bytes, error, fetched_at, length(text) AS text_chars';
245
+ return openDb().prepare(`SELECT ${cols} FROM documents WHERE solicitation_id = ? ORDER BY kind = 'notice' DESC, fetched_at`).all(solicitationId);
246
+ }
247
+
248
+ /* ---------------------------------------------------------------- proposals -- */
249
+
250
+ export function saveProposal(solicitationId, { body, markdown, provider, model }) {
251
+ const d = openDb();
252
+ const version = (d.prepare('SELECT MAX(version) AS v FROM proposals WHERE solicitation_id = ?').get(solicitationId).v || 0) + 1;
253
+ const id = randomUUID();
254
+ d.prepare('INSERT INTO proposals (id, solicitation_id, version, status, body, markdown, provider, model, created_at) VALUES (?,?,?,?,?,?,?,?,?)')
255
+ .run(id, solicitationId, version, 'draft', j(body), markdown, provider ?? null, model ?? null, now());
256
+ return { id, version };
257
+ }
258
+
259
+ const propRow = (r) => (r ? { ...r, body: pj(r.body, {}) } : null);
260
+ export function getProposal(id) {
261
+ return propRow(openDb().prepare('SELECT * FROM proposals WHERE id = ?').get(id));
262
+ }
263
+ export function latestProposal(solicitationId) {
264
+ return propRow(openDb().prepare('SELECT * FROM proposals WHERE solicitation_id = ? ORDER BY version DESC LIMIT 1').get(solicitationId));
265
+ }
266
+ export function setProposalStatus(id, status) {
267
+ openDb().prepare('UPDATE proposals SET status = ? WHERE id = ?').run(status, id);
268
+ }
269
+
270
+ /* ------------------------------------------------------------ interventions -- */
271
+
272
+ /** Queue a card once per key. A card that was dismissed stays dismissed. */
273
+ export function queueIntervention(iv) {
274
+ const d = openDb();
275
+ const existing = d.prepare('SELECT id, status FROM interventions WHERE key = ?').get(iv.key);
276
+ if (existing) {
277
+ if (existing.status === 'open') {
278
+ d.prepare('UPDATE interventions SET title = ?, body = ?, open_url = ?, copy_text = ?, proposal_id = COALESCE(?, proposal_id), priority = ?, due_at = ? WHERE id = ?')
279
+ .run(iv.title, iv.body, iv.open_url ?? null, iv.copy_text ?? null, iv.proposal_id ?? null, iv.priority ?? 50, iv.due_at ?? null, existing.id);
280
+ }
281
+ return { id: existing.id, created: false };
282
+ }
283
+ const id = randomUUID();
284
+ d.prepare(`INSERT INTO interventions (id, key, kind, solicitation_id, proposal_id, title, body, open_url, copy_text, priority, due_at, status, created_at)
285
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,'open',?)`).run(
286
+ id, iv.key, iv.kind, iv.solicitation_id ?? null, iv.proposal_id ?? null, iv.title, iv.body, iv.open_url ?? null, iv.copy_text ?? null,
287
+ iv.priority ?? 50, iv.due_at ?? null, now(),
288
+ );
289
+ return { id, created: true };
290
+ }
291
+
292
+ export function listInterventions({ status = 'open', kind, limit = 100 } = {}) {
293
+ const where = [];
294
+ const args = [];
295
+ if (status && status !== 'all') { where.push('i.status = ?'); args.push(status); }
296
+ if (kind) { where.push('i.kind = ?'); args.push(kind); }
297
+ return openDb().prepare(`SELECT i.*, s.title AS solicitation_title, s.agency, s.number, s.fit_score
298
+ FROM interventions i LEFT JOIN solicitations s ON s.id = i.solicitation_id
299
+ ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
300
+ ORDER BY i.status = 'open' DESC, i.priority DESC, i.due_at IS NULL, i.due_at ASC, i.created_at ASC LIMIT ?`).all(...args, Math.min(Number(limit) || 100, 500));
301
+ }
302
+
303
+ export function getIntervention(id) {
304
+ return openDb().prepare(`SELECT i.*, s.title AS solicitation_title, s.agency, s.number, s.fit_score, s.url AS solicitation_url
305
+ FROM interventions i LEFT JOIN solicitations s ON s.id = i.solicitation_id WHERE i.id = ?`).get(id) || null;
306
+ }
307
+
308
+ /**
309
+ * A person resolves a card. Marking a submit card done records that THEY
310
+ * submitted it (status submitted_by_human); the system never submits.
311
+ */
312
+ export function resolveIntervention(id, { status, note, by }) {
313
+ if (!['done', 'dismissed', 'open'].includes(status)) throw new Error('status must be done, dismissed or open');
314
+ const d = openDb();
315
+ const iv = d.prepare('SELECT * FROM interventions WHERE id = ?').get(id);
316
+ if (!iv) return null;
317
+ d.prepare('UPDATE interventions SET status = ?, note = ?, resolved_by = ?, resolved_at = ? WHERE id = ?')
318
+ .run(status, note ? String(note).slice(0, 2000) : null, status === 'open' ? null : by ?? null, status === 'open' ? null : now(), id);
319
+ if (iv.proposal_id && iv.kind === 'submit_proposal') {
320
+ setProposalStatus(iv.proposal_id, status === 'done' ? 'submitted_by_human' : status === 'dismissed' ? 'declined' : 'draft');
321
+ }
322
+ return getIntervention(id);
323
+ }
324
+
325
+ /* ---------------------------------------------------- accounts and sessions -- */
326
+
327
+ export function accountBySub(sub) {
328
+ return openDb().prepare('SELECT * FROM accounts WHERE coinpay_sub = ?').get(String(sub)) || null;
329
+ }
330
+ export function createAccount(sub, name) {
331
+ const id = randomUUID();
332
+ openDb().prepare('INSERT INTO accounts (id, coinpay_sub, name, created_at) VALUES (?,?,?,?)').run(id, String(sub), name ?? null, now());
333
+ return accountBySub(sub);
334
+ }
335
+ export function createSession(accountId) {
336
+ const token = randomBytes(32).toString('base64url');
337
+ openDb().prepare('INSERT INTO sessions (hash, account_id, created_at) VALUES (?,?,?)').run(sha(token), accountId, now());
338
+ return token;
339
+ }
340
+ export function accountBySession(token) {
341
+ if (!token) return null;
342
+ return openDb().prepare('SELECT a.* FROM sessions s JOIN accounts a ON a.id = s.account_id WHERE s.hash = ?').get(sha(token)) || null;
343
+ }
344
+ export function deleteSession(token) {
345
+ if (token) openDb().prepare('DELETE FROM sessions WHERE hash = ?').run(sha(token));
346
+ }
347
+
348
+ /** For tests. */
349
+ export function _reset() {
350
+ const d = openDb();
351
+ for (const t of ['interventions', 'proposals', 'documents', 'solicitations', 'sessions', 'accounts', 'runs']) d.exec(`DELETE FROM ${t}`);
352
+ }
package/src/version.js ADDED
@@ -0,0 +1,3 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;