@profullstack/gov-contracts 0.0.0-stage → 0.2.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.
- package/LICENSE +9 -0
- package/README.md +78 -2
- package/bin/gov-contracts.js +225 -0
- package/package.json +50 -4
- package/src/ai.js +46 -0
- package/src/app.js +337 -0
- package/src/auth.js +109 -0
- package/src/fit.js +127 -0
- package/src/http.js +86 -0
- package/src/index.js +12 -0
- package/src/mcp.js +159 -0
- package/src/niche.js +196 -0
- package/src/pages.js +380 -0
- package/src/pipeline.js +141 -0
- package/src/profile.js +308 -0
- package/src/propose.js +260 -0
- package/src/safety.js +48 -0
- package/src/server.js +17 -0
- package/src/service.js +27 -0
- package/src/sources/digest.js +119 -0
- package/src/sources/index.js +59 -0
- package/src/sources/lacounty.js +100 -0
- package/src/sources/sam.js +178 -0
- package/src/spider.js +218 -0
- package/src/store.js +390 -0
- package/src/version.js +3 -0
package/src/store.js
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
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
|
+
import { nicheMatch } from './niche.js';
|
|
12
|
+
|
|
13
|
+
let db;
|
|
14
|
+
|
|
15
|
+
export function openDb(path = process.env.DB_PATH || './data/gov-contracts.db') {
|
|
16
|
+
if (db) return db;
|
|
17
|
+
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
|
|
18
|
+
db = new DatabaseSync(path);
|
|
19
|
+
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
|
|
20
|
+
db.exec(`
|
|
21
|
+
CREATE TABLE IF NOT EXISTS solicitations (
|
|
22
|
+
id TEXT PRIMARY KEY, -- <source>:<external id>
|
|
23
|
+
source TEXT NOT NULL,
|
|
24
|
+
ext_id TEXT NOT NULL,
|
|
25
|
+
number TEXT,
|
|
26
|
+
title TEXT NOT NULL,
|
|
27
|
+
agency TEXT,
|
|
28
|
+
level TEXT, -- federal | state | county | city
|
|
29
|
+
region TEXT,
|
|
30
|
+
url TEXT,
|
|
31
|
+
notice_type TEXT,
|
|
32
|
+
posted_at TEXT,
|
|
33
|
+
due_at TEXT, -- ISO date or datetime
|
|
34
|
+
naics TEXT,
|
|
35
|
+
set_aside TEXT,
|
|
36
|
+
description TEXT,
|
|
37
|
+
contacts TEXT, -- JSON array
|
|
38
|
+
prefilter INTEGER NOT NULL DEFAULT 0,
|
|
39
|
+
status TEXT NOT NULL DEFAULT 'new', -- new | read | scored | drafted | skipped | closed | error
|
|
40
|
+
fit_score INTEGER,
|
|
41
|
+
fit TEXT, -- JSON from the fit step
|
|
42
|
+
error TEXT,
|
|
43
|
+
first_seen TEXT NOT NULL,
|
|
44
|
+
updated_at TEXT NOT NULL
|
|
45
|
+
);
|
|
46
|
+
CREATE INDEX IF NOT EXISTS sol_status ON solicitations(status);
|
|
47
|
+
CREATE INDEX IF NOT EXISTS sol_due ON solicitations(due_at);
|
|
48
|
+
CREATE INDEX IF NOT EXISTS sol_fit ON solicitations(fit_score);
|
|
49
|
+
|
|
50
|
+
CREATE TABLE IF NOT EXISTS documents (
|
|
51
|
+
id TEXT PRIMARY KEY,
|
|
52
|
+
solicitation_id TEXT NOT NULL REFERENCES solicitations(id) ON DELETE CASCADE,
|
|
53
|
+
name TEXT,
|
|
54
|
+
url TEXT,
|
|
55
|
+
kind TEXT, -- notice | file | link
|
|
56
|
+
bytes INTEGER,
|
|
57
|
+
text TEXT,
|
|
58
|
+
error TEXT,
|
|
59
|
+
fetched_at TEXT NOT NULL
|
|
60
|
+
);
|
|
61
|
+
CREATE INDEX IF NOT EXISTS doc_sol ON documents(solicitation_id);
|
|
62
|
+
|
|
63
|
+
CREATE TABLE IF NOT EXISTS proposals (
|
|
64
|
+
id TEXT PRIMARY KEY,
|
|
65
|
+
solicitation_id TEXT NOT NULL REFERENCES solicitations(id) ON DELETE CASCADE,
|
|
66
|
+
version INTEGER NOT NULL,
|
|
67
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
68
|
+
body TEXT NOT NULL, -- JSON: cover_letter, technical_approach, pricing, forms, compliance, questions
|
|
69
|
+
markdown TEXT NOT NULL,
|
|
70
|
+
provider TEXT,
|
|
71
|
+
model TEXT,
|
|
72
|
+
created_at TEXT NOT NULL,
|
|
73
|
+
UNIQUE (solicitation_id, version)
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
CREATE TABLE IF NOT EXISTS interventions (
|
|
77
|
+
id TEXT PRIMARY KEY,
|
|
78
|
+
key TEXT NOT NULL UNIQUE, -- dedupe: kind + subject
|
|
79
|
+
kind TEXT NOT NULL, -- submit_proposal | register_vendor | sign_or_certify | set_price | decide_bid | configure_source
|
|
80
|
+
solicitation_id TEXT REFERENCES solicitations(id) ON DELETE CASCADE,
|
|
81
|
+
proposal_id TEXT,
|
|
82
|
+
title TEXT NOT NULL,
|
|
83
|
+
body TEXT NOT NULL, -- markdown: why + numbered steps
|
|
84
|
+
open_url TEXT,
|
|
85
|
+
copy_text TEXT,
|
|
86
|
+
priority INTEGER NOT NULL DEFAULT 50,
|
|
87
|
+
due_at TEXT,
|
|
88
|
+
status TEXT NOT NULL DEFAULT 'open', -- open | done | dismissed
|
|
89
|
+
note TEXT,
|
|
90
|
+
resolved_by TEXT,
|
|
91
|
+
resolved_at TEXT,
|
|
92
|
+
created_at TEXT NOT NULL
|
|
93
|
+
);
|
|
94
|
+
CREATE INDEX IF NOT EXISTS iv_status ON interventions(status, priority);
|
|
95
|
+
|
|
96
|
+
CREATE TABLE IF NOT EXISTS accounts (
|
|
97
|
+
id TEXT PRIMARY KEY,
|
|
98
|
+
coinpay_sub TEXT NOT NULL UNIQUE,
|
|
99
|
+
name TEXT,
|
|
100
|
+
created_at TEXT NOT NULL
|
|
101
|
+
);
|
|
102
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
103
|
+
hash TEXT PRIMARY KEY,
|
|
104
|
+
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
|
105
|
+
created_at TEXT NOT NULL
|
|
106
|
+
);
|
|
107
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
108
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
109
|
+
job TEXT NOT NULL,
|
|
110
|
+
ok INTEGER NOT NULL,
|
|
111
|
+
detail TEXT,
|
|
112
|
+
at TEXT NOT NULL
|
|
113
|
+
);
|
|
114
|
+
`);
|
|
115
|
+
// 0.2.0: niche match per solicitation (niche.js), refreshed when the profile changes.
|
|
116
|
+
const cols = new Set(db.prepare('PRAGMA table_info(solicitations)').all().map((c) => c.name));
|
|
117
|
+
if (!cols.has('niche_score')) db.exec('ALTER TABLE solicitations ADD COLUMN niche_score INTEGER');
|
|
118
|
+
if (!cols.has('niches')) db.exec("ALTER TABLE solicitations ADD COLUMN niches TEXT");
|
|
119
|
+
db.exec('CREATE INDEX IF NOT EXISTS sol_niche ON solicitations(niche_score)');
|
|
120
|
+
return db;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const now = () => new Date().toISOString();
|
|
124
|
+
const j = (v) => (v == null ? null : JSON.stringify(v));
|
|
125
|
+
const pj = (v, d = null) => {
|
|
126
|
+
if (v == null) return d;
|
|
127
|
+
try { return JSON.parse(v); } catch { return d; }
|
|
128
|
+
};
|
|
129
|
+
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
|
|
130
|
+
|
|
131
|
+
/* ------------------------------------------------------------ solicitations -- */
|
|
132
|
+
|
|
133
|
+
function solRow(r) {
|
|
134
|
+
if (!r) return null;
|
|
135
|
+
return { ...r, contacts: pj(r.contacts, []), fit: pj(r.fit), ...(r.niches !== undefined ? { niches: pj(r.niches, []) } : {}) };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Insert or refresh a solicitation. Returns 'new', 'updated' or 'same'.
|
|
140
|
+
* A refresh keeps the pipeline state (status, fit) unless the notice changed
|
|
141
|
+
* its due date or description, which sends it back to be read again.
|
|
142
|
+
*/
|
|
143
|
+
export function upsertSolicitation(s) {
|
|
144
|
+
const d = openDb();
|
|
145
|
+
const id = `${s.source}:${s.ext_id}`;
|
|
146
|
+
const prev = d.prepare('SELECT * FROM solicitations WHERE id = ?').get(id);
|
|
147
|
+
const t = now();
|
|
148
|
+
const m = nicheMatch({ title: s.title, description: s.description ?? prev?.description, naics: s.naics ?? prev?.naics });
|
|
149
|
+
if (!prev) {
|
|
150
|
+
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, niche_score, niches, status, first_seen, updated_at)
|
|
151
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
|
|
152
|
+
id, s.source, String(s.ext_id), s.number ?? null, s.title, s.agency ?? null, s.level ?? null, s.region ?? null, s.url ?? null,
|
|
153
|
+
s.notice_type ?? null, s.posted_at ?? null, s.due_at ?? null, s.naics ?? null, s.set_aside ?? null, s.description ?? null,
|
|
154
|
+
j(s.contacts || []), s.prefilter ?? m.score, m.score, j(m.niches), (s.prefilter ?? m.score) > 0 ? 'new' : 'skipped', t, t,
|
|
155
|
+
);
|
|
156
|
+
return 'new';
|
|
157
|
+
}
|
|
158
|
+
const changed = (s.due_at ?? null) !== prev.due_at || ((s.description ?? null) !== null && s.description !== prev.description);
|
|
159
|
+
if (!changed && prev.title === s.title) {
|
|
160
|
+
if (prev.niche_score == null) d.prepare('UPDATE solicitations SET niche_score = ?, niches = ? WHERE id = ?').run(m.score, j(m.niches), id);
|
|
161
|
+
return 'same';
|
|
162
|
+
}
|
|
163
|
+
d.prepare(`UPDATE solicitations SET number = ?, title = ?, agency = ?, url = ?, notice_type = ?, due_at = ?, naics = COALESCE(?, naics), set_aside = COALESCE(?, set_aside),
|
|
164
|
+
description = COALESCE(?, description), contacts = ?, prefilter = ?, niche_score = ?, niches = ?, updated_at = ? WHERE id = ?`).run(
|
|
165
|
+
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,
|
|
166
|
+
s.naics ?? null, s.set_aside ?? null, s.description ?? null, j(s.contacts || pj(prev.contacts, [])), s.prefilter ?? prev.prefilter, m.score, j(m.niches), t, id,
|
|
167
|
+
);
|
|
168
|
+
return 'updated';
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Normalized title, for matching the same bid seen in two sources. */
|
|
172
|
+
export const titleKey = (t) => String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
173
|
+
|
|
174
|
+
/** An open solicitation from a feed (not a digest) with the same title, if any. */
|
|
175
|
+
export function findFeedTwin(title) {
|
|
176
|
+
const k = titleKey(title);
|
|
177
|
+
if (!k) return null;
|
|
178
|
+
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));
|
|
179
|
+
return rows.find((r) => titleKey(r.title) === k) || null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function getSolicitation(id) {
|
|
183
|
+
return solRow(openDb().prepare('SELECT * FROM solicitations WHERE id = ?').get(id));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function setSolicitation(id, fields) {
|
|
187
|
+
const keys = Object.keys(fields);
|
|
188
|
+
if (!keys.length) return;
|
|
189
|
+
const vals = keys.map((k) => (k === 'fit' || k === 'contacts' ? j(fields[k]) : fields[k]));
|
|
190
|
+
openDb().prepare(`UPDATE solicitations SET ${keys.map((k) => `${k} = ?`).join(', ')}, updated_at = ? WHERE id = ?`).run(...vals, now(), id);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Open = not past due (or no due date). `q` matches title, agency, number and description. */
|
|
194
|
+
/**
|
|
195
|
+
* `niche`: 'in' = any of our niches, 'out' = none, or a niche name; anything
|
|
196
|
+
* else (or 'all') = no niche filter.
|
|
197
|
+
*/
|
|
198
|
+
function nicheWhere(niche, where, args, col = '') {
|
|
199
|
+
if (!niche || niche === 'all') return;
|
|
200
|
+
if (niche === 'in') where.push(`${col}niche_score > 0`);
|
|
201
|
+
else if (niche === 'out') where.push(`COALESCE(${col}niche_score, 0) = 0`);
|
|
202
|
+
else { where.push(`EXISTS (SELECT 1 FROM json_each(${col}niches) WHERE value = ?)`); args.push(String(niche).slice(0, 80)); }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function searchSolicitations({ q, status, level, source, minFit, niche, open = true, limit = 50, offset = 0, order = 'fit' } = {}) {
|
|
206
|
+
const where = [];
|
|
207
|
+
const args = [];
|
|
208
|
+
if (q) {
|
|
209
|
+
where.push('(title LIKE ? OR agency LIKE ? OR number LIKE ? OR description LIKE ?)');
|
|
210
|
+
const like = `%${String(q).slice(0, 100)}%`;
|
|
211
|
+
args.push(like, like, like, like);
|
|
212
|
+
}
|
|
213
|
+
if (status) { where.push('status = ?'); args.push(status); }
|
|
214
|
+
if (level) { where.push('level = ?'); args.push(level); }
|
|
215
|
+
if (source) { where.push('source = ?'); args.push(source); }
|
|
216
|
+
if (minFit != null) { where.push('fit_score >= ?'); args.push(Number(minFit)); }
|
|
217
|
+
nicheWhere(niche, where, args);
|
|
218
|
+
if (open) { where.push("(due_at IS NULL OR due_at >= ?)"); args.push(now().slice(0, 10)); }
|
|
219
|
+
const ord = order === 'due' ? 'due_at IS NULL, due_at ASC' : order === 'new' ? 'first_seen DESC' : order === 'niche' ? 'niche_score DESC, due_at IS NULL, due_at ASC' : 'fit_score IS NULL, fit_score DESC, niche_score DESC, prefilter DESC, due_at ASC';
|
|
220
|
+
const sql = `SELECT id, source, number, title, agency, level, region, url, notice_type, due_at, naics, set_aside, prefilter, niche_score, niches, status, fit_score, fit, first_seen
|
|
221
|
+
FROM solicitations ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY ${ord} LIMIT ? OFFSET ?`;
|
|
222
|
+
const rows = openDb().prepare(sql).all(...args, Math.min(Number(limit) || 50, 200), Math.max(0, Number(offset) || 0));
|
|
223
|
+
return rows.map(solRow);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Next items for a pipeline step, soonest due first. */
|
|
227
|
+
export function dueFor(status, limit = 5) {
|
|
228
|
+
return openDb().prepare(`SELECT * FROM solicitations WHERE status = ? AND (due_at IS NULL OR due_at >= ?)
|
|
229
|
+
ORDER BY prefilter DESC, due_at IS NULL, due_at ASC LIMIT ?`).all(status, now().slice(0, 10), limit).map(solRow);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Open solicitations per niche name, most first. */
|
|
233
|
+
export function nicheCounts() {
|
|
234
|
+
return openDb().prepare(`SELECT value AS niche, COUNT(*) AS n FROM solicitations, json_each(solicitations.niches)
|
|
235
|
+
WHERE (due_at IS NULL OR due_at >= ?) GROUP BY value ORDER BY n DESC`).all(now().slice(0, 10));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function stats() {
|
|
239
|
+
const d = openDb();
|
|
240
|
+
const today = now().slice(0, 10);
|
|
241
|
+
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]));
|
|
242
|
+
return {
|
|
243
|
+
open_solicitations: d.prepare('SELECT COUNT(*) AS n FROM solicitations WHERE due_at IS NULL OR due_at >= ?').get(today).n,
|
|
244
|
+
total_seen: d.prepare('SELECT COUNT(*) AS n FROM solicitations').get().n,
|
|
245
|
+
by_status: by('status'),
|
|
246
|
+
by_source: by('source'),
|
|
247
|
+
by_level: by('level'),
|
|
248
|
+
in_niche: d.prepare('SELECT COUNT(*) AS n FROM solicitations WHERE niche_score > 0 AND (due_at IS NULL OR due_at >= ?)').get(today).n,
|
|
249
|
+
by_niche: Object.fromEntries(nicheCounts().map((r) => [r.niche, r.n])),
|
|
250
|
+
drafts: d.prepare('SELECT COUNT(*) AS n FROM proposals').get().n,
|
|
251
|
+
interventions_open: d.prepare("SELECT COUNT(*) AS n FROM interventions WHERE status = 'open'").get().n,
|
|
252
|
+
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) })),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function logRun(job, ok, detail) {
|
|
257
|
+
const d = openDb();
|
|
258
|
+
d.prepare('INSERT INTO runs (job, ok, detail, at) VALUES (?,?,?,?)').run(job, ok ? 1 : 0, j(detail), now());
|
|
259
|
+
d.prepare('DELETE FROM runs WHERE id NOT IN (SELECT id FROM runs ORDER BY id DESC LIMIT 2000)').run();
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/* ---------------------------------------------------------------- documents -- */
|
|
263
|
+
|
|
264
|
+
export function saveDocument(solicitationId, doc) {
|
|
265
|
+
const id = sha(`${solicitationId}|${doc.kind || 'file'}|${doc.name || ''}|${doc.url || ''}`).slice(0, 24);
|
|
266
|
+
openDb().prepare(`INSERT INTO documents (id, solicitation_id, name, url, kind, bytes, text, error, fetched_at) VALUES (?,?,?,?,?,?,?,?,?)
|
|
267
|
+
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(
|
|
268
|
+
id, solicitationId, doc.name ?? null, doc.url ?? null, doc.kind ?? 'file', doc.bytes ?? null, doc.text ?? null, doc.error ?? null, now(),
|
|
269
|
+
);
|
|
270
|
+
return id;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function documentsFor(solicitationId, { withText = true } = {}) {
|
|
274
|
+
const cols = withText ? '*' : 'id, solicitation_id, name, url, kind, bytes, error, fetched_at, length(text) AS text_chars';
|
|
275
|
+
return openDb().prepare(`SELECT ${cols} FROM documents WHERE solicitation_id = ? ORDER BY kind = 'notice' DESC, fetched_at`).all(solicitationId);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/* ---------------------------------------------------------------- proposals -- */
|
|
279
|
+
|
|
280
|
+
export function saveProposal(solicitationId, { body, markdown, provider, model }) {
|
|
281
|
+
const d = openDb();
|
|
282
|
+
const version = (d.prepare('SELECT MAX(version) AS v FROM proposals WHERE solicitation_id = ?').get(solicitationId).v || 0) + 1;
|
|
283
|
+
const id = randomUUID();
|
|
284
|
+
d.prepare('INSERT INTO proposals (id, solicitation_id, version, status, body, markdown, provider, model, created_at) VALUES (?,?,?,?,?,?,?,?,?)')
|
|
285
|
+
.run(id, solicitationId, version, 'draft', j(body), markdown, provider ?? null, model ?? null, now());
|
|
286
|
+
return { id, version };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const propRow = (r) => (r ? { ...r, body: pj(r.body, {}) } : null);
|
|
290
|
+
export function getProposal(id) {
|
|
291
|
+
return propRow(openDb().prepare('SELECT * FROM proposals WHERE id = ?').get(id));
|
|
292
|
+
}
|
|
293
|
+
export function latestProposal(solicitationId) {
|
|
294
|
+
return propRow(openDb().prepare('SELECT * FROM proposals WHERE solicitation_id = ? ORDER BY version DESC LIMIT 1').get(solicitationId));
|
|
295
|
+
}
|
|
296
|
+
export function setProposalStatus(id, status) {
|
|
297
|
+
openDb().prepare('UPDATE proposals SET status = ? WHERE id = ?').run(status, id);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/* ------------------------------------------------------------ interventions -- */
|
|
301
|
+
|
|
302
|
+
/** Queue a card once per key. A card that was dismissed stays dismissed. */
|
|
303
|
+
export function queueIntervention(iv) {
|
|
304
|
+
const d = openDb();
|
|
305
|
+
const existing = d.prepare('SELECT id, status FROM interventions WHERE key = ?').get(iv.key);
|
|
306
|
+
if (existing) {
|
|
307
|
+
if (existing.status === 'open') {
|
|
308
|
+
d.prepare('UPDATE interventions SET title = ?, body = ?, open_url = ?, copy_text = ?, proposal_id = COALESCE(?, proposal_id), priority = ?, due_at = ? WHERE id = ?')
|
|
309
|
+
.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);
|
|
310
|
+
}
|
|
311
|
+
return { id: existing.id, created: false };
|
|
312
|
+
}
|
|
313
|
+
const id = randomUUID();
|
|
314
|
+
d.prepare(`INSERT INTO interventions (id, key, kind, solicitation_id, proposal_id, title, body, open_url, copy_text, priority, due_at, status, created_at)
|
|
315
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,'open',?)`).run(
|
|
316
|
+
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,
|
|
317
|
+
iv.priority ?? 50, iv.due_at ?? null, now(),
|
|
318
|
+
);
|
|
319
|
+
return { id, created: true };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export function listInterventions({ status = 'open', kind, niche, limit = 100 } = {}) {
|
|
323
|
+
const where = [];
|
|
324
|
+
const args = [];
|
|
325
|
+
if (status && status !== 'all') { where.push('i.status = ?'); args.push(status); }
|
|
326
|
+
if (kind) { where.push('i.kind = ?'); args.push(kind); }
|
|
327
|
+
// Cards with no solicitation (source setup) are always in.
|
|
328
|
+
if (niche && niche !== 'all') {
|
|
329
|
+
const w = [];
|
|
330
|
+
nicheWhere(niche, w, args, 's.');
|
|
331
|
+
where.push(`(i.solicitation_id IS NULL OR ${w[0]})`);
|
|
332
|
+
}
|
|
333
|
+
return openDb().prepare(`SELECT i.*, s.title AS solicitation_title, s.agency, s.number, s.fit_score, s.niche_score, s.niches
|
|
334
|
+
FROM interventions i LEFT JOIN solicitations s ON s.id = i.solicitation_id
|
|
335
|
+
${where.length ? 'WHERE ' + where.join(' AND ') : ''}
|
|
336
|
+
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))
|
|
337
|
+
.map((r) => ({ ...r, niches: pj(r.niches, []) }));
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export function getIntervention(id) {
|
|
341
|
+
return openDb().prepare(`SELECT i.*, s.title AS solicitation_title, s.agency, s.number, s.fit_score, s.url AS solicitation_url
|
|
342
|
+
FROM interventions i LEFT JOIN solicitations s ON s.id = i.solicitation_id WHERE i.id = ?`).get(id) || null;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* A person resolves a card. Marking a submit card done records that THEY
|
|
347
|
+
* submitted it (status submitted_by_human); the system never submits.
|
|
348
|
+
*/
|
|
349
|
+
export function resolveIntervention(id, { status, note, by }) {
|
|
350
|
+
if (!['done', 'dismissed', 'open'].includes(status)) throw new Error('status must be done, dismissed or open');
|
|
351
|
+
const d = openDb();
|
|
352
|
+
const iv = d.prepare('SELECT * FROM interventions WHERE id = ?').get(id);
|
|
353
|
+
if (!iv) return null;
|
|
354
|
+
d.prepare('UPDATE interventions SET status = ?, note = ?, resolved_by = ?, resolved_at = ? WHERE id = ?')
|
|
355
|
+
.run(status, note ? String(note).slice(0, 2000) : null, status === 'open' ? null : by ?? null, status === 'open' ? null : now(), id);
|
|
356
|
+
if (iv.proposal_id && iv.kind === 'submit_proposal') {
|
|
357
|
+
setProposalStatus(iv.proposal_id, status === 'done' ? 'submitted_by_human' : status === 'dismissed' ? 'declined' : 'draft');
|
|
358
|
+
}
|
|
359
|
+
return getIntervention(id);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/* ---------------------------------------------------- accounts and sessions -- */
|
|
363
|
+
|
|
364
|
+
export function accountBySub(sub) {
|
|
365
|
+
return openDb().prepare('SELECT * FROM accounts WHERE coinpay_sub = ?').get(String(sub)) || null;
|
|
366
|
+
}
|
|
367
|
+
export function createAccount(sub, name) {
|
|
368
|
+
const id = randomUUID();
|
|
369
|
+
openDb().prepare('INSERT INTO accounts (id, coinpay_sub, name, created_at) VALUES (?,?,?,?)').run(id, String(sub), name ?? null, now());
|
|
370
|
+
return accountBySub(sub);
|
|
371
|
+
}
|
|
372
|
+
export function createSession(accountId) {
|
|
373
|
+
const token = randomBytes(32).toString('base64url');
|
|
374
|
+
openDb().prepare('INSERT INTO sessions (hash, account_id, created_at) VALUES (?,?,?)').run(sha(token), accountId, now());
|
|
375
|
+
return token;
|
|
376
|
+
}
|
|
377
|
+
export function accountBySession(token) {
|
|
378
|
+
if (!token) return null;
|
|
379
|
+
return openDb().prepare('SELECT a.* FROM sessions s JOIN accounts a ON a.id = s.account_id WHERE s.hash = ?').get(sha(token)) || null;
|
|
380
|
+
}
|
|
381
|
+
export function deleteSession(token) {
|
|
382
|
+
if (token) openDb().prepare('DELETE FROM sessions WHERE hash = ?').run(sha(token));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** For tests. */
|
|
386
|
+
export function _reset() {
|
|
387
|
+
const d = openDb();
|
|
388
|
+
for (const t of ['interventions', 'proposals', 'documents', 'solicitations', 'sessions', 'accounts', 'runs']) d.exec(`DELETE FROM ${t}`);
|
|
389
|
+
for (const t of ['profile', 'profile_pages', 'profile_pages_fts']) { try { d.exec(`DELETE FROM ${t}`); } catch { /* not created yet */ } }
|
|
390
|
+
}
|
package/src/version.js
ADDED