aitable.js 15 KB

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