aitable.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. 'use strict';
  2. // 钉钉 AI 表格(原多维表)同步服务
  3. // ----------------------------------------------------------------------------
  4. // 双层架构的云端层:AI 表格 = 在线主档案 + 多人共享层;本地数据湖 = 计算缓存层。
  5. // · pushLake — 把本地湖的新增/更新行(按 syncedAt 水位)upsert 到 AI 表格
  6. // · pullLake — 把 AI 表格记录拉回本地湖(其他机器补数据用,云端为准)
  7. // 业务键:日期|账号名|维度|门店ID(与本地 rowKey 语义对齐,幂等可重跑)。
  8. //
  9. // 钉钉侧契约(企业内部应用 access_token,域 api.dingtalk.com):
  10. // token: POST /v1.0/oauth2/accessToken {appKey, appSecret} → {accessToken, expireIn}
  11. // 记录: /v1.0/notable/bases/{baseId}/sheets/{sheetName}/records
  12. // POST 批量新增 / PUT 批量更新 / GET 分页列表
  13. // ⚠ 端点形态与批量上限在首次真机联调时核对——所有钉钉细节都收敛在本文件,
  14. // 如有偏差只需改这里的常量与两个 transport 方法。
  15. const fs = require('fs');
  16. const path = require('path');
  17. const https = require('https');
  18. const API_BASE = 'https://api.dingtalk.com';
  19. const TOKEN_PATH = '/v1.0/oauth2/accessToken';
  20. const RECORDS_PATH = (baseId, sheetName) => `/v1.0/notable/bases/${encodeURIComponent(baseId)}/sheets/${encodeURIComponent(sheetName)}/records`;
  21. const INSERT_CHUNK = 100; // 单批新增上限(保守值,真机核对后可调)
  22. const UPDATE_CHUNK = 100;
  23. const LIST_PAGE = 100;
  24. // 本地字段 → AI 表格列名(中文列头,人工可读可筛)
  25. const FIELD_COLUMNS = {
  26. date: '日期',
  27. account: '账号名',
  28. dimension: '维度',
  29. shopId: '门店ID',
  30. shopName: '门店名称',
  31. chainId: '连锁ID',
  32. chainName: '连锁名称',
  33. validOrderCnt: '有效订单',
  34. incomeAmt: '收入(元)',
  35. grossAmt: '营业额(元)',
  36. expenseAmt: '支出(元)',
  37. expUv: '曝光人数',
  38. orderUserCnt: '下单人数',
  39. clkExpRate: '进店转化率',
  40. ordClkRate: '下单转化率',
  41. perActualPay: '客单价(元)',
  42. actOrdCnt: '活动订单',
  43. actSubsidyAmt: '活动补贴(元)',
  44. shopRoi: '推广ROI',
  45. rebuyRate30d: '30日复购率',
  46. bizHours: '营业时长(h)',
  47. abnormalCloseHours: '异常关店时长(h)',
  48. goodsSaleAmt: '商品销售额(元)',
  49. };
  50. const METRIC_FIELDS = ['validOrderCnt', 'incomeAmt', 'grossAmt', 'expenseAmt', 'expUv', 'orderUserCnt',
  51. 'clkExpRate', 'ordClkRate', 'perActualPay', 'actOrdCnt', 'actSubsidyAmt', 'shopRoi', 'rebuyRate30d',
  52. 'bizHours', 'abnormalCloseHours', 'goodsSaleAmt'];
  53. const DIMENSION_LABEL = { company: '公司', chain: '连锁', shop: '门店', summary: '汇总' };
  54. function rowToRecord(row, accountName) {
  55. const fields = {
  56. [FIELD_COLUMNS.date]: row.date || '',
  57. [FIELD_COLUMNS.account]: accountName,
  58. [FIELD_COLUMNS.dimension]: DIMENSION_LABEL[row.scope] || row.scope || '',
  59. [FIELD_COLUMNS.shopId]: String(row.shopId || ''),
  60. [FIELD_COLUMNS.shopName]: row.shopName || '',
  61. [FIELD_COLUMNS.chainId]: String(row.chainId || ''),
  62. [FIELD_COLUMNS.chainName]: row.chainName || '',
  63. };
  64. for (const f of METRIC_FIELDS) {
  65. const v = row[f];
  66. fields[FIELD_COLUMNS[f]] = v == null ? null : Number(v);
  67. }
  68. return { fields };
  69. }
  70. function recordKey(fields) {
  71. return [fields[FIELD_COLUMNS.date], fields[FIELD_COLUMNS.account], fields[FIELD_COLUMNS.dimension],
  72. String(fields[FIELD_COLUMNS.shopId] || '')].join('|');
  73. }
  74. function recordToRow(record, defaultAccount) {
  75. const f = record.fields || {};
  76. const byName = (col) => {
  77. if (f[col] != null) return f[col];
  78. // 兼容按 fieldId 返回的形态:取 record.fields 中无法按名列出的场景交由真机联调修正
  79. return null;
  80. };
  81. const rev = {};
  82. for (const [k, col] of Object.entries(FIELD_COLUMNS)) rev[col] = k;
  83. const row = {
  84. date: String(byName(FIELD_COLUMNS.date) || '').replace(/-/g, ''),
  85. scope: Object.entries(DIMENSION_LABEL).find(([, label]) => label === byName(FIELD_COLUMNS.dimension))?.[0] || 'shop',
  86. shopId: String(byName(FIELD_COLUMNS.shopId) || ''),
  87. shopName: byName(FIELD_COLUMNS.shopName) || '',
  88. chainId: String(byName(FIELD_COLUMNS.chainId) || ''),
  89. chainName: byName(FIELD_COLUMNS.chainName) || '',
  90. account: byName(FIELD_COLUMNS.account) || defaultAccount || '',
  91. };
  92. for (const f2 of METRIC_FIELDS) {
  93. const v = byName(FIELD_COLUMNS[f2]);
  94. row[f2] = v == null || v === '' ? 0 : Number(v);
  95. }
  96. row.syncedAt = new Date().toISOString();
  97. return row;
  98. }
  99. function createAitableService(ctx) {
  100. const { config, workspace, logs } = ctx;
  101. // ---------- token(进程内缓存,提前 60s 过期) ----------
  102. let tokenCache = { token: null, expireAt: 0 };
  103. function transport(method, urlPath, bodyObj, token) {
  104. return new Promise((resolve, reject) => {
  105. const data = bodyObj !== undefined ? JSON.stringify(bodyObj) : null;
  106. const req = https.request({
  107. hostname: 'api.dingtalk.com', path: urlPath, method,
  108. headers: {
  109. 'Content-Type': 'application/json',
  110. ...(token ? { 'x-acs-dingtalk-access-token': token } : {}),
  111. ...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}),
  112. },
  113. timeout: 30000,
  114. }, (res) => {
  115. const chunks = [];
  116. res.on('data', (c) => chunks.push(c));
  117. res.on('end', () => {
  118. const raw = Buffer.concat(chunks).toString('utf8');
  119. let json = null;
  120. try { json = JSON.parse(raw); } catch { /* keep raw */ }
  121. resolve({ statusCode: res.statusCode, json, raw: raw.slice(0, 800) });
  122. });
  123. });
  124. req.on('error', reject);
  125. req.on('timeout', () => req.destroy(new Error('请求超时')));
  126. if (data) req.write(data);
  127. req.end();
  128. });
  129. }
  130. async function getToken() {
  131. const cfg = config.aitable || {};
  132. if (!cfg.appKey || !cfg.appSecret) throw err('未配置钉钉应用凭据(appKey/appSecret)', 'AITABLE_NO_CFG');
  133. const now = Date.now();
  134. if (tokenCache.token && now < tokenCache.expireAt) return tokenCache.token;
  135. const res = await transport('POST', TOKEN_PATH, { appKey: cfg.appKey, appSecret: cfg.appSecret });
  136. const token = res.json && (res.json.accessToken || (res.json.result && res.json.result.accessToken));
  137. const expireIn = Number((res.json && (res.json.expireIn ?? res.json.result?.expireIn)) || 7200);
  138. if (res.statusCode !== 200 || !token) {
  139. throw err(`获取 access_token 失败 HTTP ${res.statusCode}: ${(res.json && (res.json.message || res.json.errmsg)) || res.raw}`, 'AITABLE_AUTH_FAIL');
  140. }
  141. tokenCache = { token, expireAt: now + Math.max(60, expireIn - 60) * 1000 };
  142. return token;
  143. }
  144. function err(message, code) { const e = new Error(message); e.code = code; e.status = 400; return e; }
  145. function requireConfig() {
  146. const cfg = config.aitable || {};
  147. if (!cfg.enabled) throw err('钉钉 AI 表格同步未启用(系统设置中开启)', 'AITABLE_DISABLED');
  148. if (!cfg.baseId || !cfg.sheetName || !cfg.appKey) throw err('钉钉 AI 表格配置不完整(AppKey / Base ID / 数据表名称)', 'AITABLE_NO_CFG');
  149. return cfg;
  150. }
  151. async function listAllRecords(cfg) {
  152. const token = await getToken();
  153. const out = [];
  154. let nextToken = '';
  155. for (;;) {
  156. const q = `?maxResults=${LIST_PAGE}${nextToken ? `&nextToken=${encodeURIComponent(nextToken)}` : ''}`;
  157. const res = await transport('GET', RECORDS_PATH(cfg.baseId, cfg.sheetName) + q, undefined, token);
  158. if (res.statusCode !== 200) throw err(`拉取记录失败 HTTP ${res.statusCode}: ${(res.json && res.json.message) || res.raw}`, 'AITABLE_LIST_FAIL');
  159. const d = res.json || {};
  160. const records = Array.isArray(d.records) ? d.records
  161. : Array.isArray(d.value) ? d.value
  162. : Array.isArray(d.data) ? d.data : [];
  163. out.push(...records);
  164. nextToken = d.nextToken || d.nextCursor || '';
  165. if (!nextToken) break;
  166. }
  167. return out;
  168. }
  169. function chunk(arr, n) {
  170. const out = [];
  171. for (let i = 0; i < arr.length; i += n) out.push(arr.slice(i, i + n));
  172. return out;
  173. }
  174. // ---------- 推送:本地湖 → AI 表格 ----------
  175. const pushStateFile = () => path.join(workspace.getWorkspaceRoot(), '.genpic', 'aitable-push.json');
  176. function readPushState() {
  177. try { return JSON.parse(fs.readFileSync(pushStateFile(), 'utf8')); } catch { return {}; }
  178. }
  179. function writePushState(state) {
  180. try {
  181. const file = pushStateFile();
  182. fs.mkdirSync(path.dirname(file), { recursive: true });
  183. const temp = `${file}.${process.pid}.tmp`;
  184. fs.writeFileSync(temp, JSON.stringify(state, null, 2), 'utf8');
  185. fs.renameSync(temp, file);
  186. } catch { /* 状态落盘失败不阻断推送 */ }
  187. }
  188. /** 推送一个主体的数据。force=true 时忽略水位推全量。返回统计。 */
  189. async function pushLake(entity, opts = {}) {
  190. const cfg = requireConfig();
  191. const naposService = require('../../napos-service.js');
  192. const key = naposService.store.sanitizeKey(entity);
  193. const meta = naposService.store.getEntity(key);
  194. const accountName = meta ? meta.name : key;
  195. const state = readPushState();
  196. const watermark = opts.force ? 0 : (state[key] || {}).lastPushedAt || 0;
  197. let rows;
  198. if (watermark) {
  199. const all = naposService.store.loadRows(key) || [];
  200. rows = all.filter((r) => new Date(r.syncedAt || 0).getTime() > watermark);
  201. } else {
  202. rows = naposService.store.loadRows(key) || [];
  203. }
  204. if (!rows.length) return { pushed: 0, created: 0, updated: 0, skipped: '无新增数据' };
  205. const token = await getToken();
  206. // 现有记录索引:业务键 → recordId(分页拉全量)
  207. const existing = new Map();
  208. for (const rec of await listAllRecords(cfg)) {
  209. const f = rec.fields || {};
  210. const k = recordKey({
  211. [FIELD_COLUMNS.date]: f[FIELD_COLUMNS.date],
  212. [FIELD_COLUMNS.account]: f[FIELD_COLUMNS.account],
  213. [FIELD_COLUMNS.dimension]: f[FIELD_COLUMNS.dimension],
  214. [FIELD_COLUMNS.shopId]: f[FIELD_COLUMNS.shopId],
  215. });
  216. if (rec.id) existing.set(k, rec.id);
  217. }
  218. let created = 0;
  219. let updated = 0;
  220. const toCreate = [];
  221. const toUpdate = []; // {recordId, fields}
  222. for (const row of rows) {
  223. const rec = rowToRecord(row, accountName);
  224. const k = recordKey(rec.fields);
  225. const rid = existing.get(k);
  226. if (rid) toUpdate.push({ record_id: rid, fields: rec.fields });
  227. else toCreate.push(rec);
  228. }
  229. for (const part of chunk(toCreate, INSERT_CHUNK)) {
  230. const res = await transport('POST', RECORDS_PATH(cfg.baseId, cfg.sheetName), { records: part }, token);
  231. if (res.statusCode >= 300) throw err(`批量新增失败 HTTP ${res.statusCode}: ${(res.json && res.json.message) || res.raw}`, 'AITABLE_CREATE_FAIL');
  232. created += part.length;
  233. }
  234. for (const part of chunk(toUpdate, UPDATE_CHUNK)) {
  235. const res = await transport('PUT', RECORDS_PATH(cfg.baseId, cfg.sheetName), { records: part }, token);
  236. if (res.statusCode >= 300) throw err(`批量更新失败 HTTP ${res.statusCode}: ${(res.json && res.json.message) || res.raw}`, 'AITABLE_UPDATE_FAIL');
  237. updated += part.length;
  238. }
  239. const now = Date.now();
  240. state[key] = { lastPushedAt: now, pushedRows: rows.length, at: new Date().toISOString() };
  241. writePushState(state);
  242. return { pushed: rows.length, created, updated, account: accountName };
  243. }
  244. // ---------- 拉取:AI 表格 → 本地湖 ----------
  245. /**
  246. * 拉取 AI 表格记录回本地湖(云端为准,本地同键行被覆盖)。
  247. * entity 缺省 = 拉取云端全部账号:没有注册过的新账号会自动创建轻量主体
  248. * (fresh 机器拉一次即可用报表/图表/问数)。
  249. */
  250. async function pullLake(entity) {
  251. const cfg = requireConfig();
  252. const naposService = require('../../napos-service.js');
  253. const records = await listAllRecords(cfg);
  254. const groups = new Map();
  255. const wantName = entity
  256. ? ((naposService.store.getEntity(naposService.store.sanitizeKey(entity)) || {}).name || entity)
  257. : null;
  258. for (const rec of records) {
  259. const f = rec.fields || {};
  260. const acc = String(f[FIELD_COLUMNS.account] || '').trim();
  261. if (!acc) continue;
  262. if (wantName && acc !== wantName) continue;
  263. if (!groups.has(acc)) groups.set(acc, []);
  264. groups.get(acc).push(recordToRow({ fields: f }, acc));
  265. }
  266. if (!groups.size) return { pulled: 0, accounts: [], message: '云端没有可拉取的数据' };
  267. const result = { pulled: 0, accounts: [] };
  268. for (const [acc, rows] of groups) {
  269. let key = naposService.store.sanitizeKey(acc);
  270. const meta = naposService.store.getEntity(key);
  271. if (!meta || !meta.key) {
  272. const created = naposService.store.upsertEntity({ merchantId: acc, merchantName: acc, chains: [], shops: [] });
  273. key = created.entity.key;
  274. }
  275. const res = naposService.store.upsertRows(key, rows);
  276. result.pulled += rows.length;
  277. result.accounts.push({ account: acc, rows: rows.length, added: res.added, updated: res.updated });
  278. }
  279. return result;
  280. }
  281. /** 连通性测试:token + 表可读 */
  282. async function testConnection() {
  283. const cfg = requireConfig();
  284. const token = await getToken();
  285. const res = await transport('GET', RECORDS_PATH(cfg.baseId, cfg.sheetName) + `?maxResults=1`, undefined, token);
  286. if (res.statusCode !== 200) throw err(`表读取失败 HTTP ${res.statusCode}: ${(res.json && res.json.message) || res.raw}`, 'AITABLE_TEST_FAIL');
  287. return { ok: true, baseId: cfg.baseId, sheetName: cfg.sheetName };
  288. }
  289. function lastPushInfo(entity) {
  290. const key = require('../../napos-service.js').store.sanitizeKey(entity);
  291. const s = readPushState()[key] || null;
  292. return s;
  293. }
  294. logs.pushSystemLog('钉钉 AI 表格同步服务已就绪', 'info');
  295. return { pushLake, pullLake, testConnection, lastPushInfo };
  296. }
  297. module.exports = { createAitableService, FIELD_COLUMNS, DIMENSION_LABEL, rowToRecord, recordKey, recordToRow };