@yudaocode/univer-bases 1.6.218 → 1.6.219
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/README.md +8 -1
- package/lib/cjs/facade/index.js +49 -0
- package/lib/cjs/facade/index.js.map +1 -1
- package/lib/cjs/index.js +2293 -131
- package/lib/cjs/index.js.map +1 -1
- package/lib/es/facade/index.js +56 -0
- package/lib/es/facade/index.js.map +1 -1
- package/lib/es/index.js +2224 -86
- package/lib/es/index.js.map +1 -1
- package/lib/types/facade/index.d.ts +19 -1
- package/lib/types/index.d.ts +316 -7
- package/package.json +1 -1
package/lib/es/index.js
CHANGED
|
@@ -1487,11 +1487,1874 @@ function computeBaseGanttTasks(unitData, tableId, viewId) {
|
|
|
1487
1487
|
totalDays
|
|
1488
1488
|
};
|
|
1489
1489
|
}
|
|
1490
|
+
function computeBaseHierarchicalList(unitData, tableId, viewId, options) {
|
|
1491
|
+
const query = queryBaseTableView(unitData, tableId, viewId, options?.overrides);
|
|
1492
|
+
const { table, view, rows, allFields } = query;
|
|
1493
|
+
const selfLinkFields = allFields.filter(
|
|
1494
|
+
(f) => f.type === "link" && f.config?.linkedTableId === table.id
|
|
1495
|
+
);
|
|
1496
|
+
const explicitParentId = options?.parentFieldId ?? view.listParentFieldId;
|
|
1497
|
+
const preferredSelfLink = (explicitParentId ? selfLinkFields.find((f) => f.id === explicitParentId) : void 0) ?? selfLinkFields.find(
|
|
1498
|
+
(f) => f.name.includes("\u7236") || f.name.includes("\u4E0A\u7EA7") || f.name.toLowerCase().includes("parent")
|
|
1499
|
+
) ?? selfLinkFields[0] ?? null;
|
|
1500
|
+
const primaryField = table.fields[table.primaryFieldId] ?? allFields[0];
|
|
1501
|
+
const collapsedSet = new Set(
|
|
1502
|
+
options?.collapsedRecordIds ?? view.listCollapsedRecordIds ?? []
|
|
1503
|
+
);
|
|
1504
|
+
const rowById = /* @__PURE__ */ new Map();
|
|
1505
|
+
for (const row of rows) {
|
|
1506
|
+
rowById.set(row.recordId, row);
|
|
1507
|
+
}
|
|
1508
|
+
const resolvedParentMap = /* @__PURE__ */ new Map();
|
|
1509
|
+
const cycleFlags = /* @__PURE__ */ new Map();
|
|
1510
|
+
for (const row of rows) {
|
|
1511
|
+
if (!preferredSelfLink) {
|
|
1512
|
+
resolvedParentMap.set(row.recordId, null);
|
|
1513
|
+
cycleFlags.set(row.recordId, false);
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
const rawLinks = normalizeLinkIds(row.values[preferredSelfLink.id]);
|
|
1517
|
+
const selfRef = rawLinks.includes(row.recordId);
|
|
1518
|
+
const candParentId = rawLinks.find((id) => id !== row.recordId && rowById.has(id)) ?? null;
|
|
1519
|
+
if (!candParentId) {
|
|
1520
|
+
resolvedParentMap.set(row.recordId, null);
|
|
1521
|
+
cycleFlags.set(row.recordId, selfRef);
|
|
1522
|
+
continue;
|
|
1523
|
+
}
|
|
1524
|
+
const visited = /* @__PURE__ */ new Set([row.recordId]);
|
|
1525
|
+
let cur = candParentId;
|
|
1526
|
+
let hasCycle = false;
|
|
1527
|
+
while (cur) {
|
|
1528
|
+
if (visited.has(cur)) {
|
|
1529
|
+
hasCycle = true;
|
|
1530
|
+
break;
|
|
1531
|
+
}
|
|
1532
|
+
visited.add(cur);
|
|
1533
|
+
cur = resolvedParentMap.get(cur) ?? null;
|
|
1534
|
+
}
|
|
1535
|
+
if (hasCycle) {
|
|
1536
|
+
resolvedParentMap.set(row.recordId, null);
|
|
1537
|
+
cycleFlags.set(row.recordId, true);
|
|
1538
|
+
} else {
|
|
1539
|
+
resolvedParentMap.set(row.recordId, candParentId);
|
|
1540
|
+
cycleFlags.set(row.recordId, selfRef);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
const nodeById = /* @__PURE__ */ new Map();
|
|
1544
|
+
for (const row of rows) {
|
|
1545
|
+
const title = (primaryField ? row.displayValues[primaryField.id] : "") || row.recordId;
|
|
1546
|
+
nodeById.set(row.recordId, {
|
|
1547
|
+
recordId: row.recordId,
|
|
1548
|
+
parentId: resolvedParentMap.get(row.recordId) ?? null,
|
|
1549
|
+
depth: 0,
|
|
1550
|
+
title,
|
|
1551
|
+
row,
|
|
1552
|
+
collapsed: collapsedSet.has(row.recordId),
|
|
1553
|
+
cycleDetected: Boolean(cycleFlags.get(row.recordId)),
|
|
1554
|
+
children: [],
|
|
1555
|
+
descendantCount: 0
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
const roots = [];
|
|
1559
|
+
for (const row of rows) {
|
|
1560
|
+
const node = nodeById.get(row.recordId);
|
|
1561
|
+
if (node.parentId && nodeById.has(node.parentId)) {
|
|
1562
|
+
nodeById.get(node.parentId).children.push(node);
|
|
1563
|
+
} else {
|
|
1564
|
+
node.parentId = null;
|
|
1565
|
+
roots.push(node);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
let maxDepth = 0;
|
|
1569
|
+
const flattenedVisibleNodes = [];
|
|
1570
|
+
const finalizeTree = (node, depth, ancestorCollapsed, guard2) => {
|
|
1571
|
+
if (guard2.has(node.recordId)) return 0;
|
|
1572
|
+
guard2.add(node.recordId);
|
|
1573
|
+
node.depth = depth;
|
|
1574
|
+
if (depth > maxDepth) maxDepth = depth;
|
|
1575
|
+
if (!ancestorCollapsed) {
|
|
1576
|
+
flattenedVisibleNodes.push(node);
|
|
1577
|
+
}
|
|
1578
|
+
let desc = 0;
|
|
1579
|
+
const hideKids = ancestorCollapsed || node.collapsed;
|
|
1580
|
+
for (const child of node.children) {
|
|
1581
|
+
desc += 1 + finalizeTree(child, depth + 1, hideKids, guard2);
|
|
1582
|
+
}
|
|
1583
|
+
node.descendantCount = desc;
|
|
1584
|
+
return desc;
|
|
1585
|
+
};
|
|
1586
|
+
const guard = /* @__PURE__ */ new Set();
|
|
1587
|
+
for (const root of roots) {
|
|
1588
|
+
finalizeTree(root, 0, false, guard);
|
|
1589
|
+
}
|
|
1590
|
+
return {
|
|
1591
|
+
table,
|
|
1592
|
+
view,
|
|
1593
|
+
parentField: preferredSelfLink,
|
|
1594
|
+
roots,
|
|
1595
|
+
flattenedVisibleNodes,
|
|
1596
|
+
totalNodeCount: nodeById.size,
|
|
1597
|
+
maxDepth
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
function isFormFieldVisible(item, values, table, unitData, formConfig) {
|
|
1601
|
+
if (!item.visible) return false;
|
|
1602
|
+
const extraRule = formConfig?.fieldRules?.[item.fieldId];
|
|
1603
|
+
const rules = item.visibleWhen ?? extraRule?.visibleWhen ?? [];
|
|
1604
|
+
if (rules.length === 0) return true;
|
|
1605
|
+
const conjunction = item.visibleWhenConjunction ?? extraRule?.visibleWhenConjunction ?? "and";
|
|
1606
|
+
const draftRecord = {
|
|
1607
|
+
id: "__form_draft__",
|
|
1608
|
+
createdTime: "",
|
|
1609
|
+
lastModifiedTime: "",
|
|
1610
|
+
cells: values
|
|
1611
|
+
};
|
|
1612
|
+
const outcomes = rules.map((rule) => {
|
|
1613
|
+
const refField = table.fields[rule.fieldId];
|
|
1614
|
+
if (!refField) return true;
|
|
1615
|
+
const rawVal = resolveBaseCellValue(unitData, table.id, draftRecord, refField);
|
|
1616
|
+
const dispVal = formatBaseCellValue(unitData, table.id, refField, rawVal);
|
|
1617
|
+
return matchesBaseFilterRule(rule, refField, rawVal, dispVal);
|
|
1618
|
+
});
|
|
1619
|
+
return conjunction === "or" ? outcomes.some(Boolean) : outcomes.every(Boolean);
|
|
1620
|
+
}
|
|
1621
|
+
function isFormFieldRequired(item, values, table, unitData, formConfig) {
|
|
1622
|
+
if (!isFormFieldVisible(item, values, table, unitData, formConfig)) {
|
|
1623
|
+
return false;
|
|
1624
|
+
}
|
|
1625
|
+
const extraRule = formConfig?.fieldRules?.[item.fieldId];
|
|
1626
|
+
const condReq = Boolean(item.conditionalRequired ?? extraRule?.conditionalRequired);
|
|
1627
|
+
return Boolean(item.required || condReq);
|
|
1628
|
+
}
|
|
1629
|
+
function resolveBaseDetailLayout(table, view, explicitLayout) {
|
|
1630
|
+
const layout = explicitLayout ?? view?.detailLayout ?? table.detailLayout;
|
|
1631
|
+
const columns = layout?.columns === 2 ? 2 : 1;
|
|
1632
|
+
const orderedFields = table.fieldOrder.map((fid) => table.fields[fid]).filter((f) => Boolean(f));
|
|
1633
|
+
if (!layout?.sections || layout.sections.length === 0) {
|
|
1634
|
+
return {
|
|
1635
|
+
columns,
|
|
1636
|
+
sections: [
|
|
1637
|
+
{
|
|
1638
|
+
id: "sec_default",
|
|
1639
|
+
title: "\u6838\u5FC3\u5B57\u6BB5\u4FE1\u606F",
|
|
1640
|
+
collapsed: false,
|
|
1641
|
+
fields: orderedFields
|
|
1642
|
+
}
|
|
1643
|
+
]
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
const assigned = /* @__PURE__ */ new Set();
|
|
1647
|
+
const sections = layout.sections.map((sec) => {
|
|
1648
|
+
const secFields = [];
|
|
1649
|
+
for (const fid of sec.fieldIds) {
|
|
1650
|
+
const f = table.fields[fid];
|
|
1651
|
+
if (f && !assigned.has(f.id)) {
|
|
1652
|
+
assigned.add(f.id);
|
|
1653
|
+
secFields.push(f);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
return {
|
|
1657
|
+
id: sec.id,
|
|
1658
|
+
title: sec.title || "\u672A\u547D\u540D\u5206\u7EC4",
|
|
1659
|
+
collapsed: Boolean(sec.collapsed),
|
|
1660
|
+
fields: secFields
|
|
1661
|
+
};
|
|
1662
|
+
});
|
|
1663
|
+
const remaining = orderedFields.filter((f) => !assigned.has(f.id));
|
|
1664
|
+
if (remaining.length > 0) {
|
|
1665
|
+
sections.push({
|
|
1666
|
+
id: "sec_remaining",
|
|
1667
|
+
title: "\u5176\u4ED6\u5B57\u6BB5",
|
|
1668
|
+
collapsed: false,
|
|
1669
|
+
fields: remaining
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
return { columns, sections };
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
// src/engine/base-automation-engine.ts
|
|
1676
|
+
import { createIdentifier, Disposable, generateRandomId, Tools } from "@univerjs/core";
|
|
1677
|
+
var MAX_AUTOMATION_RECURSION_DEPTH = 3;
|
|
1678
|
+
var IBaseAutomationService = createIdentifier(
|
|
1679
|
+
"univer.bases.automation.service"
|
|
1680
|
+
);
|
|
1681
|
+
var BaseAutomationService = class extends Disposable {
|
|
1682
|
+
setWebhookExecutor(executor) {
|
|
1683
|
+
this._webhookExecutor = executor;
|
|
1684
|
+
}
|
|
1685
|
+
getWebhookExecutor() {
|
|
1686
|
+
return this._webhookExecutor;
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
function nowTimestamp() {
|
|
1690
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
|
|
1691
|
+
}
|
|
1692
|
+
function syncLinkInTables(tables, sourceTableId, sourceRecordId, linkField, prevLinkedIds, nextLinkedIds, timestamp) {
|
|
1693
|
+
const targetTableId = linkField.config?.linkedTableId;
|
|
1694
|
+
const symFieldId = linkField.config?.symmetricFieldId;
|
|
1695
|
+
if (!targetTableId || !symFieldId) return;
|
|
1696
|
+
const targetTable = tables[targetTableId];
|
|
1697
|
+
const sourceTable = tables[sourceTableId];
|
|
1698
|
+
if (!targetTable || !sourceTable) return;
|
|
1699
|
+
const symField = targetTable.fields[symFieldId];
|
|
1700
|
+
if (!symField || symField.type !== "link") return;
|
|
1701
|
+
const nextSet = new Set(nextLinkedIds);
|
|
1702
|
+
for (const oldTargetId of prevLinkedIds) {
|
|
1703
|
+
if (nextSet.has(oldTargetId)) continue;
|
|
1704
|
+
const targetRec = targetTable.records[oldTargetId];
|
|
1705
|
+
if (!targetRec) continue;
|
|
1706
|
+
const curBackIds = normalizeLinkIds(targetRec.cells[symFieldId]);
|
|
1707
|
+
const filtered = curBackIds.filter((id) => id !== sourceRecordId);
|
|
1708
|
+
if (filtered.length !== curBackIds.length) {
|
|
1709
|
+
targetRec.cells[symFieldId] = filtered;
|
|
1710
|
+
targetRec.lastModifiedTime = timestamp;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
for (const newTargetId of nextLinkedIds) {
|
|
1714
|
+
const targetRec = targetTable.records[newTargetId];
|
|
1715
|
+
if (!targetRec) continue;
|
|
1716
|
+
const curBackIds = normalizeLinkIds(targetRec.cells[symFieldId]);
|
|
1717
|
+
if (symField.config?.allowMultiple === false) {
|
|
1718
|
+
for (const otherSourceId of curBackIds) {
|
|
1719
|
+
if (otherSourceId === sourceRecordId) continue;
|
|
1720
|
+
const otherSourceRec = sourceTable.records[otherSourceId];
|
|
1721
|
+
if (otherSourceRec) {
|
|
1722
|
+
otherSourceRec.cells[linkField.id] = normalizeLinkIds(
|
|
1723
|
+
otherSourceRec.cells[linkField.id]
|
|
1724
|
+
).filter((id) => id !== newTargetId);
|
|
1725
|
+
otherSourceRec.lastModifiedTime = timestamp;
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
targetRec.cells[symFieldId] = [sourceRecordId];
|
|
1729
|
+
targetRec.lastModifiedTime = timestamp;
|
|
1730
|
+
} else if (!curBackIds.includes(sourceRecordId)) {
|
|
1731
|
+
targetRec.cells[symFieldId] = [...curBackIds, sourceRecordId];
|
|
1732
|
+
targetRec.lastModifiedTime = timestamp;
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
function findFieldByIdOrName(table, key) {
|
|
1737
|
+
return table.fields[key] ?? Object.values(table.fields).find((f) => f.name === key);
|
|
1738
|
+
}
|
|
1739
|
+
function evaluateAutomationConditions(conditions, conjunction, unitData, table, record) {
|
|
1740
|
+
if (!conditions || conditions.length === 0) return true;
|
|
1741
|
+
if (!record) return false;
|
|
1742
|
+
const mode = conjunction ?? "and";
|
|
1743
|
+
const outcomes = conditions.map((rule) => {
|
|
1744
|
+
const field = findFieldByIdOrName(table, rule.fieldId);
|
|
1745
|
+
if (!field) return true;
|
|
1746
|
+
const rawVal = resolveBaseCellValue(unitData, table.id, record, field);
|
|
1747
|
+
const dispVal = formatBaseCellValue(unitData, table.id, field, rawVal);
|
|
1748
|
+
return matchesBaseFilterRule(rule, field, rawVal, dispVal);
|
|
1749
|
+
});
|
|
1750
|
+
return mode === "or" ? outcomes.some(Boolean) : outcomes.every(Boolean);
|
|
1751
|
+
}
|
|
1752
|
+
function resolveWebhookPath(payload, path) {
|
|
1753
|
+
if (!payload || typeof payload !== "object") return "";
|
|
1754
|
+
const parts = path.split(".").filter(Boolean);
|
|
1755
|
+
let cur = payload;
|
|
1756
|
+
for (const p of parts) {
|
|
1757
|
+
if (cur && typeof cur === "object" && p in cur) {
|
|
1758
|
+
cur = cur[p];
|
|
1759
|
+
} else {
|
|
1760
|
+
return "";
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
return cur;
|
|
1764
|
+
}
|
|
1765
|
+
function interpolateAutomationString(template, unitData, table, record, webhookPayload) {
|
|
1766
|
+
if (!template) return "";
|
|
1767
|
+
if (template.startsWith("=") && record) {
|
|
1768
|
+
const evaluated = evaluateBaseFormula(template.slice(1).trim(), record, table, unitData);
|
|
1769
|
+
return evaluated === null || evaluated === void 0 ? "" : String(evaluated);
|
|
1770
|
+
}
|
|
1771
|
+
return template.replace(/\{([^{}]+)\}/g, (_match, rawToken) => {
|
|
1772
|
+
const token = rawToken.trim();
|
|
1773
|
+
if (token.startsWith("webhook.")) {
|
|
1774
|
+
const wVal = resolveWebhookPath(webhookPayload, token.slice("webhook.".length));
|
|
1775
|
+
return wVal === null || wVal === void 0 ? "" : String(wVal);
|
|
1776
|
+
}
|
|
1777
|
+
if (!record) return "";
|
|
1778
|
+
if (token === "recordId" || token === "_id") return record.id;
|
|
1779
|
+
const field = findFieldByIdOrName(table, token);
|
|
1780
|
+
if (!field) return "";
|
|
1781
|
+
const val = resolveBaseCellValue(unitData, table.id, record, field);
|
|
1782
|
+
return formatBaseCellValue(unitData, table.id, field, val);
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
function interpolateAutomationCellValue(rawTemplate, targetField, unitData, sourceTable, sourceRecord, webhookPayload) {
|
|
1786
|
+
if (typeof rawTemplate !== "string") {
|
|
1787
|
+
return Tools.deepClone(rawTemplate);
|
|
1788
|
+
}
|
|
1789
|
+
if (rawTemplate.startsWith("=") && sourceRecord) {
|
|
1790
|
+
const res = evaluateBaseFormula(rawTemplate.slice(1).trim(), sourceRecord, sourceTable, unitData);
|
|
1791
|
+
if (targetField && (targetField.type === "number" || targetField.type === "currency" || targetField.type === "percent" || targetField.type === "rating")) {
|
|
1792
|
+
return toNumericValue(res) ?? 0;
|
|
1793
|
+
}
|
|
1794
|
+
if (targetField?.type === "checkbox") {
|
|
1795
|
+
return Boolean(res);
|
|
1796
|
+
}
|
|
1797
|
+
return res;
|
|
1798
|
+
}
|
|
1799
|
+
const exactMatch = /^\{([^{}]+)\}$/.exec(rawTemplate.trim());
|
|
1800
|
+
if (exactMatch && sourceRecord) {
|
|
1801
|
+
const token = exactMatch[1].trim();
|
|
1802
|
+
if (token.startsWith("webhook.")) {
|
|
1803
|
+
const wVal = resolveWebhookPath(webhookPayload, token.slice("webhook.".length));
|
|
1804
|
+
return wVal ?? "";
|
|
1805
|
+
}
|
|
1806
|
+
if (token === "recordId" || token === "_id") {
|
|
1807
|
+
return targetField?.type === "link" ? [sourceRecord.id] : sourceRecord.id;
|
|
1808
|
+
}
|
|
1809
|
+
const srcField = findFieldByIdOrName(sourceTable, token);
|
|
1810
|
+
if (srcField) {
|
|
1811
|
+
const resolved = resolveBaseCellValue(unitData, sourceTable.id, sourceRecord, srcField);
|
|
1812
|
+
if (targetField && targetField.type === srcField.type) {
|
|
1813
|
+
return Tools.deepClone(resolved);
|
|
1814
|
+
}
|
|
1815
|
+
if (targetField && (targetField.type === "number" || targetField.type === "currency" || targetField.type === "percent" || targetField.type === "rating")) {
|
|
1816
|
+
const num = toNumericValue(resolved);
|
|
1817
|
+
if (num !== null) return num;
|
|
1818
|
+
}
|
|
1819
|
+
if (targetField?.type === "checkbox") {
|
|
1820
|
+
return Boolean(resolved);
|
|
1821
|
+
}
|
|
1822
|
+
return formatBaseCellValue(unitData, sourceTable.id, srcField, resolved);
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
const interpolated = interpolateAutomationString(
|
|
1826
|
+
rawTemplate,
|
|
1827
|
+
unitData,
|
|
1828
|
+
sourceTable,
|
|
1829
|
+
sourceRecord,
|
|
1830
|
+
webhookPayload
|
|
1831
|
+
);
|
|
1832
|
+
if (targetField && (targetField.type === "number" || targetField.type === "currency" || targetField.type === "percent" || targetField.type === "rating")) {
|
|
1833
|
+
const n = toNumericValue(interpolated);
|
|
1834
|
+
if (n !== null) return n;
|
|
1835
|
+
}
|
|
1836
|
+
if (targetField?.type === "checkbox") {
|
|
1837
|
+
const lower = interpolated.trim().toLowerCase();
|
|
1838
|
+
return lower === "true" || lower === "1" || lower === "\u662F";
|
|
1839
|
+
}
|
|
1840
|
+
return interpolated;
|
|
1841
|
+
}
|
|
1842
|
+
function interpolateStructuredPayload(payload, unitData, table, record, webhookPayload) {
|
|
1843
|
+
if (typeof payload === "string") {
|
|
1844
|
+
const str = interpolateAutomationString(payload, unitData, table, record, webhookPayload);
|
|
1845
|
+
const trimmed = str.trim();
|
|
1846
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
1847
|
+
try {
|
|
1848
|
+
return JSON.parse(trimmed);
|
|
1849
|
+
} catch {
|
|
1850
|
+
return str;
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
return str;
|
|
1854
|
+
}
|
|
1855
|
+
if (Array.isArray(payload)) {
|
|
1856
|
+
return payload.map(
|
|
1857
|
+
(item) => interpolateStructuredPayload(item, unitData, table, record, webhookPayload)
|
|
1858
|
+
);
|
|
1859
|
+
}
|
|
1860
|
+
if (payload && typeof payload === "object") {
|
|
1861
|
+
const out = {};
|
|
1862
|
+
for (const [k, v] of Object.entries(payload)) {
|
|
1863
|
+
out[k] = interpolateStructuredPayload(v, unitData, table, record, webhookPayload);
|
|
1864
|
+
}
|
|
1865
|
+
return out;
|
|
1866
|
+
}
|
|
1867
|
+
return payload;
|
|
1868
|
+
}
|
|
1869
|
+
function normalizeAutomationSteps(rule) {
|
|
1870
|
+
if (rule.steps && rule.steps.length > 0) {
|
|
1871
|
+
return rule.steps;
|
|
1872
|
+
}
|
|
1873
|
+
if (!rule.action) return [];
|
|
1874
|
+
if (rule.action === "updateRecord") {
|
|
1875
|
+
const fieldUpdates = rule.actionConfig?.fieldUpdates ?? rule.actionConfig?.cells ?? {};
|
|
1876
|
+
return [
|
|
1877
|
+
{
|
|
1878
|
+
id: `${rule.id}_legacy_update`,
|
|
1879
|
+
type: "updateRecord",
|
|
1880
|
+
fieldUpdates
|
|
1881
|
+
}
|
|
1882
|
+
];
|
|
1883
|
+
}
|
|
1884
|
+
if (rule.action === "webhook" || rule.action === "httpWebhook") {
|
|
1885
|
+
return [
|
|
1886
|
+
{
|
|
1887
|
+
id: `${rule.id}_legacy_webhook`,
|
|
1888
|
+
type: "httpWebhook",
|
|
1889
|
+
webhookUrl: String(rule.actionConfig?.url ?? "https://webhook.local/automations"),
|
|
1890
|
+
webhookMethod: rule.actionConfig?.method ?? "POST",
|
|
1891
|
+
webhookBodyTemplate: rule.actionConfig?.body
|
|
1892
|
+
}
|
|
1893
|
+
];
|
|
1894
|
+
}
|
|
1895
|
+
return [
|
|
1896
|
+
{
|
|
1897
|
+
id: `${rule.id}_legacy_notify`,
|
|
1898
|
+
type: "notify",
|
|
1899
|
+
notifyChannel: String(rule.actionConfig?.channel ?? "\u7CFB\u7EDF\u901A\u77E5"),
|
|
1900
|
+
notifyMessage: String(rule.actionConfig?.message ?? rule.name)
|
|
1901
|
+
}
|
|
1902
|
+
];
|
|
1903
|
+
}
|
|
1904
|
+
function cellsEqual(a, b) {
|
|
1905
|
+
if (a === b) return true;
|
|
1906
|
+
if ((a === null || a === void 0 || a === "") && (b === null || b === void 0 || b === "")) {
|
|
1907
|
+
return true;
|
|
1908
|
+
}
|
|
1909
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
1910
|
+
}
|
|
1911
|
+
function doesAutomationTriggerMatch(rule, event, unitData, table, record) {
|
|
1912
|
+
if (!rule.enabled && event.ruleId !== rule.id) {
|
|
1913
|
+
return { triggerMatched: false, conditionsMatched: false };
|
|
1914
|
+
}
|
|
1915
|
+
if (rule.tableId !== event.tableId) {
|
|
1916
|
+
return { triggerMatched: false, conditionsMatched: false };
|
|
1917
|
+
}
|
|
1918
|
+
if (event.ruleId && event.ruleId !== rule.id) {
|
|
1919
|
+
return { triggerMatched: false, conditionsMatched: false };
|
|
1920
|
+
}
|
|
1921
|
+
if (event.trigger === "manual" && (!event.ruleId || event.ruleId === rule.id)) {
|
|
1922
|
+
const condOk = evaluateAutomationConditions(
|
|
1923
|
+
rule.conditions,
|
|
1924
|
+
rule.conditionConjunction,
|
|
1925
|
+
unitData,
|
|
1926
|
+
table,
|
|
1927
|
+
record
|
|
1928
|
+
);
|
|
1929
|
+
return { triggerMatched: true, conditionsMatched: condOk };
|
|
1930
|
+
}
|
|
1931
|
+
let triggerMatched = false;
|
|
1932
|
+
switch (rule.trigger) {
|
|
1933
|
+
case "recordCreated":
|
|
1934
|
+
triggerMatched = event.trigger === "recordCreated";
|
|
1935
|
+
break;
|
|
1936
|
+
case "recordUpdated":
|
|
1937
|
+
triggerMatched = event.trigger === "recordUpdated";
|
|
1938
|
+
break;
|
|
1939
|
+
case "fieldChanged": {
|
|
1940
|
+
if (event.trigger === "recordUpdated" || event.trigger === "fieldChanged" || event.trigger === "recordCreated") {
|
|
1941
|
+
const watchedIds = [
|
|
1942
|
+
...rule.triggerFieldIds ?? [],
|
|
1943
|
+
...rule.triggerFieldId ? [rule.triggerFieldId] : []
|
|
1944
|
+
];
|
|
1945
|
+
if (watchedIds.length === 0) {
|
|
1946
|
+
triggerMatched = (event.changedFieldIds?.length ?? 0) > 0 || event.trigger === "recordCreated";
|
|
1947
|
+
} else {
|
|
1948
|
+
const changedSet = new Set(event.changedFieldIds ?? []);
|
|
1949
|
+
triggerMatched = watchedIds.some((fid) => {
|
|
1950
|
+
const resolvedField = findFieldByIdOrName(table, fid);
|
|
1951
|
+
const actualId = resolvedField?.id ?? fid;
|
|
1952
|
+
if (!changedSet.has(actualId) && !changedSet.has(fid)) {
|
|
1953
|
+
if (event.trigger === "recordCreated" && record) {
|
|
1954
|
+
return record.cells[actualId] !== void 0 && record.cells[actualId] !== "";
|
|
1955
|
+
}
|
|
1956
|
+
return false;
|
|
1957
|
+
}
|
|
1958
|
+
if (event.previousCells && record) {
|
|
1959
|
+
return !cellsEqual(event.previousCells[actualId], record.cells[actualId]);
|
|
1960
|
+
}
|
|
1961
|
+
return true;
|
|
1962
|
+
});
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
break;
|
|
1966
|
+
}
|
|
1967
|
+
case "conditionMatched": {
|
|
1968
|
+
if (event.trigger === "conditionMatched" || event.trigger === "recordCreated" || event.trigger === "recordUpdated") {
|
|
1969
|
+
const nowMatched = evaluateAutomationConditions(
|
|
1970
|
+
rule.conditions,
|
|
1971
|
+
rule.conditionConjunction,
|
|
1972
|
+
unitData,
|
|
1973
|
+
table,
|
|
1974
|
+
record
|
|
1975
|
+
);
|
|
1976
|
+
if (event.previousCells && record && event.trigger === "recordUpdated" && rule.conditions?.length) {
|
|
1977
|
+
const prevRec = {
|
|
1978
|
+
...record,
|
|
1979
|
+
cells: event.previousCells
|
|
1980
|
+
};
|
|
1981
|
+
const prevMatched = evaluateAutomationConditions(
|
|
1982
|
+
rule.conditions,
|
|
1983
|
+
rule.conditionConjunction,
|
|
1984
|
+
unitData,
|
|
1985
|
+
table,
|
|
1986
|
+
prevRec
|
|
1987
|
+
);
|
|
1988
|
+
if (prevMatched && nowMatched) {
|
|
1989
|
+
return { triggerMatched: false, conditionsMatched: false };
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
return { triggerMatched: true, conditionsMatched: nowMatched };
|
|
1993
|
+
}
|
|
1994
|
+
break;
|
|
1995
|
+
}
|
|
1996
|
+
case "fieldMatches": {
|
|
1997
|
+
if ((event.trigger === "recordCreated" || event.trigger === "recordUpdated" || event.trigger === "fieldChanged") && record) {
|
|
1998
|
+
if (!rule.triggerFieldId) {
|
|
1999
|
+
triggerMatched = true;
|
|
2000
|
+
} else {
|
|
2001
|
+
const f = findFieldByIdOrName(table, rule.triggerFieldId);
|
|
2002
|
+
if (f) {
|
|
2003
|
+
if (event.changedFieldIds && event.changedFieldIds.length > 0 && !event.changedFieldIds.includes(f.id)) {
|
|
2004
|
+
triggerMatched = false;
|
|
2005
|
+
} else {
|
|
2006
|
+
const rawVal = resolveBaseCellValue(unitData, table.id, record, f);
|
|
2007
|
+
const dispVal = formatBaseCellValue(unitData, table.id, f, rawVal);
|
|
2008
|
+
triggerMatched = matchesBaseFilterRule(
|
|
2009
|
+
{
|
|
2010
|
+
id: "legacy_match",
|
|
2011
|
+
fieldId: f.id,
|
|
2012
|
+
operator: "is",
|
|
2013
|
+
value: rule.triggerValue
|
|
2014
|
+
},
|
|
2015
|
+
f,
|
|
2016
|
+
rawVal,
|
|
2017
|
+
dispVal
|
|
2018
|
+
);
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
break;
|
|
2024
|
+
}
|
|
2025
|
+
case "scheduled":
|
|
2026
|
+
triggerMatched = event.trigger === "scheduled";
|
|
2027
|
+
break;
|
|
2028
|
+
case "webhookReceived":
|
|
2029
|
+
triggerMatched = event.trigger === "webhookReceived";
|
|
2030
|
+
break;
|
|
2031
|
+
default:
|
|
2032
|
+
triggerMatched = false;
|
|
2033
|
+
}
|
|
2034
|
+
if (!triggerMatched) {
|
|
2035
|
+
return { triggerMatched: false, conditionsMatched: false };
|
|
2036
|
+
}
|
|
2037
|
+
const conditionsMatched = evaluateAutomationConditions(
|
|
2038
|
+
rule.conditions,
|
|
2039
|
+
rule.conditionConjunction,
|
|
2040
|
+
unitData,
|
|
2041
|
+
table,
|
|
2042
|
+
record
|
|
2043
|
+
);
|
|
2044
|
+
return { triggerMatched: true, conditionsMatched };
|
|
2045
|
+
}
|
|
2046
|
+
function applyCellsUpdateToRecord(workingUnit, table, record, rawUpdates, sourceTable, sourceRecord, webhookPayload, timestamp) {
|
|
2047
|
+
const previousCells = Tools.deepClone(record.cells);
|
|
2048
|
+
const changedFieldIds = [];
|
|
2049
|
+
for (const [key, rawTemplate] of Object.entries(rawUpdates)) {
|
|
2050
|
+
const targetField = findFieldByIdOrName(table, key);
|
|
2051
|
+
if (!targetField || isComputedBaseField(targetField.type)) continue;
|
|
2052
|
+
const computedVal = interpolateAutomationCellValue(
|
|
2053
|
+
rawTemplate,
|
|
2054
|
+
targetField,
|
|
2055
|
+
workingUnit,
|
|
2056
|
+
sourceTable,
|
|
2057
|
+
sourceRecord,
|
|
2058
|
+
webhookPayload
|
|
2059
|
+
);
|
|
2060
|
+
if (targetField.type === "link") {
|
|
2061
|
+
const prevIds = normalizeLinkIds(record.cells[targetField.id]);
|
|
2062
|
+
const rawNextIds = normalizeLinkIds(computedVal);
|
|
2063
|
+
const nextIds = targetField.config?.allowMultiple === false ? rawNextIds.slice(0, 1) : rawNextIds;
|
|
2064
|
+
if (!cellsEqual(prevIds, nextIds)) {
|
|
2065
|
+
record.cells[targetField.id] = nextIds;
|
|
2066
|
+
syncLinkInTables(
|
|
2067
|
+
workingUnit.tables,
|
|
2068
|
+
table.id,
|
|
2069
|
+
record.id,
|
|
2070
|
+
targetField,
|
|
2071
|
+
prevIds,
|
|
2072
|
+
nextIds,
|
|
2073
|
+
timestamp
|
|
2074
|
+
);
|
|
2075
|
+
changedFieldIds.push(targetField.id);
|
|
2076
|
+
}
|
|
2077
|
+
} else if (!cellsEqual(record.cells[targetField.id], computedVal)) {
|
|
2078
|
+
record.cells[targetField.id] = computedVal;
|
|
2079
|
+
changedFieldIds.push(targetField.id);
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
if (changedFieldIds.length > 0) {
|
|
2083
|
+
record.lastModifiedTime = timestamp;
|
|
2084
|
+
}
|
|
2085
|
+
return { changedFieldIds, previousCells };
|
|
2086
|
+
}
|
|
2087
|
+
function buildWebhookRequestForStep(step, rule, workingUnit, currentTable, currentRecord, webhookPayload) {
|
|
2088
|
+
const url = interpolateAutomationString(
|
|
2089
|
+
step.webhookUrl || "https://webhook.local/bases",
|
|
2090
|
+
workingUnit,
|
|
2091
|
+
currentTable,
|
|
2092
|
+
currentRecord,
|
|
2093
|
+
webhookPayload
|
|
2094
|
+
);
|
|
2095
|
+
const method = step.webhookMethod || "POST";
|
|
2096
|
+
let headers;
|
|
2097
|
+
if (step.webhookHeaders) {
|
|
2098
|
+
headers = {};
|
|
2099
|
+
for (const [hk, hv] of Object.entries(step.webhookHeaders)) {
|
|
2100
|
+
headers[hk] = interpolateAutomationString(
|
|
2101
|
+
hv,
|
|
2102
|
+
workingUnit,
|
|
2103
|
+
currentTable,
|
|
2104
|
+
currentRecord,
|
|
2105
|
+
webhookPayload
|
|
2106
|
+
);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
const body = step.webhookBodyTemplate !== void 0 ? interpolateStructuredPayload(
|
|
2110
|
+
step.webhookBodyTemplate,
|
|
2111
|
+
workingUnit,
|
|
2112
|
+
currentTable,
|
|
2113
|
+
currentRecord,
|
|
2114
|
+
webhookPayload
|
|
2115
|
+
) : {
|
|
2116
|
+
ruleId: rule.id,
|
|
2117
|
+
ruleName: rule.name,
|
|
2118
|
+
tableId: currentTable.id,
|
|
2119
|
+
recordId: currentRecord?.id ?? null,
|
|
2120
|
+
cells: currentRecord ? Tools.deepClone(currentRecord.cells) : {}
|
|
2121
|
+
};
|
|
2122
|
+
return { url, method, headers, body };
|
|
2123
|
+
}
|
|
2124
|
+
function pushAutomationLog(workingUnit, log, maxLogs = 200) {
|
|
2125
|
+
if (!workingUnit.automationLogs) {
|
|
2126
|
+
workingUnit.automationLogs = [];
|
|
2127
|
+
}
|
|
2128
|
+
workingUnit.automationLogs.push(log);
|
|
2129
|
+
if (workingUnit.automationLogs.length > maxLogs) {
|
|
2130
|
+
workingUnit.automationLogs = workingUnit.automationLogs.slice(
|
|
2131
|
+
workingUnit.automationLogs.length - maxLogs
|
|
2132
|
+
);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
function runBaseAutomationsInPlaceSync(workingUnit, initialEvent, options) {
|
|
2136
|
+
const logs = [];
|
|
2137
|
+
const allQueuedWebhooks = [];
|
|
2138
|
+
const executedRuleIds = [];
|
|
2139
|
+
const timestamp = options?.timestamp ?? nowTimestamp();
|
|
2140
|
+
const maxLogs = options?.maxLogs ?? 200;
|
|
2141
|
+
const queue = [
|
|
2142
|
+
{ ...initialEvent, depth: initialEvent.depth ?? 1 }
|
|
2143
|
+
];
|
|
2144
|
+
while (queue.length > 0) {
|
|
2145
|
+
const event = queue.shift();
|
|
2146
|
+
const depth = event.depth ?? 1;
|
|
2147
|
+
const table = workingUnit.tables[event.tableId];
|
|
2148
|
+
if (!table) continue;
|
|
2149
|
+
const record = event.recordId ? table.records[event.recordId] : void 0;
|
|
2150
|
+
const rules = workingUnit.automations ?? [];
|
|
2151
|
+
for (const rule of rules) {
|
|
2152
|
+
const match = doesAutomationTriggerMatch(rule, event, workingUnit, table, record);
|
|
2153
|
+
if (!match.triggerMatched) continue;
|
|
2154
|
+
if (depth > MAX_AUTOMATION_RECURSION_DEPTH) {
|
|
2155
|
+
const skipLog = {
|
|
2156
|
+
id: `alog_${generateRandomId(6)}`,
|
|
2157
|
+
ruleId: rule.id,
|
|
2158
|
+
ruleName: rule.name,
|
|
2159
|
+
tableId: table.id,
|
|
2160
|
+
recordId: record?.id,
|
|
2161
|
+
trigger: event.trigger,
|
|
2162
|
+
status: "skipped",
|
|
2163
|
+
executedSteps: 0,
|
|
2164
|
+
timestamp,
|
|
2165
|
+
summary: `\u9012\u5F52\u6DF1\u5EA6\u8D85\u8FC7\u4E0A\u9650 (${MAX_AUTOMATION_RECURSION_DEPTH})\uFF0C\u5DF2\u81EA\u52A8\u62E6\u622A\u9632\u6B62\u6B7B\u5FAA\u73AF`
|
|
2166
|
+
};
|
|
2167
|
+
logs.push(skipLog);
|
|
2168
|
+
pushAutomationLog(workingUnit, skipLog, maxLogs);
|
|
2169
|
+
continue;
|
|
2170
|
+
}
|
|
2171
|
+
if (!match.conditionsMatched) {
|
|
2172
|
+
const skipLog = {
|
|
2173
|
+
id: `alog_${generateRandomId(6)}`,
|
|
2174
|
+
ruleId: rule.id,
|
|
2175
|
+
ruleName: rule.name,
|
|
2176
|
+
tableId: table.id,
|
|
2177
|
+
recordId: record?.id,
|
|
2178
|
+
trigger: event.trigger,
|
|
2179
|
+
status: "skipped",
|
|
2180
|
+
executedSteps: 0,
|
|
2181
|
+
timestamp,
|
|
2182
|
+
summary: "\u89E6\u53D1\u5668\u5DF2\u547D\u4E2D\uFF0C\u4F46\u672A\u6EE1\u8DB3\u524D\u7F6E\u8FC7\u6EE4\u6761\u4EF6\uFF0C\u8DF3\u8FC7\u6267\u884C"
|
|
2183
|
+
};
|
|
2184
|
+
logs.push(skipLog);
|
|
2185
|
+
pushAutomationLog(workingUnit, skipLog, maxLogs);
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
const steps = normalizeAutomationSteps(rule);
|
|
2189
|
+
let executedSteps = 0;
|
|
2190
|
+
const summaries = [];
|
|
2191
|
+
const ruleQueuedWebhooks = [];
|
|
2192
|
+
const cascades = [];
|
|
2193
|
+
let errorSummary = null;
|
|
2194
|
+
const execStepList = (stepList, ctxTable, ctxRecord) => {
|
|
2195
|
+
for (const step of stepList) {
|
|
2196
|
+
if (errorSummary) return;
|
|
2197
|
+
switch (step.type) {
|
|
2198
|
+
case "updateRecord": {
|
|
2199
|
+
if (!ctxRecord || !step.fieldUpdates) break;
|
|
2200
|
+
executedSteps += 1;
|
|
2201
|
+
const { changedFieldIds, previousCells } = applyCellsUpdateToRecord(
|
|
2202
|
+
workingUnit,
|
|
2203
|
+
ctxTable,
|
|
2204
|
+
ctxRecord,
|
|
2205
|
+
step.fieldUpdates,
|
|
2206
|
+
ctxTable,
|
|
2207
|
+
ctxRecord,
|
|
2208
|
+
event.webhookPayload,
|
|
2209
|
+
timestamp
|
|
2210
|
+
);
|
|
2211
|
+
summaries.push(`\u4FEE\u6539\u8BB0\u5F55 (${changedFieldIds.length} \u4E2A\u5B57\u6BB5)`);
|
|
2212
|
+
if (changedFieldIds.length > 0) {
|
|
2213
|
+
cascades.push({
|
|
2214
|
+
event: {
|
|
2215
|
+
trigger: "recordUpdated",
|
|
2216
|
+
tableId: ctxTable.id,
|
|
2217
|
+
recordId: ctxRecord.id,
|
|
2218
|
+
changedFieldIds,
|
|
2219
|
+
previousCells,
|
|
2220
|
+
depth: depth + 1
|
|
2221
|
+
}
|
|
2222
|
+
});
|
|
2223
|
+
}
|
|
2224
|
+
break;
|
|
2225
|
+
}
|
|
2226
|
+
case "createLinkedRecord": {
|
|
2227
|
+
const targetTableId = step.targetTableId;
|
|
2228
|
+
const targetTable = targetTableId ? workingUnit.tables[targetTableId] : void 0;
|
|
2229
|
+
if (!targetTable) {
|
|
2230
|
+
errorSummary = `\u76EE\u6807\u5173\u8054\u8868\u4E0D\u5B58\u5728: ${targetTableId ?? "\u672A\u6307\u5B9A"}`;
|
|
2231
|
+
return;
|
|
2232
|
+
}
|
|
2233
|
+
executedSteps += 1;
|
|
2234
|
+
const newRecId = `rec_auto_${generateRandomId(6)}`;
|
|
2235
|
+
const autoNum = targetTable.nextAutoNumber ?? targetTable.recordOrder.length + 1;
|
|
2236
|
+
targetTable.nextAutoNumber = autoNum + 1;
|
|
2237
|
+
const newRec = {
|
|
2238
|
+
id: newRecId,
|
|
2239
|
+
autoNumber: autoNum,
|
|
2240
|
+
createdTime: timestamp,
|
|
2241
|
+
lastModifiedTime: timestamp,
|
|
2242
|
+
createdBy: "\u81EA\u52A8\u5316\u5F15\u64CE",
|
|
2243
|
+
lastModifiedBy: "\u81EA\u52A8\u5316\u5F15\u64CE",
|
|
2244
|
+
cells: {}
|
|
2245
|
+
};
|
|
2246
|
+
targetTable.records[newRecId] = newRec;
|
|
2247
|
+
targetTable.recordOrder.push(newRecId);
|
|
2248
|
+
if (step.recordCells) {
|
|
2249
|
+
applyCellsUpdateToRecord(
|
|
2250
|
+
workingUnit,
|
|
2251
|
+
targetTable,
|
|
2252
|
+
newRec,
|
|
2253
|
+
step.recordCells,
|
|
2254
|
+
ctxTable,
|
|
2255
|
+
ctxRecord,
|
|
2256
|
+
event.webhookPayload,
|
|
2257
|
+
timestamp
|
|
2258
|
+
);
|
|
2259
|
+
}
|
|
2260
|
+
if (ctxRecord) {
|
|
2261
|
+
const explicitFieldId = step.linkBackFieldId;
|
|
2262
|
+
const srcLinkField = explicitFieldId ? ctxTable.fields[explicitFieldId] : Object.values(ctxTable.fields).find(
|
|
2263
|
+
(f) => f.type === "link" && f.config?.linkedTableId === targetTable.id
|
|
2264
|
+
);
|
|
2265
|
+
const tgtLinkField = explicitFieldId && targetTable.fields[explicitFieldId] ? targetTable.fields[explicitFieldId] : Object.values(targetTable.fields).find(
|
|
2266
|
+
(f) => f.type === "link" && f.config?.linkedTableId === ctxTable.id
|
|
2267
|
+
);
|
|
2268
|
+
if (srcLinkField && srcLinkField.type === "link" && srcLinkField.config?.linkedTableId === targetTable.id) {
|
|
2269
|
+
const prevIds = normalizeLinkIds(ctxRecord.cells[srcLinkField.id]);
|
|
2270
|
+
const nextIds = srcLinkField.config?.allowMultiple === false ? [newRecId] : Array.from(/* @__PURE__ */ new Set([...prevIds, newRecId]));
|
|
2271
|
+
ctxRecord.cells[srcLinkField.id] = nextIds;
|
|
2272
|
+
ctxRecord.lastModifiedTime = timestamp;
|
|
2273
|
+
syncLinkInTables(
|
|
2274
|
+
workingUnit.tables,
|
|
2275
|
+
ctxTable.id,
|
|
2276
|
+
ctxRecord.id,
|
|
2277
|
+
srcLinkField,
|
|
2278
|
+
prevIds,
|
|
2279
|
+
nextIds,
|
|
2280
|
+
timestamp
|
|
2281
|
+
);
|
|
2282
|
+
} else if (tgtLinkField && tgtLinkField.type === "link" && tgtLinkField.config?.linkedTableId === ctxTable.id) {
|
|
2283
|
+
const prevIds = normalizeLinkIds(newRec.cells[tgtLinkField.id]);
|
|
2284
|
+
const nextIds = tgtLinkField.config?.allowMultiple === false ? [ctxRecord.id] : Array.from(/* @__PURE__ */ new Set([...prevIds, ctxRecord.id]));
|
|
2285
|
+
newRec.cells[tgtLinkField.id] = nextIds;
|
|
2286
|
+
syncLinkInTables(
|
|
2287
|
+
workingUnit.tables,
|
|
2288
|
+
targetTable.id,
|
|
2289
|
+
newRecId,
|
|
2290
|
+
tgtLinkField,
|
|
2291
|
+
prevIds,
|
|
2292
|
+
nextIds,
|
|
2293
|
+
timestamp
|
|
2294
|
+
);
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
summaries.push(`\u65B0\u5EFA\u5173\u8054\u8BB0\u5F55 -> ${targetTable.name}(${newRecId})`);
|
|
2298
|
+
cascades.push({
|
|
2299
|
+
event: {
|
|
2300
|
+
trigger: "recordCreated",
|
|
2301
|
+
tableId: targetTable.id,
|
|
2302
|
+
recordId: newRecId,
|
|
2303
|
+
changedFieldIds: Object.keys(newRec.cells),
|
|
2304
|
+
depth: depth + 1
|
|
2305
|
+
}
|
|
2306
|
+
});
|
|
2307
|
+
break;
|
|
2308
|
+
}
|
|
2309
|
+
case "ifElse": {
|
|
2310
|
+
executedSteps += 1;
|
|
2311
|
+
const branchMatch = evaluateAutomationConditions(
|
|
2312
|
+
step.conditions,
|
|
2313
|
+
step.conditionConjunction,
|
|
2314
|
+
workingUnit,
|
|
2315
|
+
ctxTable,
|
|
2316
|
+
ctxRecord
|
|
2317
|
+
);
|
|
2318
|
+
summaries.push(branchMatch ? "If\u6761\u4EF6\u6210\u7ACB -> Then\u5206\u652F" : "If\u6761\u4EF6\u4E0D\u6210\u7ACB -> Else\u5206\u652F");
|
|
2319
|
+
if (branchMatch) {
|
|
2320
|
+
execStepList(step.thenSteps ?? [], ctxTable, ctxRecord);
|
|
2321
|
+
} else {
|
|
2322
|
+
execStepList(step.elseSteps ?? [], ctxTable, ctxRecord);
|
|
2323
|
+
}
|
|
2324
|
+
break;
|
|
2325
|
+
}
|
|
2326
|
+
case "loopRecords": {
|
|
2327
|
+
const loopTbl = workingUnit.tables[step.loopTableId || ctxTable.id];
|
|
2328
|
+
if (!loopTbl) break;
|
|
2329
|
+
executedSteps += 1;
|
|
2330
|
+
const matchedRecords = loopTbl.recordOrder.map((rid) => loopTbl.records[rid]).filter(
|
|
2331
|
+
(r) => Boolean(r) && evaluateAutomationConditions(
|
|
2332
|
+
step.loopConditions,
|
|
2333
|
+
step.loopConditionConjunction,
|
|
2334
|
+
workingUnit,
|
|
2335
|
+
loopTbl,
|
|
2336
|
+
r
|
|
2337
|
+
)
|
|
2338
|
+
);
|
|
2339
|
+
for (const loopRec of matchedRecords) {
|
|
2340
|
+
execStepList(step.loopSteps ?? [], loopTbl, loopRec);
|
|
2341
|
+
}
|
|
2342
|
+
summaries.push(`\u5FAA\u73AF\u5904\u7406 ${matchedRecords.length} \u6761\u8BB0\u5F55`);
|
|
2343
|
+
break;
|
|
2344
|
+
}
|
|
2345
|
+
case "httpWebhook": {
|
|
2346
|
+
executedSteps += 1;
|
|
2347
|
+
const req = buildWebhookRequestForStep(
|
|
2348
|
+
step,
|
|
2349
|
+
rule,
|
|
2350
|
+
workingUnit,
|
|
2351
|
+
ctxTable,
|
|
2352
|
+
ctxRecord,
|
|
2353
|
+
event.webhookPayload
|
|
2354
|
+
);
|
|
2355
|
+
if (options?.webhookExecutor) {
|
|
2356
|
+
try {
|
|
2357
|
+
const resOrPromise = options.webhookExecutor(req);
|
|
2358
|
+
if (resOrPromise && typeof resOrPromise.then === "function") {
|
|
2359
|
+
summaries.push(`Webhook ${req.method} ${req.url} (\u5F02\u6B65\u5DF2\u6D3E\u53D1)`);
|
|
2360
|
+
void resOrPromise.catch(() => {
|
|
2361
|
+
});
|
|
2362
|
+
} else {
|
|
2363
|
+
const syncRes = resOrPromise;
|
|
2364
|
+
if (syncRes.status >= 400) {
|
|
2365
|
+
errorSummary = `Webhook \u54CD\u5E94\u5F02\u5E38 HTTP ${syncRes.status}`;
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
summaries.push(`Webhook ${req.method} ${req.url} -> ${syncRes.status}`);
|
|
2369
|
+
}
|
|
2370
|
+
} catch (err) {
|
|
2371
|
+
errorSummary = err instanceof Error ? err.message : "Webhook \u6267\u884C\u5F02\u5E38";
|
|
2372
|
+
return;
|
|
2373
|
+
}
|
|
2374
|
+
} else {
|
|
2375
|
+
const queued = {
|
|
2376
|
+
id: `whq_${generateRandomId(6)}`,
|
|
2377
|
+
ruleId: rule.id,
|
|
2378
|
+
ruleName: rule.name,
|
|
2379
|
+
url: req.url,
|
|
2380
|
+
method: req.method,
|
|
2381
|
+
headers: req.headers,
|
|
2382
|
+
body: req.body,
|
|
2383
|
+
timestamp
|
|
2384
|
+
};
|
|
2385
|
+
ruleQueuedWebhooks.push(queued);
|
|
2386
|
+
allQueuedWebhooks.push(queued);
|
|
2387
|
+
if (!workingUnit.queuedWebhooks) workingUnit.queuedWebhooks = [];
|
|
2388
|
+
workingUnit.queuedWebhooks.push(queued);
|
|
2389
|
+
summaries.push(`Webhook \u5DF2\u5165\u672C\u5730\u79BB\u7EBF\u961F\u5217 (${req.url})`);
|
|
2390
|
+
}
|
|
2391
|
+
break;
|
|
2392
|
+
}
|
|
2393
|
+
case "notify": {
|
|
2394
|
+
executedSteps += 1;
|
|
2395
|
+
const msg = interpolateAutomationString(
|
|
2396
|
+
step.notifyMessage || rule.name,
|
|
2397
|
+
workingUnit,
|
|
2398
|
+
ctxTable,
|
|
2399
|
+
ctxRecord,
|
|
2400
|
+
event.webhookPayload
|
|
2401
|
+
);
|
|
2402
|
+
summaries.push(`\u53D1\u9001\u901A\u77E5 [${step.notifyChannel || "\u7CFB\u7EDF"}]: ${msg}`);
|
|
2403
|
+
break;
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
};
|
|
2408
|
+
execStepList(steps, table, record);
|
|
2409
|
+
executedRuleIds.push(rule.id);
|
|
2410
|
+
const runLog = {
|
|
2411
|
+
id: `alog_${generateRandomId(6)}`,
|
|
2412
|
+
ruleId: rule.id,
|
|
2413
|
+
ruleName: rule.name,
|
|
2414
|
+
tableId: table.id,
|
|
2415
|
+
recordId: record?.id,
|
|
2416
|
+
trigger: event.trigger,
|
|
2417
|
+
status: errorSummary ? "error" : "success",
|
|
2418
|
+
executedSteps,
|
|
2419
|
+
timestamp,
|
|
2420
|
+
summary: errorSummary ?? (summaries.join(" -> ") || "\u89C4\u5219\u5DF2\u6267\u884C"),
|
|
2421
|
+
...ruleQueuedWebhooks.length > 0 ? { queuedWebhooks: ruleQueuedWebhooks } : {}
|
|
2422
|
+
};
|
|
2423
|
+
logs.push(runLog);
|
|
2424
|
+
pushAutomationLog(workingUnit, runLog, maxLogs);
|
|
2425
|
+
if (!errorSummary && cascades.length > 0) {
|
|
2426
|
+
for (const c of cascades) {
|
|
2427
|
+
queue.push(c.event);
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
return {
|
|
2433
|
+
logs,
|
|
2434
|
+
queuedWebhooks: allQueuedWebhooks,
|
|
2435
|
+
executedRuleIds
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
async function executeBaseAutomations(unitData, initialEvent, options) {
|
|
2439
|
+
const workingUnit = Tools.deepClone(unitData);
|
|
2440
|
+
const logs = [];
|
|
2441
|
+
const allQueuedWebhooks = [];
|
|
2442
|
+
const executedRuleIds = [];
|
|
2443
|
+
const timestamp = options?.timestamp ?? nowTimestamp();
|
|
2444
|
+
const maxLogs = options?.maxLogs ?? 200;
|
|
2445
|
+
const queue = [
|
|
2446
|
+
{ ...initialEvent, depth: initialEvent.depth ?? 1 }
|
|
2447
|
+
];
|
|
2448
|
+
while (queue.length > 0) {
|
|
2449
|
+
const event = queue.shift();
|
|
2450
|
+
const depth = event.depth ?? 1;
|
|
2451
|
+
const table = workingUnit.tables[event.tableId];
|
|
2452
|
+
if (!table) continue;
|
|
2453
|
+
const record = event.recordId ? table.records[event.recordId] : void 0;
|
|
2454
|
+
const rules = workingUnit.automations ?? [];
|
|
2455
|
+
for (const rule of rules) {
|
|
2456
|
+
const match = doesAutomationTriggerMatch(rule, event, workingUnit, table, record);
|
|
2457
|
+
if (!match.triggerMatched) continue;
|
|
2458
|
+
if (depth > MAX_AUTOMATION_RECURSION_DEPTH) {
|
|
2459
|
+
const skipLog = {
|
|
2460
|
+
id: `alog_${generateRandomId(6)}`,
|
|
2461
|
+
ruleId: rule.id,
|
|
2462
|
+
ruleName: rule.name,
|
|
2463
|
+
tableId: table.id,
|
|
2464
|
+
recordId: record?.id,
|
|
2465
|
+
trigger: event.trigger,
|
|
2466
|
+
status: "skipped",
|
|
2467
|
+
executedSteps: 0,
|
|
2468
|
+
timestamp,
|
|
2469
|
+
summary: `\u9012\u5F52\u6DF1\u5EA6\u8D85\u8FC7\u4E0A\u9650 (${MAX_AUTOMATION_RECURSION_DEPTH})\uFF0C\u5DF2\u81EA\u52A8\u62E6\u622A\u9632\u6B62\u6B7B\u5FAA\u73AF`
|
|
2470
|
+
};
|
|
2471
|
+
logs.push(skipLog);
|
|
2472
|
+
pushAutomationLog(workingUnit, skipLog, maxLogs);
|
|
2473
|
+
continue;
|
|
2474
|
+
}
|
|
2475
|
+
if (!match.conditionsMatched) {
|
|
2476
|
+
const skipLog = {
|
|
2477
|
+
id: `alog_${generateRandomId(6)}`,
|
|
2478
|
+
ruleId: rule.id,
|
|
2479
|
+
ruleName: rule.name,
|
|
2480
|
+
tableId: table.id,
|
|
2481
|
+
recordId: record?.id,
|
|
2482
|
+
trigger: event.trigger,
|
|
2483
|
+
status: "skipped",
|
|
2484
|
+
executedSteps: 0,
|
|
2485
|
+
timestamp,
|
|
2486
|
+
summary: "\u89E6\u53D1\u5668\u5DF2\u547D\u4E2D\uFF0C\u4F46\u672A\u6EE1\u8DB3\u524D\u7F6E\u8FC7\u6EE4\u6761\u4EF6\uFF0C\u8DF3\u8FC7\u6267\u884C"
|
|
2487
|
+
};
|
|
2488
|
+
logs.push(skipLog);
|
|
2489
|
+
pushAutomationLog(workingUnit, skipLog, maxLogs);
|
|
2490
|
+
continue;
|
|
2491
|
+
}
|
|
2492
|
+
const steps = normalizeAutomationSteps(rule);
|
|
2493
|
+
let executedSteps = 0;
|
|
2494
|
+
const summaries = [];
|
|
2495
|
+
const ruleQueuedWebhooks = [];
|
|
2496
|
+
const cascades = [];
|
|
2497
|
+
let errorSummary = null;
|
|
2498
|
+
const execStepListAsync = async (stepList, ctxTable, ctxRecord) => {
|
|
2499
|
+
for (const step of stepList) {
|
|
2500
|
+
if (errorSummary) return;
|
|
2501
|
+
switch (step.type) {
|
|
2502
|
+
case "updateRecord": {
|
|
2503
|
+
if (!ctxRecord || !step.fieldUpdates) break;
|
|
2504
|
+
executedSteps += 1;
|
|
2505
|
+
const { changedFieldIds, previousCells } = applyCellsUpdateToRecord(
|
|
2506
|
+
workingUnit,
|
|
2507
|
+
ctxTable,
|
|
2508
|
+
ctxRecord,
|
|
2509
|
+
step.fieldUpdates,
|
|
2510
|
+
ctxTable,
|
|
2511
|
+
ctxRecord,
|
|
2512
|
+
event.webhookPayload,
|
|
2513
|
+
timestamp
|
|
2514
|
+
);
|
|
2515
|
+
summaries.push(`\u4FEE\u6539\u8BB0\u5F55 (${changedFieldIds.length} \u4E2A\u5B57\u6BB5)`);
|
|
2516
|
+
if (changedFieldIds.length > 0) {
|
|
2517
|
+
cascades.push({
|
|
2518
|
+
event: {
|
|
2519
|
+
trigger: "recordUpdated",
|
|
2520
|
+
tableId: ctxTable.id,
|
|
2521
|
+
recordId: ctxRecord.id,
|
|
2522
|
+
changedFieldIds,
|
|
2523
|
+
previousCells,
|
|
2524
|
+
depth: depth + 1
|
|
2525
|
+
}
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
break;
|
|
2529
|
+
}
|
|
2530
|
+
case "createLinkedRecord": {
|
|
2531
|
+
const targetTableId = step.targetTableId;
|
|
2532
|
+
const targetTable = targetTableId ? workingUnit.tables[targetTableId] : void 0;
|
|
2533
|
+
if (!targetTable) {
|
|
2534
|
+
errorSummary = `\u76EE\u6807\u5173\u8054\u8868\u4E0D\u5B58\u5728: ${targetTableId ?? "\u672A\u6307\u5B9A"}`;
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
executedSteps += 1;
|
|
2538
|
+
const newRecId = `rec_auto_${generateRandomId(6)}`;
|
|
2539
|
+
const autoNum = targetTable.nextAutoNumber ?? targetTable.recordOrder.length + 1;
|
|
2540
|
+
targetTable.nextAutoNumber = autoNum + 1;
|
|
2541
|
+
const newRec = {
|
|
2542
|
+
id: newRecId,
|
|
2543
|
+
autoNumber: autoNum,
|
|
2544
|
+
createdTime: timestamp,
|
|
2545
|
+
lastModifiedTime: timestamp,
|
|
2546
|
+
createdBy: "\u81EA\u52A8\u5316\u5F15\u64CE",
|
|
2547
|
+
lastModifiedBy: "\u81EA\u52A8\u5316\u5F15\u64CE",
|
|
2548
|
+
cells: {}
|
|
2549
|
+
};
|
|
2550
|
+
targetTable.records[newRecId] = newRec;
|
|
2551
|
+
targetTable.recordOrder.push(newRecId);
|
|
2552
|
+
if (step.recordCells) {
|
|
2553
|
+
applyCellsUpdateToRecord(
|
|
2554
|
+
workingUnit,
|
|
2555
|
+
targetTable,
|
|
2556
|
+
newRec,
|
|
2557
|
+
step.recordCells,
|
|
2558
|
+
ctxTable,
|
|
2559
|
+
ctxRecord,
|
|
2560
|
+
event.webhookPayload,
|
|
2561
|
+
timestamp
|
|
2562
|
+
);
|
|
2563
|
+
}
|
|
2564
|
+
if (ctxRecord) {
|
|
2565
|
+
const explicitFieldId = step.linkBackFieldId;
|
|
2566
|
+
const srcLinkField = explicitFieldId ? ctxTable.fields[explicitFieldId] : Object.values(ctxTable.fields).find(
|
|
2567
|
+
(f) => f.type === "link" && f.config?.linkedTableId === targetTable.id
|
|
2568
|
+
);
|
|
2569
|
+
const tgtLinkField = explicitFieldId && targetTable.fields[explicitFieldId] ? targetTable.fields[explicitFieldId] : Object.values(targetTable.fields).find(
|
|
2570
|
+
(f) => f.type === "link" && f.config?.linkedTableId === ctxTable.id
|
|
2571
|
+
);
|
|
2572
|
+
if (srcLinkField && srcLinkField.type === "link" && srcLinkField.config?.linkedTableId === targetTable.id) {
|
|
2573
|
+
const prevIds = normalizeLinkIds(ctxRecord.cells[srcLinkField.id]);
|
|
2574
|
+
const nextIds = srcLinkField.config?.allowMultiple === false ? [newRecId] : Array.from(/* @__PURE__ */ new Set([...prevIds, newRecId]));
|
|
2575
|
+
ctxRecord.cells[srcLinkField.id] = nextIds;
|
|
2576
|
+
ctxRecord.lastModifiedTime = timestamp;
|
|
2577
|
+
syncLinkInTables(
|
|
2578
|
+
workingUnit.tables,
|
|
2579
|
+
ctxTable.id,
|
|
2580
|
+
ctxRecord.id,
|
|
2581
|
+
srcLinkField,
|
|
2582
|
+
prevIds,
|
|
2583
|
+
nextIds,
|
|
2584
|
+
timestamp
|
|
2585
|
+
);
|
|
2586
|
+
} else if (tgtLinkField && tgtLinkField.type === "link" && tgtLinkField.config?.linkedTableId === ctxTable.id) {
|
|
2587
|
+
const prevIds = normalizeLinkIds(newRec.cells[tgtLinkField.id]);
|
|
2588
|
+
const nextIds = tgtLinkField.config?.allowMultiple === false ? [ctxRecord.id] : Array.from(/* @__PURE__ */ new Set([...prevIds, ctxRecord.id]));
|
|
2589
|
+
newRec.cells[tgtLinkField.id] = nextIds;
|
|
2590
|
+
syncLinkInTables(
|
|
2591
|
+
workingUnit.tables,
|
|
2592
|
+
targetTable.id,
|
|
2593
|
+
newRecId,
|
|
2594
|
+
tgtLinkField,
|
|
2595
|
+
prevIds,
|
|
2596
|
+
nextIds,
|
|
2597
|
+
timestamp
|
|
2598
|
+
);
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
summaries.push(`\u65B0\u5EFA\u5173\u8054\u8BB0\u5F55 -> ${targetTable.name}(${newRecId})`);
|
|
2602
|
+
cascades.push({
|
|
2603
|
+
event: {
|
|
2604
|
+
trigger: "recordCreated",
|
|
2605
|
+
tableId: targetTable.id,
|
|
2606
|
+
recordId: newRecId,
|
|
2607
|
+
changedFieldIds: Object.keys(newRec.cells),
|
|
2608
|
+
depth: depth + 1
|
|
2609
|
+
}
|
|
2610
|
+
});
|
|
2611
|
+
break;
|
|
2612
|
+
}
|
|
2613
|
+
case "ifElse": {
|
|
2614
|
+
executedSteps += 1;
|
|
2615
|
+
const branchMatch = evaluateAutomationConditions(
|
|
2616
|
+
step.conditions,
|
|
2617
|
+
step.conditionConjunction,
|
|
2618
|
+
workingUnit,
|
|
2619
|
+
ctxTable,
|
|
2620
|
+
ctxRecord
|
|
2621
|
+
);
|
|
2622
|
+
summaries.push(branchMatch ? "If\u6761\u4EF6\u6210\u7ACB -> Then\u5206\u652F" : "If\u6761\u4EF6\u4E0D\u6210\u7ACB -> Else\u5206\u652F");
|
|
2623
|
+
if (branchMatch) {
|
|
2624
|
+
await execStepListAsync(step.thenSteps ?? [], ctxTable, ctxRecord);
|
|
2625
|
+
} else {
|
|
2626
|
+
await execStepListAsync(step.elseSteps ?? [], ctxTable, ctxRecord);
|
|
2627
|
+
}
|
|
2628
|
+
break;
|
|
2629
|
+
}
|
|
2630
|
+
case "loopRecords": {
|
|
2631
|
+
const loopTbl = workingUnit.tables[step.loopTableId || ctxTable.id];
|
|
2632
|
+
if (!loopTbl) break;
|
|
2633
|
+
executedSteps += 1;
|
|
2634
|
+
const matchedRecords = loopTbl.recordOrder.map((rid) => loopTbl.records[rid]).filter(
|
|
2635
|
+
(r) => Boolean(r) && evaluateAutomationConditions(
|
|
2636
|
+
step.loopConditions,
|
|
2637
|
+
step.loopConditionConjunction,
|
|
2638
|
+
workingUnit,
|
|
2639
|
+
loopTbl,
|
|
2640
|
+
r
|
|
2641
|
+
)
|
|
2642
|
+
);
|
|
2643
|
+
for (const loopRec of matchedRecords) {
|
|
2644
|
+
await execStepListAsync(step.loopSteps ?? [], loopTbl, loopRec);
|
|
2645
|
+
}
|
|
2646
|
+
summaries.push(`\u5FAA\u73AF\u5904\u7406 ${matchedRecords.length} \u6761\u8BB0\u5F55`);
|
|
2647
|
+
break;
|
|
2648
|
+
}
|
|
2649
|
+
case "httpWebhook": {
|
|
2650
|
+
executedSteps += 1;
|
|
2651
|
+
const req = buildWebhookRequestForStep(
|
|
2652
|
+
step,
|
|
2653
|
+
rule,
|
|
2654
|
+
workingUnit,
|
|
2655
|
+
ctxTable,
|
|
2656
|
+
ctxRecord,
|
|
2657
|
+
event.webhookPayload
|
|
2658
|
+
);
|
|
2659
|
+
if (options?.webhookExecutor) {
|
|
2660
|
+
try {
|
|
2661
|
+
const res = await options.webhookExecutor(req);
|
|
2662
|
+
if (res.status >= 400) {
|
|
2663
|
+
errorSummary = `Webhook \u54CD\u5E94\u5F02\u5E38 HTTP ${res.status}`;
|
|
2664
|
+
return;
|
|
2665
|
+
}
|
|
2666
|
+
summaries.push(`Webhook ${req.method} ${req.url} -> ${res.status}`);
|
|
2667
|
+
} catch (err) {
|
|
2668
|
+
errorSummary = err instanceof Error ? err.message : "Webhook \u6267\u884C\u5F02\u5E38";
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
} else {
|
|
2672
|
+
const queued = {
|
|
2673
|
+
id: `whq_${generateRandomId(6)}`,
|
|
2674
|
+
ruleId: rule.id,
|
|
2675
|
+
ruleName: rule.name,
|
|
2676
|
+
url: req.url,
|
|
2677
|
+
method: req.method,
|
|
2678
|
+
headers: req.headers,
|
|
2679
|
+
body: req.body,
|
|
2680
|
+
timestamp
|
|
2681
|
+
};
|
|
2682
|
+
ruleQueuedWebhooks.push(queued);
|
|
2683
|
+
allQueuedWebhooks.push(queued);
|
|
2684
|
+
if (!workingUnit.queuedWebhooks) workingUnit.queuedWebhooks = [];
|
|
2685
|
+
workingUnit.queuedWebhooks.push(queued);
|
|
2686
|
+
summaries.push(`Webhook \u5DF2\u5165\u672C\u5730\u79BB\u7EBF\u961F\u5217 (${req.url})`);
|
|
2687
|
+
}
|
|
2688
|
+
break;
|
|
2689
|
+
}
|
|
2690
|
+
case "notify": {
|
|
2691
|
+
executedSteps += 1;
|
|
2692
|
+
const msg = interpolateAutomationString(
|
|
2693
|
+
step.notifyMessage || rule.name,
|
|
2694
|
+
workingUnit,
|
|
2695
|
+
ctxTable,
|
|
2696
|
+
ctxRecord,
|
|
2697
|
+
event.webhookPayload
|
|
2698
|
+
);
|
|
2699
|
+
summaries.push(`\u53D1\u9001\u901A\u77E5 [${step.notifyChannel || "\u7CFB\u7EDF"}]: ${msg}`);
|
|
2700
|
+
break;
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
};
|
|
2705
|
+
await execStepListAsync(steps, table, record);
|
|
2706
|
+
executedRuleIds.push(rule.id);
|
|
2707
|
+
const runLog = {
|
|
2708
|
+
id: `alog_${generateRandomId(6)}`,
|
|
2709
|
+
ruleId: rule.id,
|
|
2710
|
+
ruleName: rule.name,
|
|
2711
|
+
tableId: table.id,
|
|
2712
|
+
recordId: record?.id,
|
|
2713
|
+
trigger: event.trigger,
|
|
2714
|
+
status: errorSummary ? "error" : "success",
|
|
2715
|
+
executedSteps,
|
|
2716
|
+
timestamp,
|
|
2717
|
+
summary: errorSummary ?? (summaries.join(" -> ") || "\u89C4\u5219\u5DF2\u6267\u884C"),
|
|
2718
|
+
...ruleQueuedWebhooks.length > 0 ? { queuedWebhooks: ruleQueuedWebhooks } : {}
|
|
2719
|
+
};
|
|
2720
|
+
logs.push(runLog);
|
|
2721
|
+
pushAutomationLog(workingUnit, runLog, maxLogs);
|
|
2722
|
+
if (!errorSummary && cascades.length > 0) {
|
|
2723
|
+
for (const c of cascades) {
|
|
2724
|
+
queue.push(c.event);
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
return {
|
|
2730
|
+
unitData: workingUnit,
|
|
2731
|
+
logs,
|
|
2732
|
+
queuedWebhooks: allQueuedWebhooks,
|
|
2733
|
+
executedRuleIds
|
|
2734
|
+
};
|
|
2735
|
+
}
|
|
2736
|
+
|
|
2737
|
+
// src/engine/base-sync-and-acl.ts
|
|
2738
|
+
import { generateRandomId as generateRandomId2, Tools as Tools2 } from "@univerjs/core";
|
|
2739
|
+
function recordMatchesOwnerAliases(unitData, table, record, ownerFieldId, aliases) {
|
|
2740
|
+
const field = table.fields[ownerFieldId] ?? Object.values(table.fields).find((f) => f.name === ownerFieldId);
|
|
2741
|
+
if (!field) {
|
|
2742
|
+
return Boolean(record.createdBy && aliases.has(record.createdBy.toLowerCase()));
|
|
2743
|
+
}
|
|
2744
|
+
if (field.type === "createdBy") {
|
|
2745
|
+
return Boolean(record.createdBy && aliases.has(record.createdBy.toLowerCase()));
|
|
2746
|
+
}
|
|
2747
|
+
if (field.type === "lastModifiedBy") {
|
|
2748
|
+
const mod = record.lastModifiedBy ?? record.createdBy;
|
|
2749
|
+
return Boolean(mod && aliases.has(mod.toLowerCase()));
|
|
2750
|
+
}
|
|
2751
|
+
const raw = resolveBaseCellValue(unitData, table.id, record, field);
|
|
2752
|
+
if (Array.isArray(raw)) {
|
|
2753
|
+
return raw.some((item) => {
|
|
2754
|
+
if (typeof item === "string") {
|
|
2755
|
+
return aliases.has(item.toLowerCase());
|
|
2756
|
+
}
|
|
2757
|
+
if (item && typeof item === "object") {
|
|
2758
|
+
const id = "id" in item && item.id ? String(item.id).toLowerCase() : "";
|
|
2759
|
+
const name = "name" in item && item.name ? String(item.name).toLowerCase() : "";
|
|
2760
|
+
const email = "email" in item && item.email ? String(item.email).toLowerCase() : "";
|
|
2761
|
+
return id && aliases.has(id) || name && aliases.has(name) || email && aliases.has(email);
|
|
2762
|
+
}
|
|
2763
|
+
return false;
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2766
|
+
if (raw !== null && raw !== void 0) {
|
|
2767
|
+
return aliases.has(String(raw).trim().toLowerCase());
|
|
2768
|
+
}
|
|
2769
|
+
return false;
|
|
2770
|
+
}
|
|
2771
|
+
function evaluateRowAccessRuleOnRecord(rule, unitData, table, record, context, userAliases) {
|
|
2772
|
+
if (rule.allowAllRecords) return true;
|
|
2773
|
+
const checks = [];
|
|
2774
|
+
if (rule.ownerFieldId) {
|
|
2775
|
+
checks.push(recordMatchesOwnerAliases(unitData, table, record, rule.ownerFieldId, userAliases));
|
|
2776
|
+
}
|
|
2777
|
+
if (rule.filters && rule.filters.length > 0) {
|
|
2778
|
+
const filterOutcomes = rule.filters.map((fRule) => {
|
|
2779
|
+
const field = table.fields[fRule.fieldId] ?? Object.values(table.fields).find((f) => f.name === fRule.fieldId);
|
|
2780
|
+
if (!field) return true;
|
|
2781
|
+
const rawVal = resolveBaseCellValue(unitData, table.id, record, field);
|
|
2782
|
+
const dispVal = formatBaseCellValue(unitData, table.id, field, rawVal);
|
|
2783
|
+
const valStr = typeof fRule.value === "string" ? fRule.value.trim() : "";
|
|
2784
|
+
if (valStr === "$currentUser" || valStr === "$userId" || valStr === "{userId}" || valStr === "{currentUser}") {
|
|
2785
|
+
if (field.type === "person" || field.type === "createdBy" || field.type === "lastModifiedBy") {
|
|
2786
|
+
const hit = recordMatchesOwnerAliases(unitData, table, record, field.id, userAliases);
|
|
2787
|
+
return fRule.operator === "isNot" || fRule.operator === "notContains" ? !hit : hit;
|
|
2788
|
+
}
|
|
2789
|
+
return matchesBaseFilterRule(
|
|
2790
|
+
{ ...fRule, value: context.userId },
|
|
2791
|
+
field,
|
|
2792
|
+
rawVal,
|
|
2793
|
+
dispVal
|
|
2794
|
+
);
|
|
2795
|
+
}
|
|
2796
|
+
return matchesBaseFilterRule(fRule, field, rawVal, dispVal);
|
|
2797
|
+
});
|
|
2798
|
+
const conj = rule.filterConjunction ?? "and";
|
|
2799
|
+
checks.push(conj === "or" ? filterOutcomes.some(Boolean) : filterOutcomes.every(Boolean));
|
|
2800
|
+
}
|
|
2801
|
+
if (checks.length === 0) {
|
|
2802
|
+
return true;
|
|
2803
|
+
}
|
|
2804
|
+
const mode = rule.filterConjunction ?? "and";
|
|
2805
|
+
return mode === "or" ? checks.some(Boolean) : checks.every(Boolean);
|
|
2806
|
+
}
|
|
2807
|
+
function applyBaseRowReadScope(unitData, context) {
|
|
2808
|
+
const scoped = Tools2.deepClone(unitData);
|
|
2809
|
+
const roleSet = new Set((context.roles ?? []).map((r) => r.toLowerCase()));
|
|
2810
|
+
const userAliases = /* @__PURE__ */ new Set();
|
|
2811
|
+
if (context.userId) userAliases.add(context.userId.toLowerCase());
|
|
2812
|
+
if (context.userName) userAliases.add(context.userName.toLowerCase());
|
|
2813
|
+
const matchedCollab = (unitData.collaborators ?? []).find(
|
|
2814
|
+
(c) => c.id === context.userId || c.name === context.userId || context.userName && c.name === context.userName
|
|
2815
|
+
);
|
|
2816
|
+
if (matchedCollab) {
|
|
2817
|
+
userAliases.add(matchedCollab.id.toLowerCase());
|
|
2818
|
+
userAliases.add(matchedCollab.name.toLowerCase());
|
|
2819
|
+
if (matchedCollab.email) userAliases.add(matchedCollab.email.toLowerCase());
|
|
2820
|
+
}
|
|
2821
|
+
for (const tableId of scoped.tableOrder) {
|
|
2822
|
+
const sourceTable = unitData.tables[tableId];
|
|
2823
|
+
const targetTable = scoped.tables[tableId];
|
|
2824
|
+
if (!sourceTable || !targetTable) continue;
|
|
2825
|
+
const tableRules = context.rules.filter(
|
|
2826
|
+
(r) => r.tableId === tableId || r.tableId === "*"
|
|
2827
|
+
);
|
|
2828
|
+
if (tableRules.length === 0) continue;
|
|
2829
|
+
const applicableRules = tableRules.filter((r) => {
|
|
2830
|
+
const hasRoleFilter = Boolean(r.roles && r.roles.length > 0);
|
|
2831
|
+
const hasUserFilter = Boolean(r.userIds && r.userIds.length > 0);
|
|
2832
|
+
if (!hasRoleFilter && !hasUserFilter) return true;
|
|
2833
|
+
const roleHit = hasRoleFilter && r.roles.some((role) => roleSet.has(role.toLowerCase()));
|
|
2834
|
+
const userHit = hasUserFilter && r.userIds.some((uid) => userAliases.has(uid.toLowerCase()) || uid === context.userId);
|
|
2835
|
+
return Boolean(roleHit || userHit);
|
|
2836
|
+
});
|
|
2837
|
+
if (applicableRules.length === 0) {
|
|
2838
|
+
targetTable.recordOrder = [];
|
|
2839
|
+
targetTable.records = {};
|
|
2840
|
+
continue;
|
|
2841
|
+
}
|
|
2842
|
+
const nextRecordOrder = [];
|
|
2843
|
+
const nextRecords = {};
|
|
2844
|
+
const fieldsHiddenEverywhere = /* @__PURE__ */ new Set();
|
|
2845
|
+
if (applicableRules.every((r) => r.maskMode === "hide" && (r.restrictedFieldIds?.length ?? 0) > 0)) {
|
|
2846
|
+
const firstRestricted = applicableRules[0].restrictedFieldIds ?? [];
|
|
2847
|
+
for (const fid of firstRestricted) {
|
|
2848
|
+
if (applicableRules.every((r) => r.restrictedFieldIds?.includes(fid))) {
|
|
2849
|
+
fieldsHiddenEverywhere.add(fid);
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
for (const recId of sourceTable.recordOrder) {
|
|
2854
|
+
const srcRec = sourceTable.records[recId];
|
|
2855
|
+
if (!srcRec) continue;
|
|
2856
|
+
const permittingRules = applicableRules.filter(
|
|
2857
|
+
(rule) => evaluateRowAccessRuleOnRecord(rule, unitData, sourceTable, srcRec, context, userAliases)
|
|
2858
|
+
);
|
|
2859
|
+
if (permittingRules.length === 0) continue;
|
|
2860
|
+
const clonedRec = Tools2.deepClone(srcRec);
|
|
2861
|
+
const candidateRestricted = /* @__PURE__ */ new Set();
|
|
2862
|
+
for (const pRule of permittingRules) {
|
|
2863
|
+
for (const fid of pRule.restrictedFieldIds ?? []) {
|
|
2864
|
+
const resolvedField = targetTable.fields[fid] ?? Object.values(targetTable.fields).find((f) => f.name === fid);
|
|
2865
|
+
if (resolvedField) candidateRestricted.add(resolvedField.id);
|
|
2866
|
+
}
|
|
2867
|
+
}
|
|
2868
|
+
for (const fid of candidateRestricted) {
|
|
2869
|
+
const restrictedByAll = permittingRules.every(
|
|
2870
|
+
(pRule) => (pRule.restrictedFieldIds ?? []).some(
|
|
2871
|
+
(rf) => rf === fid || targetTable.fields[fid]?.name === rf
|
|
2872
|
+
)
|
|
2873
|
+
);
|
|
2874
|
+
if (!restrictedByAll) continue;
|
|
2875
|
+
const governingRule = permittingRules[0];
|
|
2876
|
+
if (governingRule.maskMode === "hide") {
|
|
2877
|
+
delete clonedRec.cells[fid];
|
|
2878
|
+
fieldsHiddenEverywhere.add(fid);
|
|
2879
|
+
} else {
|
|
2880
|
+
const maskVal = governingRule.maskValue !== void 0 ? Tools2.deepClone(governingRule.maskValue) : "***";
|
|
2881
|
+
clonedRec.cells[fid] = maskVal;
|
|
2882
|
+
const fld = targetTable.fields[fid];
|
|
2883
|
+
if (fld && isComputedBaseField(fld.type)) {
|
|
2884
|
+
targetTable.fields[fid] = {
|
|
2885
|
+
...fld,
|
|
2886
|
+
type: "text",
|
|
2887
|
+
config: void 0
|
|
2888
|
+
};
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
nextRecordOrder.push(recId);
|
|
2893
|
+
nextRecords[recId] = clonedRec;
|
|
2894
|
+
}
|
|
2895
|
+
for (const hiddenFid of fieldsHiddenEverywhere) {
|
|
2896
|
+
if (targetTable.fields[hiddenFid] && !targetTable.fields[hiddenFid].isPrimary) {
|
|
2897
|
+
targetTable.fields[hiddenFid].hidden = true;
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
targetTable.recordOrder = nextRecordOrder;
|
|
2901
|
+
targetTable.records = nextRecords;
|
|
2902
|
+
}
|
|
2903
|
+
for (const tbl of Object.values(scoped.tables)) {
|
|
2904
|
+
const linkFields = Object.values(tbl.fields).filter(
|
|
2905
|
+
(f) => f.type === "link" && f.config?.linkedTableId && scoped.tables[f.config.linkedTableId]
|
|
2906
|
+
);
|
|
2907
|
+
if (linkFields.length === 0) continue;
|
|
2908
|
+
for (const rec of Object.values(tbl.records)) {
|
|
2909
|
+
for (const lf of linkFields) {
|
|
2910
|
+
const targetTbl = scoped.tables[lf.config.linkedTableId];
|
|
2911
|
+
const curIds = normalizeLinkIds(rec.cells[lf.id]);
|
|
2912
|
+
const validIds = curIds.filter((id) => Boolean(targetTbl.records[id]));
|
|
2913
|
+
if (validIds.length !== curIds.length) {
|
|
2914
|
+
rec.cells[lf.id] = validIds;
|
|
2915
|
+
}
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
return scoped;
|
|
2920
|
+
}
|
|
2921
|
+
function nowTimestamp2() {
|
|
2922
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
|
|
2923
|
+
}
|
|
2924
|
+
function resolveField(table, idOrName) {
|
|
2925
|
+
if (!idOrName) return void 0;
|
|
2926
|
+
return table.fields[idOrName] ?? Object.values(table.fields).find((f) => f.name === idOrName);
|
|
2927
|
+
}
|
|
2928
|
+
function buildFieldMappingPairs(sourceTable, targetTable, explicitMap) {
|
|
2929
|
+
const pairs = [];
|
|
2930
|
+
if (explicitMap && Object.keys(explicitMap).length > 0) {
|
|
2931
|
+
for (const [srcKey, tgtKey] of Object.entries(explicitMap)) {
|
|
2932
|
+
const sField = resolveField(sourceTable, srcKey);
|
|
2933
|
+
const tField = resolveField(targetTable, tgtKey);
|
|
2934
|
+
if (sField && tField && !isComputedBaseField(tField.type)) {
|
|
2935
|
+
pairs.push({ sourceField: sField, targetField: tField });
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
return pairs;
|
|
2939
|
+
}
|
|
2940
|
+
for (const sFieldId of sourceTable.fieldOrder) {
|
|
2941
|
+
const sField = sourceTable.fields[sFieldId];
|
|
2942
|
+
if (!sField) continue;
|
|
2943
|
+
const tField = Object.values(targetTable.fields).find((tf) => tf.name === sField.name) ?? targetTable.fields[sField.id];
|
|
2944
|
+
if (tField && !isComputedBaseField(tField.type) && tField.type !== "link") {
|
|
2945
|
+
pairs.push({ sourceField: sField, targetField: tField });
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
return pairs;
|
|
2949
|
+
}
|
|
2950
|
+
function extractRecordKey(unit, table, record, keyField) {
|
|
2951
|
+
const raw = resolveBaseCellValue(unit, table.id, record, keyField);
|
|
2952
|
+
if (isCellValueEmpty(raw)) return "";
|
|
2953
|
+
if (typeof raw === "string" || typeof raw === "number") {
|
|
2954
|
+
return String(raw).trim();
|
|
2955
|
+
}
|
|
2956
|
+
return formatBaseCellValue(unit, table.id, keyField, raw).trim();
|
|
2957
|
+
}
|
|
2958
|
+
function cellsDeepEqual(a, b) {
|
|
2959
|
+
if (a === b) return true;
|
|
2960
|
+
if ((a === null || a === void 0 || a === "") && (b === null || b === void 0 || b === "")) {
|
|
2961
|
+
return true;
|
|
2962
|
+
}
|
|
2963
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
2964
|
+
}
|
|
2965
|
+
function compareModifiedTimestamps(tsA, tsB) {
|
|
2966
|
+
const msA = Date.parse(tsA.replace(" ", "T"));
|
|
2967
|
+
const msB = Date.parse(tsB.replace(" ", "T"));
|
|
2968
|
+
if (!Number.isNaN(msA) && !Number.isNaN(msB) && msA !== msB) {
|
|
2969
|
+
return msA - msB;
|
|
2970
|
+
}
|
|
2971
|
+
return tsA.localeCompare(tsB);
|
|
2972
|
+
}
|
|
2973
|
+
function passesSourceFilters(filters, unit, table, record) {
|
|
2974
|
+
if (!filters || filters.length === 0) return true;
|
|
2975
|
+
return filters.every((rule) => {
|
|
2976
|
+
const f = resolveField(table, rule.fieldId);
|
|
2977
|
+
if (!f) return true;
|
|
2978
|
+
const raw = resolveBaseCellValue(unit, table.id, record, f);
|
|
2979
|
+
const disp = formatBaseCellValue(unit, table.id, f, raw);
|
|
2980
|
+
return matchesBaseFilterRule(rule, f, raw, disp);
|
|
2981
|
+
});
|
|
2982
|
+
}
|
|
2983
|
+
function syncOneWayBaseTable(sourceUnit, sourceTableId, targetUnit, targetTableId, mapping) {
|
|
2984
|
+
const sourceTable = sourceUnit.tables[sourceTableId];
|
|
2985
|
+
if (!sourceTable) {
|
|
2986
|
+
throw new Error(`[UniverBases] Source table "${sourceTableId}" does not exist.`);
|
|
2987
|
+
}
|
|
2988
|
+
const clonedTargetUnit = Tools2.deepClone(targetUnit);
|
|
2989
|
+
const targetTable = clonedTargetUnit.tables[targetTableId];
|
|
2990
|
+
if (!targetTable) {
|
|
2991
|
+
throw new Error(`[UniverBases] Target table "${targetTableId}" does not exist.`);
|
|
2992
|
+
}
|
|
2993
|
+
const srcKeyField = resolveField(sourceTable, mapping?.sourceKeyField) ?? sourceTable.fields[sourceTable.primaryFieldId] ?? Object.values(sourceTable.fields)[0];
|
|
2994
|
+
const tgtKeyField = resolveField(targetTable, mapping?.targetKeyField) ?? resolveField(targetTable, srcKeyField?.name) ?? targetTable.fields[targetTable.primaryFieldId] ?? Object.values(targetTable.fields)[0];
|
|
2995
|
+
if (!srcKeyField || !tgtKeyField) {
|
|
2996
|
+
throw new Error("[UniverBases] Unable to resolve key fields for one-way table sync.");
|
|
2997
|
+
}
|
|
2998
|
+
const pairs = buildFieldMappingPairs(sourceTable, targetTable, mapping?.fieldMap);
|
|
2999
|
+
if (!pairs.some((p) => p.targetField.id === tgtKeyField.id) && !isComputedBaseField(tgtKeyField.type)) {
|
|
3000
|
+
pairs.unshift({ sourceField: srcKeyField, targetField: tgtKeyField });
|
|
3001
|
+
}
|
|
3002
|
+
const targetByKey = /* @__PURE__ */ new Map();
|
|
3003
|
+
for (const rid of targetTable.recordOrder) {
|
|
3004
|
+
const rec = targetTable.records[rid];
|
|
3005
|
+
if (!rec) continue;
|
|
3006
|
+
const k = extractRecordKey(clonedTargetUnit, targetTable, rec, tgtKeyField);
|
|
3007
|
+
if (k && !targetByKey.has(k)) {
|
|
3008
|
+
targetByKey.set(k, rec);
|
|
3009
|
+
}
|
|
3010
|
+
}
|
|
3011
|
+
const syncTs = mapping?.syncTimestamp ?? nowTimestamp2();
|
|
3012
|
+
let insertedCount = 0;
|
|
3013
|
+
let updatedCount = 0;
|
|
3014
|
+
let unchangedCount = 0;
|
|
3015
|
+
let nextAuto = targetTable.nextAutoNumber ?? targetTable.recordOrder.length + 1;
|
|
3016
|
+
for (const sRecId of sourceTable.recordOrder) {
|
|
3017
|
+
const sRec = sourceTable.records[sRecId];
|
|
3018
|
+
if (!sRec) continue;
|
|
3019
|
+
if (!passesSourceFilters(mapping?.sourceFilters, sourceUnit, sourceTable, sRec)) continue;
|
|
3020
|
+
const key = extractRecordKey(sourceUnit, sourceTable, sRec, srcKeyField);
|
|
3021
|
+
if (!key) continue;
|
|
3022
|
+
const mappedCells = {};
|
|
3023
|
+
for (const { sourceField, targetField } of pairs) {
|
|
3024
|
+
const val = resolveBaseCellValue(sourceUnit, sourceTable.id, sRec, sourceField);
|
|
3025
|
+
mappedCells[targetField.id] = Tools2.deepClone(val);
|
|
3026
|
+
}
|
|
3027
|
+
if (!isComputedBaseField(tgtKeyField.type) && mappedCells[tgtKeyField.id] === void 0) {
|
|
3028
|
+
mappedCells[tgtKeyField.id] = key;
|
|
3029
|
+
}
|
|
3030
|
+
const existingTarget = targetByKey.get(key);
|
|
3031
|
+
if (!existingTarget) {
|
|
3032
|
+
const newId = `rec_sync_${generateRandomId2(6)}`;
|
|
3033
|
+
const newRec = {
|
|
3034
|
+
id: newId,
|
|
3035
|
+
autoNumber: nextAuto++,
|
|
3036
|
+
createdTime: sRec.createdTime || syncTs,
|
|
3037
|
+
lastModifiedTime: sRec.lastModifiedTime || syncTs,
|
|
3038
|
+
createdBy: sRec.createdBy ?? "\u8DE8\u5E93\u540C\u6B65",
|
|
3039
|
+
lastModifiedBy: "\u8DE8\u5E93\u540C\u6B65",
|
|
3040
|
+
cells: mappedCells
|
|
3041
|
+
};
|
|
3042
|
+
targetTable.records[newId] = newRec;
|
|
3043
|
+
targetTable.recordOrder.push(newId);
|
|
3044
|
+
targetByKey.set(key, newRec);
|
|
3045
|
+
insertedCount += 1;
|
|
3046
|
+
} else {
|
|
3047
|
+
let changed = false;
|
|
3048
|
+
for (const [fid, nextVal] of Object.entries(mappedCells)) {
|
|
3049
|
+
if (!cellsDeepEqual(existingTarget.cells[fid], nextVal)) {
|
|
3050
|
+
existingTarget.cells[fid] = nextVal;
|
|
3051
|
+
changed = true;
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
if (changed) {
|
|
3055
|
+
existingTarget.lastModifiedTime = syncTs;
|
|
3056
|
+
existingTarget.lastModifiedBy = "\u8DE8\u5E93\u540C\u6B65";
|
|
3057
|
+
updatedCount += 1;
|
|
3058
|
+
} else {
|
|
3059
|
+
unchangedCount += 1;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
targetTable.nextAutoNumber = nextAuto;
|
|
3064
|
+
clonedTargetUnit.rev = (clonedTargetUnit.rev ?? 1) + 1;
|
|
3065
|
+
return {
|
|
3066
|
+
targetUnit: clonedTargetUnit,
|
|
3067
|
+
insertedCount,
|
|
3068
|
+
updatedCount,
|
|
3069
|
+
unchangedCount,
|
|
3070
|
+
totalTargetRecords: targetTable.recordOrder.length
|
|
3071
|
+
};
|
|
3072
|
+
}
|
|
3073
|
+
function syncTwoWayBaseTables(unitA, tableIdA, unitB, tableIdB, mapping) {
|
|
3074
|
+
const clonedA = Tools2.deepClone(unitA);
|
|
3075
|
+
const clonedB = Tools2.deepClone(unitB);
|
|
3076
|
+
const tableA = clonedA.tables[tableIdA];
|
|
3077
|
+
const tableB = clonedB.tables[tableIdB];
|
|
3078
|
+
if (!tableA || !tableB) {
|
|
3079
|
+
throw new Error("[UniverBases] Both tableA and tableB must exist for two-way sync.");
|
|
3080
|
+
}
|
|
3081
|
+
const keyFieldA = resolveField(tableA, mapping?.sourceKeyField) ?? tableA.fields[tableA.primaryFieldId] ?? Object.values(tableA.fields)[0];
|
|
3082
|
+
const keyFieldB = resolveField(tableB, mapping?.targetKeyField) ?? resolveField(tableB, keyFieldA?.name) ?? tableB.fields[tableB.primaryFieldId] ?? Object.values(tableB.fields)[0];
|
|
3083
|
+
if (!keyFieldA || !keyFieldB) {
|
|
3084
|
+
throw new Error("[UniverBases] Unable to resolve key fields for two-way table sync.");
|
|
3085
|
+
}
|
|
3086
|
+
const pairsAtoB = buildFieldMappingPairs(tableA, tableB, mapping?.fieldMap);
|
|
3087
|
+
if (!pairsAtoB.some((p) => p.targetField.id === keyFieldB.id) && !isComputedBaseField(keyFieldB.type)) {
|
|
3088
|
+
pairsAtoB.unshift({ sourceField: keyFieldA, targetField: keyFieldB });
|
|
3089
|
+
}
|
|
3090
|
+
const reverseFieldMap = mapping?.fieldMap ? Object.fromEntries(Object.entries(mapping.fieldMap).map(([k, v]) => [v, k])) : void 0;
|
|
3091
|
+
const pairsBtoA = buildFieldMappingPairs(tableB, tableA, reverseFieldMap);
|
|
3092
|
+
if (!pairsBtoA.some((p) => p.targetField.id === keyFieldA.id) && !isComputedBaseField(keyFieldA.type)) {
|
|
3093
|
+
pairsBtoA.unshift({ sourceField: keyFieldB, targetField: keyFieldA });
|
|
3094
|
+
}
|
|
3095
|
+
const mapA = /* @__PURE__ */ new Map();
|
|
3096
|
+
const orderedKeys = [];
|
|
3097
|
+
for (const rid of tableA.recordOrder) {
|
|
3098
|
+
const rec = tableA.records[rid];
|
|
3099
|
+
if (!rec) continue;
|
|
3100
|
+
const k = extractRecordKey(clonedA, tableA, rec, keyFieldA);
|
|
3101
|
+
if (k && !mapA.has(k)) {
|
|
3102
|
+
mapA.set(k, rec);
|
|
3103
|
+
orderedKeys.push(k);
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
const mapB = /* @__PURE__ */ new Map();
|
|
3107
|
+
for (const rid of tableB.recordOrder) {
|
|
3108
|
+
const rec = tableB.records[rid];
|
|
3109
|
+
if (!rec) continue;
|
|
3110
|
+
const k = extractRecordKey(clonedB, tableB, rec, keyFieldB);
|
|
3111
|
+
if (k && !mapB.has(k)) {
|
|
3112
|
+
mapB.set(k, rec);
|
|
3113
|
+
if (!mapA.has(k)) orderedKeys.push(k);
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
const strategy = mapping?.conflictStrategy ?? "latestWins";
|
|
3117
|
+
const syncTs = mapping?.syncTimestamp ?? nowTimestamp2();
|
|
3118
|
+
let insertedInA = 0;
|
|
3119
|
+
let updatedInA = 0;
|
|
3120
|
+
let insertedInB = 0;
|
|
3121
|
+
let updatedInB = 0;
|
|
3122
|
+
let conflictsResolved = 0;
|
|
3123
|
+
let nextAutoA = tableA.nextAutoNumber ?? tableA.recordOrder.length + 1;
|
|
3124
|
+
let nextAutoB = tableB.nextAutoNumber ?? tableB.recordOrder.length + 1;
|
|
3125
|
+
for (const key of orderedKeys) {
|
|
3126
|
+
const recA = mapA.get(key);
|
|
3127
|
+
const recB = mapB.get(key);
|
|
3128
|
+
if (recA && !recB) {
|
|
3129
|
+
const cellsB = {};
|
|
3130
|
+
for (const { sourceField, targetField } of pairsAtoB) {
|
|
3131
|
+
cellsB[targetField.id] = Tools2.deepClone(
|
|
3132
|
+
resolveBaseCellValue(clonedA, tableA.id, recA, sourceField)
|
|
3133
|
+
);
|
|
3134
|
+
}
|
|
3135
|
+
const newIdB = `rec_sync_${generateRandomId2(6)}`;
|
|
3136
|
+
tableB.records[newIdB] = {
|
|
3137
|
+
id: newIdB,
|
|
3138
|
+
autoNumber: nextAutoB++,
|
|
3139
|
+
createdTime: recA.createdTime || syncTs,
|
|
3140
|
+
lastModifiedTime: recA.lastModifiedTime || syncTs,
|
|
3141
|
+
createdBy: recA.createdBy ?? "\u53CC\u5411\u540C\u6B65",
|
|
3142
|
+
lastModifiedBy: "\u53CC\u5411\u540C\u6B65",
|
|
3143
|
+
cells: cellsB
|
|
3144
|
+
};
|
|
3145
|
+
tableB.recordOrder.push(newIdB);
|
|
3146
|
+
insertedInB += 1;
|
|
3147
|
+
continue;
|
|
3148
|
+
}
|
|
3149
|
+
if (!recA && recB) {
|
|
3150
|
+
const cellsA = {};
|
|
3151
|
+
for (const { sourceField, targetField } of pairsBtoA) {
|
|
3152
|
+
cellsA[targetField.id] = Tools2.deepClone(
|
|
3153
|
+
resolveBaseCellValue(clonedB, tableB.id, recB, sourceField)
|
|
3154
|
+
);
|
|
3155
|
+
}
|
|
3156
|
+
const newIdA = `rec_sync_${generateRandomId2(6)}`;
|
|
3157
|
+
tableA.records[newIdA] = {
|
|
3158
|
+
id: newIdA,
|
|
3159
|
+
autoNumber: nextAutoA++,
|
|
3160
|
+
createdTime: recB.createdTime || syncTs,
|
|
3161
|
+
lastModifiedTime: recB.lastModifiedTime || syncTs,
|
|
3162
|
+
createdBy: recB.createdBy ?? "\u53CC\u5411\u540C\u6B65",
|
|
3163
|
+
lastModifiedBy: "\u53CC\u5411\u540C\u6B65",
|
|
3164
|
+
cells: cellsA
|
|
3165
|
+
};
|
|
3166
|
+
tableA.recordOrder.push(newIdA);
|
|
3167
|
+
insertedInA += 1;
|
|
3168
|
+
continue;
|
|
3169
|
+
}
|
|
3170
|
+
if (recA && recB) {
|
|
3171
|
+
let hasDiff = false;
|
|
3172
|
+
for (const { sourceField, targetField } of pairsAtoB) {
|
|
3173
|
+
const valA = resolveBaseCellValue(clonedA, tableA.id, recA, sourceField);
|
|
3174
|
+
const valB = resolveBaseCellValue(clonedB, tableB.id, recB, targetField);
|
|
3175
|
+
if (!cellsDeepEqual(valA, valB)) {
|
|
3176
|
+
hasDiff = true;
|
|
3177
|
+
break;
|
|
3178
|
+
}
|
|
3179
|
+
}
|
|
3180
|
+
if (!hasDiff) continue;
|
|
3181
|
+
conflictsResolved += 1;
|
|
3182
|
+
let winner;
|
|
3183
|
+
if (strategy === "sourceWins") {
|
|
3184
|
+
winner = "A";
|
|
3185
|
+
} else if (strategy === "targetWins") {
|
|
3186
|
+
winner = "B";
|
|
3187
|
+
} else {
|
|
3188
|
+
winner = compareModifiedTimestamps(recA.lastModifiedTime, recB.lastModifiedTime) >= 0 ? "A" : "B";
|
|
3189
|
+
}
|
|
3190
|
+
if (winner === "A") {
|
|
3191
|
+
for (const { sourceField, targetField } of pairsAtoB) {
|
|
3192
|
+
if (isComputedBaseField(targetField.type)) continue;
|
|
3193
|
+
recB.cells[targetField.id] = Tools2.deepClone(
|
|
3194
|
+
resolveBaseCellValue(clonedA, tableA.id, recA, sourceField)
|
|
3195
|
+
);
|
|
3196
|
+
}
|
|
3197
|
+
recB.lastModifiedTime = recA.lastModifiedTime || syncTs;
|
|
3198
|
+
recB.lastModifiedBy = "\u53CC\u5411\u540C\u6B65";
|
|
3199
|
+
updatedInB += 1;
|
|
3200
|
+
} else {
|
|
3201
|
+
for (const { sourceField, targetField } of pairsBtoA) {
|
|
3202
|
+
if (isComputedBaseField(targetField.type)) continue;
|
|
3203
|
+
recA.cells[targetField.id] = Tools2.deepClone(
|
|
3204
|
+
resolveBaseCellValue(clonedB, tableB.id, recB, sourceField)
|
|
3205
|
+
);
|
|
3206
|
+
}
|
|
3207
|
+
recA.lastModifiedTime = recB.lastModifiedTime || syncTs;
|
|
3208
|
+
recA.lastModifiedBy = "\u53CC\u5411\u540C\u6B65";
|
|
3209
|
+
updatedInA += 1;
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
tableA.nextAutoNumber = nextAutoA;
|
|
3214
|
+
tableB.nextAutoNumber = nextAutoB;
|
|
3215
|
+
clonedA.rev = (clonedA.rev ?? 1) + 1;
|
|
3216
|
+
clonedB.rev = (clonedB.rev ?? 1) + 1;
|
|
3217
|
+
return {
|
|
3218
|
+
unitA: clonedA,
|
|
3219
|
+
unitB: clonedB,
|
|
3220
|
+
insertedInA,
|
|
3221
|
+
updatedInA,
|
|
3222
|
+
insertedInB,
|
|
3223
|
+
updatedInB,
|
|
3224
|
+
conflictsResolved
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
function mergeMultipleSourcesIntoBaseTable(sources, targetUnit, targetTableId, keyFieldName, options) {
|
|
3228
|
+
const clonedTargetUnit = Tools2.deepClone(targetUnit);
|
|
3229
|
+
const targetTable = clonedTargetUnit.tables[targetTableId];
|
|
3230
|
+
if (!targetTable) {
|
|
3231
|
+
throw new Error(`[UniverBases] Target table "${targetTableId}" does not exist.`);
|
|
3232
|
+
}
|
|
3233
|
+
const tgtKeyField = resolveField(targetTable, keyFieldName) ?? targetTable.fields[targetTable.primaryFieldId] ?? Object.values(targetTable.fields)[0];
|
|
3234
|
+
if (!tgtKeyField) {
|
|
3235
|
+
throw new Error(`[UniverBases] Target key field "${keyFieldName}" not found.`);
|
|
3236
|
+
}
|
|
3237
|
+
const hasAnySourceTag = sources.some((s) => Boolean(s.sourceTag));
|
|
3238
|
+
const tagFieldName = options?.sourceTagFieldName || "\u6570\u636E\u6765\u6E90";
|
|
3239
|
+
let sourceTagField = resolveField(targetTable, tagFieldName) ?? resolveField(targetTable, "\u6765\u6E90");
|
|
3240
|
+
if (hasAnySourceTag && !sourceTagField) {
|
|
3241
|
+
const newTagFieldId = "fld_sync_source_tag";
|
|
3242
|
+
sourceTagField = {
|
|
3243
|
+
id: newTagFieldId,
|
|
3244
|
+
name: tagFieldName,
|
|
3245
|
+
type: "text",
|
|
3246
|
+
width: 140
|
|
3247
|
+
};
|
|
3248
|
+
targetTable.fields[newTagFieldId] = sourceTagField;
|
|
3249
|
+
targetTable.fieldOrder.push(newTagFieldId);
|
|
3250
|
+
}
|
|
3251
|
+
const targetByKey = /* @__PURE__ */ new Map();
|
|
3252
|
+
for (const rid of targetTable.recordOrder) {
|
|
3253
|
+
const rec = targetTable.records[rid];
|
|
3254
|
+
if (!rec) continue;
|
|
3255
|
+
const k = extractRecordKey(clonedTargetUnit, targetTable, rec, tgtKeyField);
|
|
3256
|
+
if (k && !targetByKey.has(k)) {
|
|
3257
|
+
targetByKey.set(k, { record: rec, wasInsertedInMerge: false });
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
const strategy = options?.conflictStrategy ?? "latestWins";
|
|
3261
|
+
const syncTs = options?.syncTimestamp ?? nowTimestamp2();
|
|
3262
|
+
let insertedCount = 0;
|
|
3263
|
+
let updatedCount = 0;
|
|
3264
|
+
let unchangedCount = 0;
|
|
3265
|
+
let deduplicatedCount = 0;
|
|
3266
|
+
let nextAuto = targetTable.nextAutoNumber ?? targetTable.recordOrder.length + 1;
|
|
3267
|
+
const seenInSources = /* @__PURE__ */ new Set();
|
|
3268
|
+
for (const srcItem of sources) {
|
|
3269
|
+
const srcTable = srcItem.unit.tables[srcItem.tableId];
|
|
3270
|
+
if (!srcTable) continue;
|
|
3271
|
+
const srcKeyField = resolveField(srcTable, keyFieldName) ?? srcTable.fields[srcTable.primaryFieldId] ?? Object.values(srcTable.fields)[0];
|
|
3272
|
+
if (!srcKeyField) continue;
|
|
3273
|
+
const pairs = buildFieldMappingPairs(srcTable, targetTable);
|
|
3274
|
+
if (!pairs.some((p) => p.targetField.id === tgtKeyField.id) && !isComputedBaseField(tgtKeyField.type)) {
|
|
3275
|
+
pairs.unshift({ sourceField: srcKeyField, targetField: tgtKeyField });
|
|
3276
|
+
}
|
|
3277
|
+
for (const sRecId of srcTable.recordOrder) {
|
|
3278
|
+
const sRec = srcTable.records[sRecId];
|
|
3279
|
+
if (!sRec) continue;
|
|
3280
|
+
const key = extractRecordKey(srcItem.unit, srcTable, sRec, srcKeyField);
|
|
3281
|
+
if (!key) continue;
|
|
3282
|
+
if (seenInSources.has(key)) {
|
|
3283
|
+
deduplicatedCount += 1;
|
|
3284
|
+
} else {
|
|
3285
|
+
seenInSources.add(key);
|
|
3286
|
+
}
|
|
3287
|
+
const mappedCells = {};
|
|
3288
|
+
for (const { sourceField, targetField } of pairs) {
|
|
3289
|
+
mappedCells[targetField.id] = Tools2.deepClone(
|
|
3290
|
+
resolveBaseCellValue(srcItem.unit, srcTable.id, sRec, sourceField)
|
|
3291
|
+
);
|
|
3292
|
+
}
|
|
3293
|
+
if (srcItem.sourceTag && sourceTagField) {
|
|
3294
|
+
mappedCells[sourceTagField.id] = srcItem.sourceTag;
|
|
3295
|
+
}
|
|
3296
|
+
const existing = targetByKey.get(key);
|
|
3297
|
+
if (!existing) {
|
|
3298
|
+
const newId = `rec_merge_${generateRandomId2(6)}`;
|
|
3299
|
+
const newRec = {
|
|
3300
|
+
id: newId,
|
|
3301
|
+
autoNumber: nextAuto++,
|
|
3302
|
+
createdTime: sRec.createdTime || syncTs,
|
|
3303
|
+
lastModifiedTime: sRec.lastModifiedTime || syncTs,
|
|
3304
|
+
createdBy: srcItem.sourceTag ?? sRec.createdBy ?? "\u591A\u6E90\u5F52\u96C6",
|
|
3305
|
+
lastModifiedBy: srcItem.sourceTag ?? "\u591A\u6E90\u5F52\u96C6",
|
|
3306
|
+
cells: mappedCells
|
|
3307
|
+
};
|
|
3308
|
+
targetTable.records[newId] = newRec;
|
|
3309
|
+
targetTable.recordOrder.push(newId);
|
|
3310
|
+
targetByKey.set(key, { record: newRec, wasInsertedInMerge: true });
|
|
3311
|
+
insertedCount += 1;
|
|
3312
|
+
} else {
|
|
3313
|
+
const tgtRec = existing.record;
|
|
3314
|
+
const shouldOverwrite = strategy === "lastWins" ? true : strategy === "firstWins" ? false : compareModifiedTimestamps(sRec.lastModifiedTime, tgtRec.lastModifiedTime) >= 0;
|
|
3315
|
+
if (!shouldOverwrite) {
|
|
3316
|
+
unchangedCount += 1;
|
|
3317
|
+
continue;
|
|
3318
|
+
}
|
|
3319
|
+
let changed = false;
|
|
3320
|
+
for (const [fid, val] of Object.entries(mappedCells)) {
|
|
3321
|
+
if (!cellsDeepEqual(tgtRec.cells[fid], val)) {
|
|
3322
|
+
tgtRec.cells[fid] = val;
|
|
3323
|
+
changed = true;
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
if (changed) {
|
|
3327
|
+
tgtRec.lastModifiedTime = sRec.lastModifiedTime || syncTs;
|
|
3328
|
+
if (!existing.wasInsertedInMerge) {
|
|
3329
|
+
updatedCount += 1;
|
|
3330
|
+
}
|
|
3331
|
+
} else {
|
|
3332
|
+
unchangedCount += 1;
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
targetTable.nextAutoNumber = nextAuto;
|
|
3338
|
+
clonedTargetUnit.rev = (clonedTargetUnit.rev ?? 1) + 1;
|
|
3339
|
+
return {
|
|
3340
|
+
targetUnit: clonedTargetUnit,
|
|
3341
|
+
insertedCount,
|
|
3342
|
+
updatedCount,
|
|
3343
|
+
unchangedCount,
|
|
3344
|
+
deduplicatedCount,
|
|
3345
|
+
totalTargetRecords: targetTable.recordOrder.length
|
|
3346
|
+
};
|
|
3347
|
+
}
|
|
3348
|
+
var syncBaseTables = {
|
|
3349
|
+
oneWay: syncOneWayBaseTable,
|
|
3350
|
+
twoWay: syncTwoWayBaseTables,
|
|
3351
|
+
mergeMultipleSources: mergeMultipleSourcesIntoBaseTable
|
|
3352
|
+
};
|
|
1490
3353
|
|
|
1491
3354
|
// src/presets/base-presets.ts
|
|
1492
|
-
import { generateRandomId, Tools } from "@univerjs/core";
|
|
3355
|
+
import { generateRandomId as generateRandomId3, Tools as Tools3 } from "@univerjs/core";
|
|
1493
3356
|
function createSampleProjectBaseData(options) {
|
|
1494
|
-
const unitId = options?.id || `base-${
|
|
3357
|
+
const unitId = options?.id || `base-${generateRandomId3(6)}`;
|
|
1495
3358
|
const unitName = options?.name || "\u4F01\u4E1A\u7814\u53D1\u9879\u76EE\u4E0E\u51B2\u523A\u534F\u540C\u5E93";
|
|
1496
3359
|
const projectsTable = {
|
|
1497
3360
|
id: "tbl_projects",
|
|
@@ -2189,6 +4052,7 @@ function createSampleProjectBaseData(options) {
|
|
|
2189
4052
|
},
|
|
2190
4053
|
viewOrder: [
|
|
2191
4054
|
"vw_task_grid",
|
|
4055
|
+
"vw_task_list",
|
|
2192
4056
|
"vw_task_kanban",
|
|
2193
4057
|
"vw_task_calendar",
|
|
2194
4058
|
"vw_task_gallery",
|
|
@@ -2218,6 +4082,12 @@ function createSampleProjectBaseData(options) {
|
|
|
2218
4082
|
fld_task_progress: "avg"
|
|
2219
4083
|
}
|
|
2220
4084
|
},
|
|
4085
|
+
vw_task_list: {
|
|
4086
|
+
id: "vw_task_list",
|
|
4087
|
+
name: "\u5217\u8868\u89C6\u56FE",
|
|
4088
|
+
type: "list",
|
|
4089
|
+
listParentFieldId: "fld_task_deps"
|
|
4090
|
+
},
|
|
2221
4091
|
vw_task_kanban: {
|
|
2222
4092
|
id: "vw_task_kanban",
|
|
2223
4093
|
name: "\u770B\u677F\u89C6\u56FE",
|
|
@@ -2399,7 +4269,7 @@ function createSampleProjectBaseData(options) {
|
|
|
2399
4269
|
};
|
|
2400
4270
|
}
|
|
2401
4271
|
function createSampleCrmBaseData(options) {
|
|
2402
|
-
const unitId = options?.id || `base-crm-${
|
|
4272
|
+
const unitId = options?.id || `base-crm-${generateRandomId3(6)}`;
|
|
2403
4273
|
const unitName = options?.name || "\u653F\u4F01\u5BA2\u6237\u4E0E\u5546\u673A\u56DE\u6B3E\u7BA1\u7406";
|
|
2404
4274
|
const accountsTable = {
|
|
2405
4275
|
id: "tbl_accounts",
|
|
@@ -2772,12 +4642,14 @@ function createDefaultBaseUnitData(partial) {
|
|
|
2772
4642
|
...partial?.rev !== void 0 ? { rev: partial.rev } : {},
|
|
2773
4643
|
...partial?.activeTableId && sample.tables[partial.activeTableId] ? { activeTableId: partial.activeTableId } : {},
|
|
2774
4644
|
...partial?.workspaceMode ? { workspaceMode: partial.workspaceMode } : {},
|
|
2775
|
-
...partial?.dashboards ? { dashboards:
|
|
2776
|
-
...partial?.automations ? { automations:
|
|
2777
|
-
...partial?.
|
|
4645
|
+
...partial?.dashboards ? { dashboards: Tools3.deepClone(partial.dashboards) } : {},
|
|
4646
|
+
...partial?.automations ? { automations: Tools3.deepClone(partial.automations) } : {},
|
|
4647
|
+
...partial?.automationLogs ? { automationLogs: Tools3.deepClone(partial.automationLogs) } : {},
|
|
4648
|
+
...partial?.queuedWebhooks ? { queuedWebhooks: Tools3.deepClone(partial.queuedWebhooks) } : {},
|
|
4649
|
+
...partial?.metadata ? { metadata: Tools3.deepClone(partial.metadata) } : {}
|
|
2778
4650
|
};
|
|
2779
4651
|
}
|
|
2780
|
-
const tables =
|
|
4652
|
+
const tables = Tools3.deepClone(partial.tables);
|
|
2781
4653
|
const tableOrder = partial.tableOrder && partial.tableOrder.length > 0 ? partial.tableOrder.filter((id) => Boolean(tables[id])) : Object.keys(tables);
|
|
2782
4654
|
for (const tid of Object.keys(tables)) {
|
|
2783
4655
|
if (!tableOrder.includes(tid)) tableOrder.push(tid);
|
|
@@ -2786,7 +4658,7 @@ function createDefaultBaseUnitData(partial) {
|
|
|
2786
4658
|
if (!tbl.primaryFieldId) tbl.primaryFieldId = tbl.fieldOrder[0] ?? "";
|
|
2787
4659
|
if (!tbl.recordOrder) tbl.recordOrder = Object.keys(tbl.records ?? {});
|
|
2788
4660
|
if (!tbl.views || Object.keys(tbl.views).length === 0) {
|
|
2789
|
-
const vid = `vw_${
|
|
4661
|
+
const vid = `vw_${generateRandomId3(6)}`;
|
|
2790
4662
|
tbl.views = { [vid]: { id: vid, name: "\u8868\u683C\u89C6\u56FE", type: "grid" } };
|
|
2791
4663
|
tbl.viewOrder = [vid];
|
|
2792
4664
|
tbl.activeViewId = vid;
|
|
@@ -2806,7 +4678,7 @@ function createDefaultBaseUnitData(partial) {
|
|
|
2806
4678
|
return {
|
|
2807
4679
|
schema: UNIVER_BASE_SCHEMA,
|
|
2808
4680
|
schemaVersion: partial.schemaVersion ?? UNIVER_BASE_SCHEMA_VERSION,
|
|
2809
|
-
id: partial.id || `base-${
|
|
4681
|
+
id: partial.id || `base-${generateRandomId3(6)}`,
|
|
2810
4682
|
name: partial.name || "\u672A\u547D\u540D\u591A\u7EF4\u6570\u636E\u8868",
|
|
2811
4683
|
rev: partial.rev ?? 1,
|
|
2812
4684
|
activeTableId,
|
|
@@ -2815,15 +4687,17 @@ function createDefaultBaseUnitData(partial) {
|
|
|
2815
4687
|
workspaceMode: partial.workspaceMode ?? "table",
|
|
2816
4688
|
tableOrder,
|
|
2817
4689
|
tables,
|
|
2818
|
-
dashboards: partial.dashboards ?
|
|
2819
|
-
automations: partial.automations ?
|
|
2820
|
-
|
|
2821
|
-
|
|
4690
|
+
dashboards: partial.dashboards ? Tools3.deepClone(partial.dashboards) : [],
|
|
4691
|
+
automations: partial.automations ? Tools3.deepClone(partial.automations) : [],
|
|
4692
|
+
automationLogs: partial.automationLogs ? Tools3.deepClone(partial.automationLogs) : [],
|
|
4693
|
+
queuedWebhooks: partial.queuedWebhooks ? Tools3.deepClone(partial.queuedWebhooks) : [],
|
|
4694
|
+
collaborators: partial.collaborators ? Tools3.deepClone(partial.collaborators) : [],
|
|
4695
|
+
metadata: partial.metadata ? Tools3.deepClone(partial.metadata) : {}
|
|
2822
4696
|
};
|
|
2823
4697
|
}
|
|
2824
4698
|
|
|
2825
4699
|
// src/models/base-unit-model.ts
|
|
2826
|
-
import { Tools as
|
|
4700
|
+
import { Tools as Tools4, UnitModel, UniverInstanceType } from "@univerjs/core";
|
|
2827
4701
|
import { BehaviorSubject, Subject } from "rxjs";
|
|
2828
4702
|
var BaseUnitModel = class extends UnitModel {
|
|
2829
4703
|
constructor(snapshot) {
|
|
@@ -2856,7 +4730,7 @@ var BaseUnitModel = class extends UnitModel {
|
|
|
2856
4730
|
return this._snapshot;
|
|
2857
4731
|
}
|
|
2858
4732
|
save() {
|
|
2859
|
-
return
|
|
4733
|
+
return Tools4.deepClone(this._snapshot);
|
|
2860
4734
|
}
|
|
2861
4735
|
getRev() {
|
|
2862
4736
|
return this._snapshot.rev;
|
|
@@ -2920,16 +4794,25 @@ var BaseUnitModel = class extends UnitModel {
|
|
|
2920
4794
|
computeGanttTasks(tableId, viewId) {
|
|
2921
4795
|
return computeBaseGanttTasks(this._snapshot, tableId, viewId);
|
|
2922
4796
|
}
|
|
4797
|
+
computeHierarchicalList(tableId, viewId) {
|
|
4798
|
+
return computeBaseHierarchicalList(this._snapshot, tableId, viewId);
|
|
4799
|
+
}
|
|
2923
4800
|
computeDashboardWidget(widget) {
|
|
2924
4801
|
return computeBaseDashboardWidget(this._snapshot, widget);
|
|
2925
4802
|
}
|
|
4803
|
+
getAutomations() {
|
|
4804
|
+
return this._snapshot.automations ?? [];
|
|
4805
|
+
}
|
|
4806
|
+
getAutomationLogs() {
|
|
4807
|
+
return this._snapshot.automationLogs ?? [];
|
|
4808
|
+
}
|
|
2926
4809
|
// =========================================================================
|
|
2927
4810
|
// Internal synchronous mutators invoked exclusively by IMutation handlers
|
|
2928
4811
|
// =========================================================================
|
|
2929
4812
|
__replaceSnapshot(nextSnapshot) {
|
|
2930
4813
|
const prevId = this._snapshot.id;
|
|
2931
4814
|
const normalized = createDefaultBaseUnitData({
|
|
2932
|
-
...
|
|
4815
|
+
...Tools4.deepClone(nextSnapshot),
|
|
2933
4816
|
id: nextSnapshot.id || prevId
|
|
2934
4817
|
});
|
|
2935
4818
|
const prevName = this._snapshot.name;
|
|
@@ -2942,7 +4825,7 @@ var BaseUnitModel = class extends UnitModel {
|
|
|
2942
4825
|
}
|
|
2943
4826
|
__applyTablesState(params) {
|
|
2944
4827
|
this._snapshot.tableOrder = [...params.tableOrder];
|
|
2945
|
-
this._snapshot.tables =
|
|
4828
|
+
this._snapshot.tables = Tools4.deepClone(params.tables);
|
|
2946
4829
|
if (params.activeTableId !== void 0) {
|
|
2947
4830
|
this._snapshot.activeTableId = params.activeTableId;
|
|
2948
4831
|
}
|
|
@@ -2952,6 +4835,15 @@ var BaseUnitModel = class extends UnitModel {
|
|
|
2952
4835
|
if (params.workspaceMode !== void 0) {
|
|
2953
4836
|
this._snapshot.workspaceMode = params.workspaceMode;
|
|
2954
4837
|
}
|
|
4838
|
+
if (params.automations !== void 0) {
|
|
4839
|
+
this._snapshot.automations = Tools4.deepClone(params.automations);
|
|
4840
|
+
}
|
|
4841
|
+
if (params.automationLogs !== void 0) {
|
|
4842
|
+
this._snapshot.automationLogs = Tools4.deepClone(params.automationLogs);
|
|
4843
|
+
}
|
|
4844
|
+
if (params.queuedWebhooks !== void 0) {
|
|
4845
|
+
this._snapshot.queuedWebhooks = Tools4.deepClone(params.queuedWebhooks);
|
|
4846
|
+
}
|
|
2955
4847
|
this.incrementRev();
|
|
2956
4848
|
this._notifyChange();
|
|
2957
4849
|
}
|
|
@@ -2980,7 +4872,7 @@ var BaseUnitModel = class extends UnitModel {
|
|
|
2980
4872
|
this._notifyChange();
|
|
2981
4873
|
}
|
|
2982
4874
|
__applyDashboardsState(params) {
|
|
2983
|
-
this._snapshot.dashboards =
|
|
4875
|
+
this._snapshot.dashboards = Tools4.deepClone(params.dashboards);
|
|
2984
4876
|
if (params.activeDashboardId !== void 0) {
|
|
2985
4877
|
this._snapshot.activeDashboardId = params.activeDashboardId;
|
|
2986
4878
|
}
|
|
@@ -3055,14 +4947,14 @@ var ReplaceBaseSnapshotMutation = {
|
|
|
3055
4947
|
// src/commands/commands/base.command.ts
|
|
3056
4948
|
import {
|
|
3057
4949
|
CommandType as CommandType2,
|
|
3058
|
-
generateRandomId as
|
|
4950
|
+
generateRandomId as generateRandomId4,
|
|
3059
4951
|
ICommandService,
|
|
3060
4952
|
IUndoRedoService,
|
|
3061
4953
|
IUniverInstanceService as IUniverInstanceService2,
|
|
3062
|
-
Tools as
|
|
4954
|
+
Tools as Tools5,
|
|
3063
4955
|
UniverInstanceType as UniverInstanceType3
|
|
3064
4956
|
} from "@univerjs/core";
|
|
3065
|
-
function
|
|
4957
|
+
function nowTimestamp3() {
|
|
3066
4958
|
return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
|
|
3067
4959
|
}
|
|
3068
4960
|
function resolveUnitContext(accessor, explicitUnitId) {
|
|
@@ -3076,16 +4968,59 @@ function resolveUnitContext(accessor, explicitUnitId) {
|
|
|
3076
4968
|
undoRedoService: accessor.get(IUndoRedoService)
|
|
3077
4969
|
};
|
|
3078
4970
|
}
|
|
4971
|
+
var activeCommandAutomationDepth = 0;
|
|
4972
|
+
function resolveWebhookExecutor(accessor, explicit) {
|
|
4973
|
+
if (explicit) return explicit;
|
|
4974
|
+
try {
|
|
4975
|
+
if (accessor.has(IBaseAutomationService)) {
|
|
4976
|
+
return accessor.get(IBaseAutomationService).getWebhookExecutor();
|
|
4977
|
+
}
|
|
4978
|
+
} catch {
|
|
4979
|
+
}
|
|
4980
|
+
return void 0;
|
|
4981
|
+
}
|
|
3079
4982
|
function captureTablesState(unitId, snap) {
|
|
3080
4983
|
return {
|
|
3081
4984
|
unitId,
|
|
3082
4985
|
tableOrder: [...snap.tableOrder],
|
|
3083
|
-
tables:
|
|
4986
|
+
tables: Tools5.deepClone(snap.tables),
|
|
3084
4987
|
activeTableId: snap.activeTableId,
|
|
3085
4988
|
activeViewId: snap.activeViewId,
|
|
3086
|
-
workspaceMode: snap.workspaceMode ?? "table"
|
|
4989
|
+
workspaceMode: snap.workspaceMode ?? "table",
|
|
4990
|
+
automations: Tools5.deepClone(snap.automations ?? []),
|
|
4991
|
+
automationLogs: Tools5.deepClone(snap.automationLogs ?? []),
|
|
4992
|
+
queuedWebhooks: Tools5.deepClone(snap.queuedWebhooks ?? [])
|
|
3087
4993
|
};
|
|
3088
4994
|
}
|
|
4995
|
+
function applyAutomationsToTransitionState(snap, after, event, webhookExecutor) {
|
|
4996
|
+
const workingUnit = {
|
|
4997
|
+
...snap,
|
|
4998
|
+
tableOrder: after.tableOrder,
|
|
4999
|
+
tables: after.tables,
|
|
5000
|
+
automations: after.automations ?? [],
|
|
5001
|
+
automationLogs: after.automationLogs ?? [],
|
|
5002
|
+
queuedWebhooks: after.queuedWebhooks ?? []
|
|
5003
|
+
};
|
|
5004
|
+
activeCommandAutomationDepth += 1;
|
|
5005
|
+
try {
|
|
5006
|
+
const res = runBaseAutomationsInPlaceSync(
|
|
5007
|
+
workingUnit,
|
|
5008
|
+
{
|
|
5009
|
+
...event,
|
|
5010
|
+
depth: event.depth ?? activeCommandAutomationDepth
|
|
5011
|
+
},
|
|
5012
|
+
{ webhookExecutor }
|
|
5013
|
+
);
|
|
5014
|
+
after.tables = workingUnit.tables;
|
|
5015
|
+
after.tableOrder = workingUnit.tableOrder;
|
|
5016
|
+
after.automations = workingUnit.automations;
|
|
5017
|
+
after.automationLogs = workingUnit.automationLogs;
|
|
5018
|
+
after.queuedWebhooks = workingUnit.queuedWebhooks;
|
|
5019
|
+
return res.logs;
|
|
5020
|
+
} finally {
|
|
5021
|
+
activeCommandAutomationDepth -= 1;
|
|
5022
|
+
}
|
|
5023
|
+
}
|
|
3089
5024
|
function commitTablesTransition(ctx, beforeState, afterState) {
|
|
3090
5025
|
const ok = ctx.commandService.syncExecuteCommand(ApplyBaseTablesStateMutation.id, afterState);
|
|
3091
5026
|
if (ok) {
|
|
@@ -3142,15 +5077,15 @@ function syncBidirectionalLinkField(tables, sourceTableId, sourceRecordId, linkF
|
|
|
3142
5077
|
}
|
|
3143
5078
|
}
|
|
3144
5079
|
function buildDefaultFieldConfig(type, config, unitSnap, currentTableId) {
|
|
3145
|
-
if (config) return
|
|
5080
|
+
if (config) return Tools5.deepClone(config);
|
|
3146
5081
|
switch (type) {
|
|
3147
5082
|
case "singleSelect":
|
|
3148
5083
|
case "multiSelect":
|
|
3149
5084
|
return {
|
|
3150
5085
|
options: [
|
|
3151
|
-
{ id: `opt_${
|
|
3152
|
-
{ id: `opt_${
|
|
3153
|
-
{ id: `opt_${
|
|
5086
|
+
{ id: `opt_${generateRandomId4(4)}`, name: "\u9009\u9879\u4E00", color: BASE_SELECT_PALETTE[0] },
|
|
5087
|
+
{ id: `opt_${generateRandomId4(4)}`, name: "\u9009\u9879\u4E8C", color: BASE_SELECT_PALETTE[1] },
|
|
5088
|
+
{ id: `opt_${generateRandomId4(4)}`, name: "\u9009\u9879\u4E09", color: BASE_SELECT_PALETTE[2] }
|
|
3154
5089
|
]
|
|
3155
5090
|
};
|
|
3156
5091
|
case "currency":
|
|
@@ -3188,12 +5123,12 @@ var AddBaseTableCommand = {
|
|
|
3188
5123
|
const snap = ctx.unit.getSnapshot();
|
|
3189
5124
|
const before = captureTablesState(ctx.unitId, snap);
|
|
3190
5125
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3191
|
-
const tableId = params?.tableId || `tbl_${
|
|
5126
|
+
const tableId = params?.tableId || `tbl_${generateRandomId4(6)}`;
|
|
3192
5127
|
if (after.tables[tableId]) return false;
|
|
3193
|
-
const defaultFields = params?.fields && params.fields.length > 0 ?
|
|
3194
|
-
{ id: `fld_${
|
|
5128
|
+
const defaultFields = params?.fields && params.fields.length > 0 ? Tools5.deepClone(params.fields) : [
|
|
5129
|
+
{ id: `fld_${generateRandomId4(5)}`, name: "\u6807\u9898\u540D\u79F0", type: "text", isPrimary: true, width: 220 },
|
|
3195
5130
|
{
|
|
3196
|
-
id: `fld_${
|
|
5131
|
+
id: `fld_${generateRandomId4(5)}`,
|
|
3197
5132
|
name: "\u72B6\u6001\u6807\u7B7E",
|
|
3198
5133
|
type: "singleSelect",
|
|
3199
5134
|
width: 130,
|
|
@@ -3205,8 +5140,8 @@ var AddBaseTableCommand = {
|
|
|
3205
5140
|
]
|
|
3206
5141
|
}
|
|
3207
5142
|
},
|
|
3208
|
-
{ id: `fld_${
|
|
3209
|
-
{ id: `fld_${
|
|
5143
|
+
{ id: `fld_${generateRandomId4(5)}`, name: "\u8D1F\u8D23\u4EBA", type: "person", width: 130 },
|
|
5144
|
+
{ id: `fld_${generateRandomId4(5)}`, name: "\u622A\u6B62\u65E5\u671F", type: "date", width: 130 }
|
|
3210
5145
|
];
|
|
3211
5146
|
if (!defaultFields.some((f) => f.isPrimary) && defaultFields[0]) {
|
|
3212
5147
|
defaultFields[0].isPrimary = true;
|
|
@@ -3214,9 +5149,9 @@ var AddBaseTableCommand = {
|
|
|
3214
5149
|
const fieldsMap = {};
|
|
3215
5150
|
for (const f of defaultFields) fieldsMap[f.id] = f;
|
|
3216
5151
|
const primaryFieldId = defaultFields.find((f) => f.isPrimary)?.id ?? defaultFields[0].id;
|
|
3217
|
-
const gridViewId = `vw_${
|
|
3218
|
-
const now =
|
|
3219
|
-
const initRecId = `rec_${
|
|
5152
|
+
const gridViewId = `vw_${generateRandomId4(6)}`;
|
|
5153
|
+
const now = nowTimestamp3();
|
|
5154
|
+
const initRecId = `rec_${generateRandomId4(6)}`;
|
|
3220
5155
|
const newTable = {
|
|
3221
5156
|
id: tableId,
|
|
3222
5157
|
name: params?.name?.trim() || `\u6570\u636E\u8868 ${after.tableOrder.length + 1}`,
|
|
@@ -3384,7 +5319,7 @@ var AddBaseFieldCommand = {
|
|
|
3384
5319
|
const before = captureTablesState(ctx.unitId, snap);
|
|
3385
5320
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3386
5321
|
const table = after.tables[tableId];
|
|
3387
|
-
const fieldId = params.fieldId || `fld_${
|
|
5322
|
+
const fieldId = params.fieldId || `fld_${generateRandomId4(6)}`;
|
|
3388
5323
|
if (table.fields[fieldId]) return false;
|
|
3389
5324
|
const resolvedConfig = buildDefaultFieldConfig(params.type, params.config, snap, tableId);
|
|
3390
5325
|
const newField = {
|
|
@@ -3406,7 +5341,7 @@ var AddBaseFieldCommand = {
|
|
|
3406
5341
|
symmetricFieldId: fieldId
|
|
3407
5342
|
};
|
|
3408
5343
|
} else {
|
|
3409
|
-
const symId = existingSymId || `fld_sym_${
|
|
5344
|
+
const symId = existingSymId || `fld_sym_${generateRandomId4(5)}`;
|
|
3410
5345
|
const symName = params.symmetricFieldName?.trim() || `\u5173\u8054${table.name}`;
|
|
3411
5346
|
targetTable.fields[symId] = {
|
|
3412
5347
|
id: symId,
|
|
@@ -3464,7 +5399,7 @@ var UpdateBaseFieldCommand = {
|
|
|
3464
5399
|
if (params.patch.config !== void 0) {
|
|
3465
5400
|
targetField.config = {
|
|
3466
5401
|
...targetField.config ?? {},
|
|
3467
|
-
...
|
|
5402
|
+
...Tools5.deepClone(params.patch.config)
|
|
3468
5403
|
};
|
|
3469
5404
|
}
|
|
3470
5405
|
return commitTablesTransition(ctx, before, after);
|
|
@@ -3535,9 +5470,9 @@ var AddBaseRecordCommand = {
|
|
|
3535
5470
|
const before = captureTablesState(ctx.unitId, snap);
|
|
3536
5471
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3537
5472
|
const table = after.tables[tableId];
|
|
3538
|
-
const recordId = params?.recordId || `rec_${
|
|
5473
|
+
const recordId = params?.recordId || `rec_${generateRandomId4(6)}`;
|
|
3539
5474
|
if (table.records[recordId]) return false;
|
|
3540
|
-
const now =
|
|
5475
|
+
const now = nowTimestamp3();
|
|
3541
5476
|
const autoNumber = table.nextAutoNumber ?? table.recordOrder.length + 1;
|
|
3542
5477
|
table.nextAutoNumber = autoNumber + 1;
|
|
3543
5478
|
const cleanCells = {};
|
|
@@ -3548,7 +5483,7 @@ var AddBaseRecordCommand = {
|
|
|
3548
5483
|
const ids = normalizeLinkIds(val);
|
|
3549
5484
|
cleanCells[fid] = f.config?.allowMultiple === false ? ids.slice(0, 1) : ids;
|
|
3550
5485
|
} else {
|
|
3551
|
-
cleanCells[fid] =
|
|
5486
|
+
cleanCells[fid] = Tools5.deepClone(val);
|
|
3552
5487
|
}
|
|
3553
5488
|
}
|
|
3554
5489
|
const newRecord = {
|
|
@@ -3582,6 +5517,19 @@ var AddBaseRecordCommand = {
|
|
|
3582
5517
|
}
|
|
3583
5518
|
}
|
|
3584
5519
|
}
|
|
5520
|
+
if ((after.automations?.length ?? 0) > 0) {
|
|
5521
|
+
applyAutomationsToTransitionState(
|
|
5522
|
+
snap,
|
|
5523
|
+
after,
|
|
5524
|
+
{
|
|
5525
|
+
trigger: "recordCreated",
|
|
5526
|
+
tableId,
|
|
5527
|
+
recordId,
|
|
5528
|
+
changedFieldIds: Object.keys(cleanCells)
|
|
5529
|
+
},
|
|
5530
|
+
resolveWebhookExecutor(accessor)
|
|
5531
|
+
);
|
|
5532
|
+
}
|
|
3585
5533
|
const ok = commitTablesTransition(ctx, before, after);
|
|
3586
5534
|
if (ok && params?.onCreated) params.onCreated(recordId);
|
|
3587
5535
|
return ok;
|
|
@@ -3602,7 +5550,9 @@ var UpdateBaseRecordCommand = {
|
|
|
3602
5550
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3603
5551
|
const table = after.tables[tableId];
|
|
3604
5552
|
const record = table.records[params.recordId];
|
|
3605
|
-
const
|
|
5553
|
+
const previousCells = Tools5.deepClone(record.cells);
|
|
5554
|
+
const changedFieldIds = [];
|
|
5555
|
+
const now = nowTimestamp3();
|
|
3606
5556
|
for (const [fid, val] of Object.entries(params.cells)) {
|
|
3607
5557
|
const field = table.fields[fid];
|
|
3608
5558
|
if (!field || isComputedBaseField(field.type)) continue;
|
|
@@ -3611,6 +5561,7 @@ var UpdateBaseRecordCommand = {
|
|
|
3611
5561
|
const rawNextIds = normalizeLinkIds(val);
|
|
3612
5562
|
const nextIds = field.config?.allowMultiple === false ? rawNextIds.slice(0, 1) : rawNextIds;
|
|
3613
5563
|
record.cells[fid] = nextIds;
|
|
5564
|
+
changedFieldIds.push(fid);
|
|
3614
5565
|
syncBidirectionalLinkField(
|
|
3615
5566
|
after.tables,
|
|
3616
5567
|
tableId,
|
|
@@ -3621,13 +5572,28 @@ var UpdateBaseRecordCommand = {
|
|
|
3621
5572
|
now
|
|
3622
5573
|
);
|
|
3623
5574
|
} else {
|
|
3624
|
-
record.cells[fid] =
|
|
5575
|
+
record.cells[fid] = Tools5.deepClone(val);
|
|
5576
|
+
changedFieldIds.push(fid);
|
|
3625
5577
|
}
|
|
3626
5578
|
}
|
|
3627
5579
|
record.lastModifiedTime = now;
|
|
3628
5580
|
if (params.modifiedBy) {
|
|
3629
5581
|
record.lastModifiedBy = params.modifiedBy;
|
|
3630
5582
|
}
|
|
5583
|
+
if ((after.automations?.length ?? 0) > 0 && changedFieldIds.length > 0) {
|
|
5584
|
+
applyAutomationsToTransitionState(
|
|
5585
|
+
snap,
|
|
5586
|
+
after,
|
|
5587
|
+
{
|
|
5588
|
+
trigger: "recordUpdated",
|
|
5589
|
+
tableId,
|
|
5590
|
+
recordId: params.recordId,
|
|
5591
|
+
changedFieldIds,
|
|
5592
|
+
previousCells
|
|
5593
|
+
},
|
|
5594
|
+
resolveWebhookExecutor(accessor)
|
|
5595
|
+
);
|
|
5596
|
+
}
|
|
3631
5597
|
return commitTablesTransition(ctx, before, after);
|
|
3632
5598
|
}
|
|
3633
5599
|
};
|
|
@@ -3647,7 +5613,7 @@ var DeleteBaseRecordsCommand = {
|
|
|
3647
5613
|
const before = captureTablesState(ctx.unitId, snap);
|
|
3648
5614
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3649
5615
|
const table = after.tables[tableId];
|
|
3650
|
-
const now =
|
|
5616
|
+
const now = nowTimestamp3();
|
|
3651
5617
|
for (const rid of delSet) {
|
|
3652
5618
|
delete table.records[rid];
|
|
3653
5619
|
}
|
|
@@ -3684,17 +5650,17 @@ var BatchInsertBaseRecordsCommand = {
|
|
|
3684
5650
|
const before = captureTablesState(ctx.unitId, snap);
|
|
3685
5651
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3686
5652
|
const table = after.tables[tableId];
|
|
3687
|
-
const now =
|
|
5653
|
+
const now = nowTimestamp3();
|
|
3688
5654
|
let nextAuto = table.nextAutoNumber ?? table.recordOrder.length + 1;
|
|
3689
5655
|
const createdIds = [];
|
|
3690
5656
|
for (const item of params.records) {
|
|
3691
|
-
const rid = item.id || `rec_${
|
|
5657
|
+
const rid = item.id || `rec_${generateRandomId4(6)}`;
|
|
3692
5658
|
if (table.records[rid]) continue;
|
|
3693
5659
|
const cells = {};
|
|
3694
5660
|
for (const [fid, val] of Object.entries(item.cells ?? {})) {
|
|
3695
5661
|
const f = table.fields[fid];
|
|
3696
5662
|
if (f && isComputedBaseField(f.type)) continue;
|
|
3697
|
-
cells[fid] = f?.type === "link" ? normalizeLinkIds(val) :
|
|
5663
|
+
cells[fid] = f?.type === "link" ? normalizeLinkIds(val) : Tools5.deepClone(val);
|
|
3698
5664
|
}
|
|
3699
5665
|
table.records[rid] = {
|
|
3700
5666
|
id: rid,
|
|
@@ -3735,9 +5701,15 @@ var SubmitBaseFormResponseCommand = {
|
|
|
3735
5701
|
const table = snap.tables[tableId];
|
|
3736
5702
|
if (!table) return false;
|
|
3737
5703
|
const view = (params.viewId ? table.views[params.viewId] : void 0) ?? Object.values(table.views).find((v) => v.type === "form");
|
|
5704
|
+
const cleanedValues = { ...params.values };
|
|
3738
5705
|
if (view?.formConfig?.fields?.length) {
|
|
3739
5706
|
for (const item of view.formConfig.fields) {
|
|
3740
|
-
|
|
5707
|
+
const visible = isFormFieldVisible(item, params.values, table, snap, view.formConfig);
|
|
5708
|
+
if (!visible) {
|
|
5709
|
+
delete cleanedValues[item.fieldId];
|
|
5710
|
+
continue;
|
|
5711
|
+
}
|
|
5712
|
+
if (!isFormFieldRequired(item, params.values, table, snap, view.formConfig)) continue;
|
|
3741
5713
|
const field = table.fields[item.fieldId];
|
|
3742
5714
|
if (!field || isComputedBaseField(field.type)) continue;
|
|
3743
5715
|
const v = params.values[item.fieldId];
|
|
@@ -3750,7 +5722,7 @@ var SubmitBaseFormResponseCommand = {
|
|
|
3750
5722
|
return ctx.commandService.syncExecuteCommand(AddBaseRecordCommand.id, {
|
|
3751
5723
|
unitId: ctx.unitId,
|
|
3752
5724
|
tableId,
|
|
3753
|
-
cells:
|
|
5725
|
+
cells: cleanedValues,
|
|
3754
5726
|
createdBy: params.submittedBy ?? "\u8868\u5355\u63D0\u62A5\u4EBA",
|
|
3755
5727
|
onCreated: params.onSubmitted
|
|
3756
5728
|
});
|
|
@@ -3769,10 +5741,11 @@ var AddBaseViewCommand = {
|
|
|
3769
5741
|
const before = captureTablesState(ctx.unitId, snap);
|
|
3770
5742
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3771
5743
|
const table = after.tables[tableId];
|
|
3772
|
-
const viewId = params.viewId || `vw_${
|
|
5744
|
+
const viewId = params.viewId || `vw_${generateRandomId4(6)}`;
|
|
3773
5745
|
if (table.views[viewId]) return false;
|
|
3774
5746
|
const typeLabels = {
|
|
3775
5747
|
grid: "\u8868\u683C\u89C6\u56FE",
|
|
5748
|
+
list: "\u5217\u8868\u89C6\u56FE",
|
|
3776
5749
|
kanban: "\u770B\u677F\u89C6\u56FE",
|
|
3777
5750
|
calendar: "\u65E5\u5386\u89C6\u56FE",
|
|
3778
5751
|
gallery: "\u753B\u5ECA\u89C6\u56FE",
|
|
@@ -3783,11 +5756,15 @@ var AddBaseViewCommand = {
|
|
|
3783
5756
|
const allFields = table.fieldOrder.map((fid) => table.fields[fid]).filter(Boolean);
|
|
3784
5757
|
const selectField = allFields.find((f) => f.type === "singleSelect" || f.type === "person");
|
|
3785
5758
|
const dateFields = allFields.filter((f) => f.type === "date");
|
|
5759
|
+
const selfLinkField = allFields.find(
|
|
5760
|
+
(f) => f.type === "link" && f.config?.linkedTableId === tableId
|
|
5761
|
+
);
|
|
3786
5762
|
const newView = {
|
|
3787
|
-
...params.view ?
|
|
5763
|
+
...params.view ? Tools5.deepClone(params.view) : {},
|
|
3788
5764
|
id: viewId,
|
|
3789
5765
|
name: params.name?.trim() || params.view?.name || typeLabels[params.type],
|
|
3790
5766
|
type: params.type,
|
|
5767
|
+
...params.type === "list" && !params.view?.listParentFieldId && selfLinkField ? { listParentFieldId: selfLinkField.id } : {},
|
|
3791
5768
|
...params.type === "kanban" && !params.view?.kanbanGroupFieldId && selectField ? { kanbanGroupFieldId: selectField.id } : {},
|
|
3792
5769
|
...params.type === "calendar" && !params.view?.calendarDateFieldId && dateFields[0] ? { calendarDateFieldId: dateFields[0].id } : {},
|
|
3793
5770
|
...(params.type === "gantt" || params.type === "timeline") && !params.view?.ganttStartDateFieldId ? {
|
|
@@ -3839,7 +5816,7 @@ var UpdateBaseViewCommand = {
|
|
|
3839
5816
|
const after = captureTablesState(ctx.unitId, snap);
|
|
3840
5817
|
after.tables[tableId].views[viewId] = {
|
|
3841
5818
|
...after.tables[tableId].views[viewId],
|
|
3842
|
-
...
|
|
5819
|
+
...Tools5.deepClone(params.patch),
|
|
3843
5820
|
id: viewId
|
|
3844
5821
|
};
|
|
3845
5822
|
return commitTablesTransition(ctx, before, after);
|
|
@@ -3908,10 +5885,10 @@ var SetActiveBaseViewCommand = {
|
|
|
3908
5885
|
}
|
|
3909
5886
|
};
|
|
3910
5887
|
function ensureDashboardsClone(snap) {
|
|
3911
|
-
const cloned =
|
|
5888
|
+
const cloned = Tools5.deepClone(snap.dashboards ?? []);
|
|
3912
5889
|
if (cloned.length === 0) {
|
|
3913
5890
|
cloned.push({
|
|
3914
|
-
id: `dash_${
|
|
5891
|
+
id: `dash_${generateRandomId4(5)}`,
|
|
3915
5892
|
name: "\u6570\u636E\u5168\u666F\u4EEA\u8868\u76D8",
|
|
3916
5893
|
widgets: []
|
|
3917
5894
|
});
|
|
@@ -3926,12 +5903,12 @@ var AddBaseDashboardWidgetCommand = {
|
|
|
3926
5903
|
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
3927
5904
|
if (!ctx) return false;
|
|
3928
5905
|
const snap = ctx.unit.getSnapshot();
|
|
3929
|
-
const beforeDashboards =
|
|
5906
|
+
const beforeDashboards = Tools5.deepClone(snap.dashboards ?? []);
|
|
3930
5907
|
const afterDashboards = ensureDashboardsClone(snap);
|
|
3931
5908
|
const targetDash = (params.dashboardId ? afterDashboards.find((d) => d.id === params.dashboardId) : void 0) ?? afterDashboards[0];
|
|
3932
|
-
const widgetId = params.widget.id || `wdg_${
|
|
5909
|
+
const widgetId = params.widget.id || `wdg_${generateRandomId4(6)}`;
|
|
3933
5910
|
targetDash.widgets.push({
|
|
3934
|
-
...
|
|
5911
|
+
...Tools5.deepClone(params.widget),
|
|
3935
5912
|
id: widgetId
|
|
3936
5913
|
});
|
|
3937
5914
|
const beforeParams = {
|
|
@@ -3969,8 +5946,8 @@ var UpdateBaseDashboardWidgetCommand = {
|
|
|
3969
5946
|
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
3970
5947
|
if (!ctx) return false;
|
|
3971
5948
|
const snap = ctx.unit.getSnapshot();
|
|
3972
|
-
const beforeDashboards =
|
|
3973
|
-
const afterDashboards =
|
|
5949
|
+
const beforeDashboards = Tools5.deepClone(snap.dashboards ?? []);
|
|
5950
|
+
const afterDashboards = Tools5.deepClone(snap.dashboards ?? []);
|
|
3974
5951
|
let updated = false;
|
|
3975
5952
|
for (const dash of afterDashboards) {
|
|
3976
5953
|
if (params.dashboardId && dash.id !== params.dashboardId) continue;
|
|
@@ -3978,7 +5955,7 @@ var UpdateBaseDashboardWidgetCommand = {
|
|
|
3978
5955
|
if (idx >= 0) {
|
|
3979
5956
|
dash.widgets[idx] = {
|
|
3980
5957
|
...dash.widgets[idx],
|
|
3981
|
-
...
|
|
5958
|
+
...Tools5.deepClone(params.patch),
|
|
3982
5959
|
id: params.widgetId
|
|
3983
5960
|
};
|
|
3984
5961
|
updated = true;
|
|
@@ -4018,8 +5995,8 @@ var DeleteBaseDashboardWidgetCommand = {
|
|
|
4018
5995
|
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
4019
5996
|
if (!ctx) return false;
|
|
4020
5997
|
const snap = ctx.unit.getSnapshot();
|
|
4021
|
-
const beforeDashboards =
|
|
4022
|
-
const afterDashboards =
|
|
5998
|
+
const beforeDashboards = Tools5.deepClone(snap.dashboards ?? []);
|
|
5999
|
+
const afterDashboards = Tools5.deepClone(snap.dashboards ?? []);
|
|
4023
6000
|
let removed = false;
|
|
4024
6001
|
for (const dash of afterDashboards) {
|
|
4025
6002
|
if (params.dashboardId && dash.id !== params.dashboardId) continue;
|
|
@@ -4063,7 +6040,7 @@ var ReplaceBaseSnapshotCommand = {
|
|
|
4063
6040
|
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
4064
6041
|
if (!ctx) return false;
|
|
4065
6042
|
const beforeSnapshot = ctx.unit.save();
|
|
4066
|
-
const afterSnapshot =
|
|
6043
|
+
const afterSnapshot = Tools5.deepClone(params.snapshot);
|
|
4067
6044
|
afterSnapshot.id = ctx.unitId;
|
|
4068
6045
|
const redoParams = { unitId: ctx.unitId, snapshot: afterSnapshot };
|
|
4069
6046
|
const undoParams = { unitId: ctx.unitId, snapshot: beforeSnapshot };
|
|
@@ -4078,9 +6055,126 @@ var ReplaceBaseSnapshotCommand = {
|
|
|
4078
6055
|
return Boolean(ok);
|
|
4079
6056
|
}
|
|
4080
6057
|
};
|
|
6058
|
+
var UpdateBaseDetailLayoutCommand = {
|
|
6059
|
+
id: "bases.command.update-detail-layout",
|
|
6060
|
+
type: CommandType2.COMMAND,
|
|
6061
|
+
handler: (accessor, params) => {
|
|
6062
|
+
if (!params?.detailLayout) return false;
|
|
6063
|
+
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
6064
|
+
if (!ctx) return false;
|
|
6065
|
+
const snap = ctx.unit.getSnapshot();
|
|
6066
|
+
const tableId = params.tableId || snap.activeTableId;
|
|
6067
|
+
if (!snap.tables[tableId]) return false;
|
|
6068
|
+
const before = captureTablesState(ctx.unitId, snap);
|
|
6069
|
+
const after = captureTablesState(ctx.unitId, snap);
|
|
6070
|
+
const table = after.tables[tableId];
|
|
6071
|
+
if (params.viewId && table.views[params.viewId]) {
|
|
6072
|
+
table.views[params.viewId].detailLayout = Tools5.deepClone(params.detailLayout);
|
|
6073
|
+
} else {
|
|
6074
|
+
table.detailLayout = Tools5.deepClone(params.detailLayout);
|
|
6075
|
+
}
|
|
6076
|
+
return commitTablesTransition(ctx, before, after);
|
|
6077
|
+
}
|
|
6078
|
+
};
|
|
6079
|
+
var SaveBaseAutomationRuleCommand = {
|
|
6080
|
+
id: "bases.command.save-automation-rule",
|
|
6081
|
+
type: CommandType2.COMMAND,
|
|
6082
|
+
handler: (accessor, params) => {
|
|
6083
|
+
if (!params?.rule?.name?.trim() || !params.rule.tableId) return false;
|
|
6084
|
+
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
6085
|
+
if (!ctx) return false;
|
|
6086
|
+
const snap = ctx.unit.getSnapshot();
|
|
6087
|
+
if (!snap.tables[params.rule.tableId]) return false;
|
|
6088
|
+
const before = captureTablesState(ctx.unitId, snap);
|
|
6089
|
+
const after = captureTablesState(ctx.unitId, snap);
|
|
6090
|
+
const list = after.automations ?? [];
|
|
6091
|
+
const ruleId = params.rule.id || `auto_${generateRandomId4(6)}`;
|
|
6092
|
+
const normalizedRule = {
|
|
6093
|
+
...Tools5.deepClone(params.rule),
|
|
6094
|
+
id: ruleId,
|
|
6095
|
+
name: params.rule.name.trim()
|
|
6096
|
+
};
|
|
6097
|
+
const existingIdx = list.findIndex((r) => r.id === ruleId);
|
|
6098
|
+
if (existingIdx >= 0) {
|
|
6099
|
+
list[existingIdx] = normalizedRule;
|
|
6100
|
+
} else {
|
|
6101
|
+
list.push(normalizedRule);
|
|
6102
|
+
}
|
|
6103
|
+
after.automations = list;
|
|
6104
|
+
const ok = commitTablesTransition(ctx, before, after);
|
|
6105
|
+
if (ok && params.onSaved) params.onSaved(ruleId);
|
|
6106
|
+
return ok;
|
|
6107
|
+
}
|
|
6108
|
+
};
|
|
6109
|
+
var DeleteBaseAutomationRuleCommand = {
|
|
6110
|
+
id: "bases.command.delete-automation-rule",
|
|
6111
|
+
type: CommandType2.COMMAND,
|
|
6112
|
+
handler: (accessor, params) => {
|
|
6113
|
+
if (!params?.ruleId) return false;
|
|
6114
|
+
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
6115
|
+
if (!ctx) return false;
|
|
6116
|
+
const snap = ctx.unit.getSnapshot();
|
|
6117
|
+
const curList = snap.automations ?? [];
|
|
6118
|
+
if (!curList.some((r) => r.id === params.ruleId)) return false;
|
|
6119
|
+
const before = captureTablesState(ctx.unitId, snap);
|
|
6120
|
+
const after = captureTablesState(ctx.unitId, snap);
|
|
6121
|
+
after.automations = (after.automations ?? []).filter((r) => r.id !== params.ruleId);
|
|
6122
|
+
return commitTablesTransition(ctx, before, after);
|
|
6123
|
+
}
|
|
6124
|
+
};
|
|
6125
|
+
var ToggleBaseAutomationRuleCommand = {
|
|
6126
|
+
id: "bases.command.toggle-automation-rule",
|
|
6127
|
+
type: CommandType2.COMMAND,
|
|
6128
|
+
handler: (accessor, params) => {
|
|
6129
|
+
if (!params?.ruleId) return false;
|
|
6130
|
+
const ctx = resolveUnitContext(accessor, params.unitId);
|
|
6131
|
+
if (!ctx) return false;
|
|
6132
|
+
const snap = ctx.unit.getSnapshot();
|
|
6133
|
+
const curList = snap.automations ?? [];
|
|
6134
|
+
if (!curList.some((r) => r.id === params.ruleId)) return false;
|
|
6135
|
+
const before = captureTablesState(ctx.unitId, snap);
|
|
6136
|
+
const after = captureTablesState(ctx.unitId, snap);
|
|
6137
|
+
after.automations = (after.automations ?? []).map(
|
|
6138
|
+
(r) => r.id === params.ruleId ? { ...r, enabled: params.enabled !== void 0 ? params.enabled : !r.enabled } : r
|
|
6139
|
+
);
|
|
6140
|
+
return commitTablesTransition(ctx, before, after);
|
|
6141
|
+
}
|
|
6142
|
+
};
|
|
6143
|
+
var TriggerBaseAutomationCommand = {
|
|
6144
|
+
id: "bases.command.trigger-automation",
|
|
6145
|
+
type: CommandType2.COMMAND,
|
|
6146
|
+
handler: (accessor, params) => {
|
|
6147
|
+
const ctx = resolveUnitContext(accessor, params?.unitId);
|
|
6148
|
+
if (!ctx) return false;
|
|
6149
|
+
const snap = ctx.unit.getSnapshot();
|
|
6150
|
+
const targetRule = params?.ruleId ? (snap.automations ?? []).find((r) => r.id === params.ruleId) : void 0;
|
|
6151
|
+
if (params?.ruleId && !targetRule) return false;
|
|
6152
|
+
const tableId = params?.tableId || targetRule?.tableId || snap.activeTableId;
|
|
6153
|
+
const table = snap.tables[tableId];
|
|
6154
|
+
if (!table) return false;
|
|
6155
|
+
const recordId = params?.recordId ?? table.recordOrder[0];
|
|
6156
|
+
const before = captureTablesState(ctx.unitId, snap);
|
|
6157
|
+
const after = captureTablesState(ctx.unitId, snap);
|
|
6158
|
+
const logs = applyAutomationsToTransitionState(
|
|
6159
|
+
snap,
|
|
6160
|
+
after,
|
|
6161
|
+
{
|
|
6162
|
+
trigger: params?.trigger ?? "manual",
|
|
6163
|
+
ruleId: params?.ruleId,
|
|
6164
|
+
tableId,
|
|
6165
|
+
recordId,
|
|
6166
|
+
webhookPayload: params?.webhookPayload
|
|
6167
|
+
},
|
|
6168
|
+
resolveWebhookExecutor(accessor, params?.webhookExecutor)
|
|
6169
|
+
);
|
|
6170
|
+
const ok = commitTablesTransition(ctx, before, after);
|
|
6171
|
+
if (ok && params?.onExecuted) params.onExecuted(logs);
|
|
6172
|
+
return ok;
|
|
6173
|
+
}
|
|
6174
|
+
};
|
|
4081
6175
|
|
|
4082
6176
|
// src/exporter/csv-codec.ts
|
|
4083
|
-
import { generateRandomId as
|
|
6177
|
+
import { generateRandomId as generateRandomId5 } from "@univerjs/core";
|
|
4084
6178
|
function parseDelimitedText(text, delimiter = ",") {
|
|
4085
6179
|
const clean = text.startsWith("\uFEFF") ? text.slice(1) : text;
|
|
4086
6180
|
if (!clean.trim()) return [];
|
|
@@ -4231,7 +6325,7 @@ function exportBaseTableToCsv(unitData, tableId, options) {
|
|
|
4231
6325
|
return options?.includeBom ? `\uFEFF${body}` : body;
|
|
4232
6326
|
}
|
|
4233
6327
|
function buildBaseTableFromGridRows(gridRows, options) {
|
|
4234
|
-
const tableId = options?.tableId || `tbl_${
|
|
6328
|
+
const tableId = options?.tableId || `tbl_${generateRandomId5(6)}`;
|
|
4235
6329
|
const tableName = options?.tableName?.trim() || "\u5BFC\u5165\u6570\u636E\u8868";
|
|
4236
6330
|
const headerRow = gridRows[0] ?? ["\u6807\u9898"];
|
|
4237
6331
|
const dataRows = gridRows.slice(1).filter((r) => r.some((c) => c.trim() !== ""));
|
|
@@ -4253,7 +6347,7 @@ function buildBaseTableFromGridRows(gridRows, options) {
|
|
|
4253
6347
|
usedNames.add(uniqueName);
|
|
4254
6348
|
const samples = dataRows.map((r) => r[c] ?? "");
|
|
4255
6349
|
const inferred = c === 0 ? { type: "text" } : inferFieldFromColumnSamples(samples);
|
|
4256
|
-
const fid = `fld_${c + 1}_${
|
|
6350
|
+
const fid = `fld_${c + 1}_${generateRandomId5(4)}`;
|
|
4257
6351
|
fields[fid] = {
|
|
4258
6352
|
id: fid,
|
|
4259
6353
|
name: uniqueName,
|
|
@@ -4268,7 +6362,7 @@ function buildBaseTableFromGridRows(gridRows, options) {
|
|
|
4268
6362
|
const records = {};
|
|
4269
6363
|
const recordOrder = [];
|
|
4270
6364
|
dataRows.forEach((rowVals, idx) => {
|
|
4271
|
-
const rid = `rec_${idx + 1}_${
|
|
6365
|
+
const rid = `rec_${idx + 1}_${generateRandomId5(4)}`;
|
|
4272
6366
|
const cells = {};
|
|
4273
6367
|
fieldOrder.forEach((fid, colIdx) => {
|
|
4274
6368
|
const f = fields[fid];
|
|
@@ -4285,14 +6379,14 @@ function buildBaseTableFromGridRows(gridRows, options) {
|
|
|
4285
6379
|
};
|
|
4286
6380
|
recordOrder.push(rid);
|
|
4287
6381
|
});
|
|
4288
|
-
const gridViewId = `vw_grid_${
|
|
6382
|
+
const gridViewId = `vw_grid_${generateRandomId5(4)}`;
|
|
4289
6383
|
const views = {
|
|
4290
6384
|
[gridViewId]: { id: gridViewId, name: "\u8868\u683C\u89C6\u56FE", type: "grid" }
|
|
4291
6385
|
};
|
|
4292
6386
|
const viewOrder = [gridViewId];
|
|
4293
6387
|
const selectField = Object.values(fields).find((f) => f.type === "singleSelect");
|
|
4294
6388
|
if (selectField) {
|
|
4295
|
-
const kanbanViewId = `vw_kanban_${
|
|
6389
|
+
const kanbanViewId = `vw_kanban_${generateRandomId5(4)}`;
|
|
4296
6390
|
views[kanbanViewId] = {
|
|
4297
6391
|
id: kanbanViewId,
|
|
4298
6392
|
name: "\u770B\u677F\u89C6\u56FE",
|
|
@@ -4325,7 +6419,7 @@ function importCsvToBaseTable(csvText, options) {
|
|
|
4325
6419
|
}
|
|
4326
6420
|
|
|
4327
6421
|
// src/exporter/xlsx-codec.ts
|
|
4328
|
-
import { generateRandomId as
|
|
6422
|
+
import { generateRandomId as generateRandomId6 } from "@univerjs/core";
|
|
4329
6423
|
var UTF8_ENCODER = new TextEncoder();
|
|
4330
6424
|
var UTF8_DECODER = new TextDecoder("utf-8");
|
|
4331
6425
|
var CRC32_TABLE = (() => {
|
|
@@ -5004,7 +7098,7 @@ function importXlsxBytesToBase(bytes, options) {
|
|
|
5004
7098
|
continue;
|
|
5005
7099
|
}
|
|
5006
7100
|
const grid = parseWorksheetGrid(wsXml, sharedStrings, dateStyleIds);
|
|
5007
|
-
const tid = `tbl_${sheetIdx + 1}_${
|
|
7101
|
+
const tid = `tbl_${sheetIdx + 1}_${generateRandomId6(4)}`;
|
|
5008
7102
|
const table = buildBaseTableFromGridRows(grid.length ? grid : [["\u6807\u9898"]], {
|
|
5009
7103
|
tableId: tid,
|
|
5010
7104
|
tableName: sheetName
|
|
@@ -5015,7 +7109,7 @@ function importXlsxBytesToBase(bytes, options) {
|
|
|
5015
7109
|
}
|
|
5016
7110
|
if (tableOrder.length === 0) {
|
|
5017
7111
|
const fallbackTbl = buildBaseTableFromGridRows([["\u6807\u9898"]], {
|
|
5018
|
-
tableId: `tbl_1_${
|
|
7112
|
+
tableId: `tbl_1_${generateRandomId6(4)}`,
|
|
5019
7113
|
tableName: "Sheet1"
|
|
5020
7114
|
});
|
|
5021
7115
|
tables[fallbackTbl.id] = fallbackTbl;
|
|
@@ -5023,7 +7117,7 @@ function importXlsxBytesToBase(bytes, options) {
|
|
|
5023
7117
|
}
|
|
5024
7118
|
const firstTbl = tables[tableOrder[0]];
|
|
5025
7119
|
return createDefaultBaseUnitData({
|
|
5026
|
-
id: options?.id || `base-${
|
|
7120
|
+
id: options?.id || `base-${generateRandomId6(6)}`,
|
|
5027
7121
|
name: options?.name || "\u5BFC\u5165\u591A\u7EF4\u6570\u636E\u7C3F",
|
|
5028
7122
|
activeTableId: firstTbl.id,
|
|
5029
7123
|
activeViewId: firstTbl.activeViewId,
|
|
@@ -5033,10 +7127,10 @@ function importXlsxBytesToBase(bytes, options) {
|
|
|
5033
7127
|
}
|
|
5034
7128
|
|
|
5035
7129
|
// src/services/base-io.service.ts
|
|
5036
|
-
import { createIdentifier, Disposable, generateRandomId as
|
|
7130
|
+
import { createIdentifier as createIdentifier2, Disposable as Disposable2, generateRandomId as generateRandomId7 } from "@univerjs/core";
|
|
5037
7131
|
import { Subject as Subject2 } from "rxjs";
|
|
5038
|
-
var IBaseIoService =
|
|
5039
|
-
var BaseIoService = class extends
|
|
7132
|
+
var IBaseIoService = createIdentifier2("univer.bases.io.service");
|
|
7133
|
+
var BaseIoService = class extends Disposable2 {
|
|
5040
7134
|
constructor() {
|
|
5041
7135
|
super(...arguments);
|
|
5042
7136
|
this._adapter = { name: "builtin-pure-ts" };
|
|
@@ -5077,7 +7171,7 @@ var BaseIoService = class extends Disposable {
|
|
|
5077
7171
|
delimiter
|
|
5078
7172
|
});
|
|
5079
7173
|
return createDefaultBaseUnitData({
|
|
5080
|
-
id: options?.id || `base-${
|
|
7174
|
+
id: options?.id || `base-${generateRandomId7(6)}`,
|
|
5081
7175
|
name: options?.name || table.name,
|
|
5082
7176
|
activeTableId: table.id,
|
|
5083
7177
|
activeViewId: table.activeViewId,
|
|
@@ -5115,12 +7209,12 @@ var BaseIoService = class extends Disposable {
|
|
|
5115
7209
|
};
|
|
5116
7210
|
|
|
5117
7211
|
// src/services/base-selection.service.ts
|
|
5118
|
-
import { createIdentifier as
|
|
7212
|
+
import { createIdentifier as createIdentifier3, Disposable as Disposable3 } from "@univerjs/core";
|
|
5119
7213
|
import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
|
|
5120
|
-
var IBaseSelectionService =
|
|
7214
|
+
var IBaseSelectionService = createIdentifier3(
|
|
5121
7215
|
"univer.bases.selection.service"
|
|
5122
7216
|
);
|
|
5123
|
-
var BaseSelectionService = class extends
|
|
7217
|
+
var BaseSelectionService = class extends Disposable3 {
|
|
5124
7218
|
constructor() {
|
|
5125
7219
|
super(...arguments);
|
|
5126
7220
|
this._state$ = new BehaviorSubject2({
|
|
@@ -5129,6 +7223,7 @@ var BaseSelectionService = class extends Disposable2 {
|
|
|
5129
7223
|
searchQuery: "",
|
|
5130
7224
|
activeModal: null,
|
|
5131
7225
|
linkPickerSession: null,
|
|
7226
|
+
editingAutomationRuleId: null,
|
|
5132
7227
|
lastToastMessage: null
|
|
5133
7228
|
});
|
|
5134
7229
|
this.state$ = this._state$.asObservable();
|
|
@@ -5170,14 +7265,24 @@ var BaseSelectionService = class extends Disposable2 {
|
|
|
5170
7265
|
this._state$.next({
|
|
5171
7266
|
...this.getState(),
|
|
5172
7267
|
activeModal: modal,
|
|
5173
|
-
...modal !== "linkPicker" ? { linkPickerSession: null } : {}
|
|
7268
|
+
...modal !== "linkPicker" ? { linkPickerSession: null } : {},
|
|
7269
|
+
...modal !== "automationBuilder" ? { editingAutomationRuleId: null } : {}
|
|
5174
7270
|
});
|
|
5175
7271
|
}
|
|
5176
7272
|
openLinkPicker(session) {
|
|
5177
7273
|
this._state$.next({
|
|
5178
7274
|
...this.getState(),
|
|
5179
7275
|
activeModal: session ? "linkPicker" : null,
|
|
5180
|
-
linkPickerSession: session
|
|
7276
|
+
linkPickerSession: session,
|
|
7277
|
+
editingAutomationRuleId: null
|
|
7278
|
+
});
|
|
7279
|
+
}
|
|
7280
|
+
openAutomationBuilder(ruleId) {
|
|
7281
|
+
this._state$.next({
|
|
7282
|
+
...this.getState(),
|
|
7283
|
+
activeModal: "automationBuilder",
|
|
7284
|
+
linkPickerSession: null,
|
|
7285
|
+
editingAutomationRuleId: ruleId ?? null
|
|
5181
7286
|
});
|
|
5182
7287
|
}
|
|
5183
7288
|
notifyToast(message) {
|
|
@@ -5248,12 +7353,16 @@ var UniverBasesPlugin = class extends Plugin {
|
|
|
5248
7353
|
this.disposeWithMe({ dispose: () => focusSub.unsubscribe() });
|
|
5249
7354
|
const dependencies = [
|
|
5250
7355
|
[IBaseSelectionService, { useClass: BaseSelectionService }],
|
|
5251
|
-
[IBaseIoService, { useClass: BaseIoService }]
|
|
7356
|
+
[IBaseIoService, { useClass: BaseIoService }],
|
|
7357
|
+
[IBaseAutomationService, { useClass: BaseAutomationService }]
|
|
5252
7358
|
];
|
|
5253
7359
|
dependencies.forEach((dep) => this._injector.add(dep));
|
|
5254
7360
|
if (this._config.io) {
|
|
5255
7361
|
this._injector.get(IBaseIoService).setAdapter(this._config.io);
|
|
5256
7362
|
}
|
|
7363
|
+
if (this._config.webhookExecutor) {
|
|
7364
|
+
this._injector.get(IBaseAutomationService).setWebhookExecutor(this._config.webhookExecutor);
|
|
7365
|
+
}
|
|
5257
7366
|
const commands = [
|
|
5258
7367
|
// Mutations
|
|
5259
7368
|
ApplyBaseTablesStateMutation,
|
|
@@ -5282,7 +7391,12 @@ var UniverBasesPlugin = class extends Plugin {
|
|
|
5282
7391
|
AddBaseDashboardWidgetCommand,
|
|
5283
7392
|
UpdateBaseDashboardWidgetCommand,
|
|
5284
7393
|
DeleteBaseDashboardWidgetCommand,
|
|
5285
|
-
ReplaceBaseSnapshotCommand
|
|
7394
|
+
ReplaceBaseSnapshotCommand,
|
|
7395
|
+
UpdateBaseDetailLayoutCommand,
|
|
7396
|
+
SaveBaseAutomationRuleCommand,
|
|
7397
|
+
DeleteBaseAutomationRuleCommand,
|
|
7398
|
+
ToggleBaseAutomationRuleCommand,
|
|
7399
|
+
TriggerBaseAutomationCommand
|
|
5286
7400
|
];
|
|
5287
7401
|
for (const cmd of commands) {
|
|
5288
7402
|
this.disposeWithMe(this._commandService.registerCommand(cmd));
|
|
@@ -5296,7 +7410,7 @@ UniverBasesPlugin = __decorateClass([
|
|
|
5296
7410
|
], UniverBasesPlugin);
|
|
5297
7411
|
|
|
5298
7412
|
// src/index.ts
|
|
5299
|
-
var VERSION = "1.6.
|
|
7413
|
+
var VERSION = "1.6.219";
|
|
5300
7414
|
export {
|
|
5301
7415
|
ALL_BASE_FIELD_TYPES,
|
|
5302
7416
|
AddBaseDashboardWidgetCommand,
|
|
@@ -5308,46 +7422,59 @@ export {
|
|
|
5308
7422
|
ApplyBaseTablesStateMutation,
|
|
5309
7423
|
BASE_ROW_COLOR_PALETTE,
|
|
5310
7424
|
BASE_SELECT_PALETTE,
|
|
7425
|
+
BaseAutomationService,
|
|
5311
7426
|
BaseIoService,
|
|
5312
7427
|
BaseSelectionService,
|
|
5313
7428
|
BaseUnitModel,
|
|
5314
7429
|
BatchInsertBaseRecordsCommand,
|
|
5315
7430
|
COMPUTED_BASE_FIELD_TYPES,
|
|
7431
|
+
DeleteBaseAutomationRuleCommand,
|
|
5316
7432
|
DeleteBaseDashboardWidgetCommand,
|
|
5317
7433
|
DeleteBaseFieldCommand,
|
|
5318
7434
|
DeleteBaseRecordsCommand,
|
|
5319
7435
|
DeleteBaseTableCommand,
|
|
5320
7436
|
DeleteBaseViewCommand,
|
|
7437
|
+
IBaseAutomationService,
|
|
5321
7438
|
IBaseIoService,
|
|
5322
7439
|
IBaseSelectionService,
|
|
7440
|
+
MAX_AUTOMATION_RECURSION_DEPTH,
|
|
5323
7441
|
ReorderBaseFieldsCommand,
|
|
5324
7442
|
ReplaceBaseSnapshotCommand,
|
|
5325
7443
|
ReplaceBaseSnapshotMutation,
|
|
7444
|
+
SaveBaseAutomationRuleCommand,
|
|
5326
7445
|
SetActiveBaseTableCommand,
|
|
5327
7446
|
SetActiveBaseViewCommand,
|
|
5328
7447
|
SetBaseActiveNavigationMutation,
|
|
5329
7448
|
SetBaseWorkspaceModeCommand,
|
|
5330
7449
|
SubmitBaseFormResponseCommand,
|
|
7450
|
+
ToggleBaseAutomationRuleCommand,
|
|
7451
|
+
TriggerBaseAutomationCommand,
|
|
5331
7452
|
UNIVER_BASES_PLUGIN_NAME,
|
|
5332
7453
|
UNIVER_BASE_SCHEMA,
|
|
5333
7454
|
UNIVER_BASE_SCHEMA_VERSION,
|
|
5334
7455
|
UniverBasesPlugin,
|
|
5335
7456
|
UpdateBaseDashboardWidgetCommand,
|
|
7457
|
+
UpdateBaseDetailLayoutCommand,
|
|
5336
7458
|
UpdateBaseFieldCommand,
|
|
5337
7459
|
UpdateBaseRecordCommand,
|
|
5338
7460
|
UpdateBaseTableCommand,
|
|
5339
7461
|
UpdateBaseViewCommand,
|
|
5340
7462
|
VERSION,
|
|
7463
|
+
applyBaseRowReadScope,
|
|
5341
7464
|
buildBaseTableFromGridRows,
|
|
5342
7465
|
buildLinearBarcodeBars,
|
|
5343
7466
|
coerceImportedCellValue,
|
|
5344
7467
|
computeBaseDashboardWidget,
|
|
5345
7468
|
computeBaseGanttTasks,
|
|
7469
|
+
computeBaseHierarchicalList,
|
|
5346
7470
|
computeFieldSummary,
|
|
5347
7471
|
createDefaultBaseUnitData,
|
|
5348
7472
|
createSampleCrmBaseData,
|
|
5349
7473
|
createSampleProjectBaseData,
|
|
7474
|
+
doesAutomationTriggerMatch,
|
|
7475
|
+
evaluateAutomationConditions,
|
|
5350
7476
|
evaluateBaseFormula,
|
|
7477
|
+
executeBaseAutomations,
|
|
5351
7478
|
exportBaseTableToCsv,
|
|
5352
7479
|
exportBaseToXlsxBytes,
|
|
5353
7480
|
formatBaseCellValue,
|
|
@@ -5355,16 +7482,27 @@ export {
|
|
|
5355
7482
|
importCsvToBaseTable,
|
|
5356
7483
|
importXlsxBytesToBase,
|
|
5357
7484
|
inferFieldFromColumnSamples,
|
|
7485
|
+
interpolateAutomationCellValue,
|
|
7486
|
+
interpolateAutomationString,
|
|
5358
7487
|
isCellValueEmpty,
|
|
5359
7488
|
isComputedBaseField,
|
|
7489
|
+
isFormFieldRequired,
|
|
7490
|
+
isFormFieldVisible,
|
|
5360
7491
|
matchesBaseFilterRule,
|
|
7492
|
+
mergeMultipleSourcesIntoBaseTable,
|
|
7493
|
+
normalizeAutomationSteps,
|
|
5361
7494
|
normalizeLinkIds,
|
|
5362
7495
|
parseDelimitedText,
|
|
5363
7496
|
queryBaseTableView,
|
|
5364
7497
|
resolveBaseCellValue,
|
|
7498
|
+
resolveBaseDetailLayout,
|
|
5365
7499
|
resolveLinkedRecordItems,
|
|
5366
7500
|
roundToPrecision,
|
|
7501
|
+
runBaseAutomationsInPlaceSync,
|
|
5367
7502
|
serializeDelimitedText,
|
|
7503
|
+
syncBaseTables,
|
|
7504
|
+
syncOneWayBaseTable,
|
|
7505
|
+
syncTwoWayBaseTables,
|
|
5368
7506
|
toNumericValue
|
|
5369
7507
|
};
|
|
5370
7508
|
//# sourceMappingURL=index.js.map
|