ops-pg.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. 'use strict';
  2. /**
  3. * ops 存储 · PostgreSQL 驱动
  4. * ----------------------------------------------------------------------------
  5. * 与 SQLite 驱动同接口。`pg` 为可选依赖(本期不安装):未安装时 health() 返回明确原因,
  6. * 只有「店铺运营」功能不可用,服务与其它功能不受影响。
  7. *
  8. * 上线切换步骤见设计文档 §5.6:改 config.storage.driver = "postgres" + 填连接串 + npm i pg。
  9. */
  10. const SCHEMA_VERSION = '1';
  11. const DDL = [
  12. `CREATE TABLE IF NOT EXISTS ops_meta (
  13. key text PRIMARY KEY,
  14. value text NOT NULL
  15. )`,
  16. `CREATE TABLE IF NOT EXISTS ops_upload (
  17. id text PRIMARY KEY,
  18. original_name text NOT NULL,
  19. sha256 text NOT NULL,
  20. size_bytes integer NOT NULL,
  21. uploaded_at timestamptz NOT NULL,
  22. year integer NOT NULL,
  23. parser_kind text NOT NULL,
  24. parser_version integer NOT NULL,
  25. report jsonb NOT NULL DEFAULT '{}'::jsonb,
  26. content bytea NOT NULL
  27. )`,
  28. `CREATE INDEX IF NOT EXISTS ops_upload_sha256_idx ON ops_upload (sha256, uploaded_at DESC)`,
  29. `CREATE TABLE IF NOT EXISTS ops_shop (
  30. key text PRIMARY KEY,
  31. shop_id text,
  32. shop_name text NOT NULL,
  33. school text NOT NULL,
  34. status text,
  35. last_upload_id text REFERENCES ops_upload(id) ON DELETE SET NULL,
  36. first_seen timestamptz NOT NULL,
  37. last_seen timestamptz NOT NULL
  38. )`,
  39. `CREATE TABLE IF NOT EXISTS ops_row (
  40. date char(8) NOT NULL,
  41. shop_key text NOT NULL,
  42. upload_id text NOT NULL REFERENCES ops_upload(id) ON DELETE CASCADE,
  43. shop_id text,
  44. shop_name text NOT NULL,
  45. school text NOT NULL,
  46. status text,
  47. order_cnt integer,
  48. revenue numeric(14,2),
  49. exposure integer,
  50. click_rate numeric(8,6),
  51. raw jsonb NOT NULL DEFAULT '{}'::jsonb,
  52. quality text[] NOT NULL DEFAULT '{}',
  53. updated_at timestamptz NOT NULL,
  54. PRIMARY KEY (date, shop_key)
  55. )`,
  56. `CREATE INDEX IF NOT EXISTS ops_row_school_date_idx ON ops_row (school, date)`,
  57. `CREATE TABLE IF NOT EXISTS ops_platform_row (
  58. date char(8) NOT NULL,
  59. shop_id text NOT NULL,
  60. upload_id text NOT NULL REFERENCES ops_upload(id) ON DELETE CASCADE,
  61. school text NOT NULL DEFAULT '',
  62. shop_name text NOT NULL DEFAULT '',
  63. data jsonb NOT NULL DEFAULT '{}'::jsonb,
  64. updated_at timestamptz NOT NULL,
  65. PRIMARY KEY (date, shop_id)
  66. )`,
  67. `CREATE INDEX IF NOT EXISTS ops_platform_row_date_idx ON ops_platform_row (date)`,
  68. `CREATE TABLE IF NOT EXISTS ops_report (
  69. id text PRIMARY KEY,
  70. created_at timestamptz NOT NULL,
  71. period_from char(8) NOT NULL,
  72. period_to char(8) NOT NULL,
  73. schools jsonb NOT NULL DEFAULT '[]'::jsonb,
  74. shops jsonb NOT NULL DEFAULT '[]'::jsonb,
  75. source text NOT NULL DEFAULT 'rules',
  76. model text NOT NULL DEFAULT '',
  77. title text NOT NULL DEFAULT '',
  78. report jsonb NOT NULL
  79. )`,
  80. `CREATE INDEX IF NOT EXISTS ops_report_created_idx ON ops_report (created_at DESC)`,
  81. ];
  82. function rowToApi(row) {
  83. if (!row) return null;
  84. return {
  85. date: String(row.date || '').trim(),
  86. shopKey: row.shop_key,
  87. shopId: row.shop_id,
  88. shopName: row.shop_name,
  89. school: row.school,
  90. status: row.status,
  91. order_cnt: row.order_cnt == null ? null : Number(row.order_cnt),
  92. revenue: row.revenue == null ? null : Number(row.revenue),
  93. exposure: row.exposure == null ? null : Number(row.exposure),
  94. click_rate: row.click_rate == null ? null : Number(row.click_rate),
  95. raw: row.raw || {},
  96. quality: row.quality || [],
  97. uploadId: row.upload_id,
  98. updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : row.updated_at,
  99. };
  100. }
  101. function createPgStore({ connectionString, ssl = true, max = 5, schema = 'public', connectTimeoutMs = 10000 }) {
  102. let pool = null;
  103. let initPromise = null;
  104. function getPool() {
  105. if (pool) return pool;
  106. let pg;
  107. try {
  108. pg = require('pg');
  109. } catch {
  110. const err = new Error('未安装 pg(npm i pg)');
  111. err.reason = 'pg-not-installed';
  112. throw err;
  113. }
  114. pool = new pg.Pool({
  115. connectionString,
  116. max: Number(max) || 5,
  117. ssl: ssl ? { rejectUnauthorized: false } : false,
  118. connectionTimeoutMillis: Number(connectTimeoutMs) || 10000,
  119. options: `-c search_path=${schema || 'public'}`,
  120. });
  121. return pool;
  122. }
  123. async function init() {
  124. if (!initPromise) {
  125. initPromise = (async () => {
  126. const client = await getPool().connect();
  127. try {
  128. for (const sql of DDL) await client.query(sql);
  129. await client.query(
  130. 'INSERT INTO ops_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value',
  131. ['schema_version', SCHEMA_VERSION],
  132. );
  133. } finally {
  134. client.release();
  135. }
  136. return true;
  137. })().catch((e) => {
  138. initPromise = null;
  139. throw e;
  140. });
  141. }
  142. return initPromise;
  143. }
  144. async function health() {
  145. try {
  146. await getPool().query('SELECT 1 AS ok');
  147. return { ok: true, kind: 'postgres', detail: (schema || 'public') };
  148. } catch (e) {
  149. return { ok: false, kind: 'postgres', detail: e.message || String(e) };
  150. }
  151. }
  152. async function withTransaction(fn) {
  153. const client = await getPool().connect();
  154. try {
  155. await client.query('BEGIN');
  156. const result = await fn(makeTx(client));
  157. await client.query('COMMIT');
  158. return result;
  159. } catch (e) {
  160. try { await client.query('ROLLBACK'); } catch { /* 已结束 */ }
  161. throw e;
  162. } finally {
  163. client.release();
  164. }
  165. }
  166. function makeTx(client) {
  167. return {
  168. async insertUpload(upload) {
  169. await client.query(
  170. `INSERT INTO ops_upload (id, original_name, sha256, size_bytes, uploaded_at, year,
  171. parser_kind, parser_version, report, content)
  172. VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
  173. [upload.id, upload.originalName, upload.sha256, upload.sizeBytes, upload.uploadedAt,
  174. upload.year, upload.parserKind, upload.parserVersion, JSON.stringify(upload.report || {}), upload.content],
  175. );
  176. },
  177. async upsertRows(rows) {
  178. const now = new Date().toISOString();
  179. for (const r of rows) {
  180. await client.query(
  181. `INSERT INTO ops_row (date, shop_key, upload_id, shop_id, shop_name, school, status,
  182. order_cnt, revenue, exposure, click_rate, raw, quality, updated_at)
  183. VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
  184. ON CONFLICT (date, shop_key) DO UPDATE SET
  185. upload_id = EXCLUDED.upload_id, shop_id = EXCLUDED.shop_id, shop_name = EXCLUDED.shop_name,
  186. school = EXCLUDED.school, status = EXCLUDED.status, order_cnt = EXCLUDED.order_cnt,
  187. revenue = EXCLUDED.revenue, exposure = EXCLUDED.exposure, click_rate = EXCLUDED.click_rate,
  188. raw = EXCLUDED.raw, quality = EXCLUDED.quality, updated_at = EXCLUDED.updated_at`,
  189. [r.date, r.shopKey, r.uploadId, r.shopId || null, r.shopName, r.school, r.status || null,
  190. r.order_cnt, r.revenue, r.exposure, r.click_rate,
  191. JSON.stringify(r.raw || {}), r.quality || [], now],
  192. );
  193. }
  194. },
  195. async upsertShops(shops) {
  196. const now = new Date().toISOString();
  197. for (const s of shops) {
  198. await client.query(
  199. `INSERT INTO ops_shop (key, shop_id, shop_name, school, status, last_upload_id, first_seen, last_seen)
  200. VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
  201. ON CONFLICT (key) DO UPDATE SET
  202. shop_id = EXCLUDED.shop_id, shop_name = EXCLUDED.shop_name, school = EXCLUDED.school,
  203. status = EXCLUDED.status, last_upload_id = EXCLUDED.last_upload_id, last_seen = EXCLUDED.last_seen`,
  204. [s.key, s.shopId || null, s.shopName, s.school, s.status || null, s.lastUploadId || null, now, now],
  205. );
  206. }
  207. },
  208. async deleteRowsByUpload(uploadId) {
  209. await client.query('DELETE FROM ops_row WHERE upload_id = $1', [uploadId]);
  210. },
  211. async upsertPlatformRows(rows) {
  212. const now = new Date().toISOString();
  213. for (const r of rows) {
  214. await client.query(
  215. `INSERT INTO ops_platform_row (date, shop_id, upload_id, school, shop_name, data, updated_at)
  216. VALUES ($1,$2,$3,$4,$5,$6,$7)
  217. ON CONFLICT (date, shop_id) DO UPDATE SET
  218. upload_id = EXCLUDED.upload_id, school = EXCLUDED.school,
  219. shop_name = EXCLUDED.shop_name, data = EXCLUDED.data, updated_at = EXCLUDED.updated_at`,
  220. [r.date, r.shopId, r.uploadId, r.school || '', r.shopName || '', JSON.stringify(r.data || {}), now],
  221. );
  222. }
  223. },
  224. async deletePlatformRowsByUpload(uploadId) {
  225. await client.query('DELETE FROM ops_platform_row WHERE upload_id = $1', [uploadId]);
  226. },
  227. async deletePlatformRowsBySha(sha256) {
  228. await client.query('DELETE FROM ops_platform_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = $1)', [sha256]);
  229. },
  230. async deleteRowsBySha(sha256) {
  231. await client.query('DELETE FROM ops_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = $1)', [sha256]);
  232. },
  233. async pruneOrphanShops() {
  234. await client.query('DELETE FROM ops_shop s WHERE NOT EXISTS (SELECT 1 FROM ops_row r WHERE r.shop_key = s.key)');
  235. },
  236. async findUploadBySha(sha256) {
  237. const r = await client.query('SELECT id FROM ops_upload WHERE sha256 = $1 ORDER BY uploaded_at DESC LIMIT 1', [sha256]);
  238. return r.rows.length ? r.rows[0].id : null;
  239. },
  240. async updateReport(id, report) {
  241. await client.query('UPDATE ops_upload SET report = $1 WHERE id = $2', [JSON.stringify(report || {}), id]);
  242. },
  243. };
  244. }
  245. async function findUploadBySha(sha256) {
  246. const r = await getPool().query('SELECT id FROM ops_upload WHERE sha256 = $1 ORDER BY uploaded_at DESC LIMIT 1', [sha256]);
  247. return r.rows.length ? r.rows[0].id : null;
  248. }
  249. function uploadRowToApi(row) {
  250. if (!row) return null;
  251. const report = row.report || {};
  252. return {
  253. id: row.id,
  254. originalName: row.original_name,
  255. sha256: row.sha256,
  256. sizeBytes: row.size_bytes,
  257. uploadedAt: row.uploaded_at instanceof Date ? row.uploaded_at.toISOString() : row.uploaded_at,
  258. year: row.year,
  259. parserKind: row.parser_kind,
  260. parserVersion: row.parser_version,
  261. report,
  262. rows: report.rows || 0,
  263. shops: report.shops || 0,
  264. warningCount: report.warningCount || 0,
  265. };
  266. }
  267. async function listUploads() {
  268. const r = await getPool().query(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  269. parser_kind, parser_version, report FROM ops_upload ORDER BY uploaded_at DESC`);
  270. return r.rows.map(uploadRowToApi);
  271. }
  272. async function getUpload(id) {
  273. const r = await getPool().query(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  274. parser_kind, parser_version, report FROM ops_upload WHERE id = $1`, [id]);
  275. return uploadRowToApi(r.rows[0]);
  276. }
  277. async function getContent(id) {
  278. const r = await getPool().query('SELECT content, original_name FROM ops_upload WHERE id = $1', [id]);
  279. if (!r.rows.length) return null;
  280. return { content: r.rows[0].content, originalName: r.rows[0].original_name };
  281. }
  282. async function queryRows({ from, to, schools, shops } = {}) {
  283. const where = [];
  284. const params = [];
  285. if (from) { params.push(String(from)); where.push(`date >= $${params.length}`); }
  286. if (to) { params.push(String(to)); where.push(`date <= $${params.length}`); }
  287. if (Array.isArray(schools) && schools.length) { params.push(schools.map(String)); where.push(`school = ANY($${params.length})`); }
  288. if (Array.isArray(shops) && shops.length) { params.push(shops.map(String)); where.push(`shop_key = ANY($${params.length})`); }
  289. const sql = `SELECT * FROM ops_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
  290. ORDER BY school ASC, shop_name ASC, date ASC`;
  291. const r = await getPool().query(sql, params);
  292. return r.rows.map(rowToApi);
  293. }
  294. async function queryPlatformRows({ from, to } = {}) {
  295. const where = [];
  296. const params = [];
  297. if (from) { params.push(String(from)); where.push(`date >= ${params.length}`); }
  298. if (to) { params.push(String(to)); where.push(`date <= ${params.length}`); }
  299. const sql = `SELECT * FROM ops_platform_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY date ASC, shop_id ASC`;
  300. const r = await getPool().query(sql, params);
  301. return r.rows.map((row) => ({
  302. date: String(row.date).trim(),
  303. shopId: row.shop_id,
  304. uploadId: row.upload_id,
  305. school: row.school,
  306. shopName: row.shop_name,
  307. data: row.data || {},
  308. updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : row.updated_at,
  309. }));
  310. }
  311. async function summary() {
  312. const poolRef = getPool();
  313. const [uploadCount, rowCount, platformRowCount, range, matrix, schools, shops, last] = await Promise.all([
  314. poolRef.query('SELECT COUNT(*)::int AS c FROM ops_upload'),
  315. poolRef.query('SELECT COUNT(*)::int AS c FROM ops_row'),
  316. poolRef.query('SELECT COUNT(*)::int AS c FROM ops_platform_row'),
  317. poolRef.query(`SELECT MIN(d) AS f, MAX(d) AS t FROM (
  318. SELECT date AS d FROM ops_row UNION SELECT date AS d FROM ops_platform_row)`),
  319. poolRef.query(`SELECT COUNT(*)::int AS c FROM (
  320. SELECT date, shop_key FROM ops_row UNION SELECT date, shop_id FROM ops_platform_row)`),
  321. poolRef.query(`SELECT school, COUNT(DISTINCT shop)::int AS c FROM (
  322. SELECT school, shop_id AS shop FROM ops_platform_row WHERE school <> ''
  323. UNION SELECT school, shop_key AS shop FROM ops_row WHERE school <> ''
  324. UNION SELECT school, key AS shop FROM ops_shop WHERE school <> ''
  325. ) AS t GROUP BY school ORDER BY school ASC`),
  326. poolRef.query(`SELECT key, MAX(shop_id) AS shop_id, MAX(shop_name) AS shop_name,
  327. MAX(school) AS school, MAX(status) AS status FROM (
  328. SELECT key, shop_id, shop_name, school, status FROM ops_shop
  329. UNION ALL
  330. SELECT shop_id AS key, shop_id, shop_name, school, NULL AS status FROM ops_platform_row
  331. ) AS t GROUP BY key ORDER BY school ASC, shop_name ASC`),
  332. poolRef.query('SELECT id, original_name, uploaded_at, report FROM ops_upload ORDER BY uploaded_at DESC LIMIT 1'),
  333. ]);
  334. return {
  335. schools: schools.rows.map((r) => ({ name: r.school, shopCount: r.c })),
  336. shops: shops.rows.map((r) => ({ key: r.key, shopId: r.shop_id, shopName: r.shop_name, school: r.school, status: r.status })),
  337. uploadCount: uploadCount.rows[0].c,
  338. rowCount: rowCount.rows[0].c,
  339. platformRowCount: platformRowCount.rows[0].c,
  340. matrixRowCount: matrix.rows[0].c,
  341. coverage: range.rows[0] && range.rows[0].f ? { from: String(range.rows[0].f).replace(/-/g, ''), to: String(range.rows[0].t).replace(/-/g, '') } : null,
  342. lastUpload: last.rows.length ? {
  343. id: last.rows[0].id,
  344. at: last.rows[0].uploaded_at instanceof Date ? last.rows[0].uploaded_at.toISOString() : last.rows[0].uploaded_at,
  345. originalName: last.rows[0].original_name,
  346. rows: (last.rows[0].report || {}).rows || 0,
  347. warningCount: (last.rows[0].report || {}).warningCount || 0,
  348. } : null,
  349. };
  350. }
  351. async function insertReport(record) {
  352. await getPool().query(
  353. `INSERT INTO ops_report (id, created_at, period_from, period_to, schools, shops, source, model, title, report)
  354. VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
  355. [record.id, record.createdAt, record.periodFrom, record.periodTo,
  356. JSON.stringify(record.schools || []), JSON.stringify(record.shops || []),
  357. record.source || 'rules', record.model || '', record.title || '', JSON.stringify(record.report)],
  358. );
  359. }
  360. async function listReports() {
  361. const r = await getPool().query(`SELECT id, created_at, period_from, period_to, source, model, title, report
  362. FROM ops_report ORDER BY created_at DESC LIMIT 100`);
  363. return r.rows.map((row) => ({
  364. id: row.id,
  365. createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
  366. from: String(row.period_from).trim(),
  367. to: String(row.period_to).trim(),
  368. source: row.source,
  369. model: row.model,
  370. title: row.title,
  371. kpis: ((row.report && row.report.kpis) || []).slice(0, 3).map((k) => ({ label: k.label, current: k.current, unit: k.unit })),
  372. }));
  373. }
  374. async function getReport(id) {
  375. const r = await getPool().query('SELECT report FROM ops_report WHERE id = $1', [id]);
  376. return r.rows.length ? r.rows[0].report : null;
  377. }
  378. async function deleteReport(id) {
  379. const r = await getPool().query('DELETE FROM ops_report WHERE id = $1', [id]);
  380. return r.rowCount;
  381. }
  382. async function close() {
  383. if (pool) {
  384. try { await pool.end(); } catch { /* ignore */ }
  385. pool = null;
  386. initPromise = null;
  387. }
  388. }
  389. return {
  390. kind: 'postgres',
  391. init,
  392. health,
  393. withTransaction,
  394. findUploadBySha,
  395. queryPlatformRows,
  396. insertReport,
  397. listReports,
  398. getReport,
  399. deleteReport,
  400. listUploads,
  401. getUpload,
  402. getContent,
  403. queryRows,
  404. summary,
  405. close,
  406. };
  407. }
  408. module.exports = { createPgStore };