-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathdata.ts
369 lines (340 loc) · 10.1 KB
/
data.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import { DEFAULT_REVISION_ID } from "../constants";
import { UuidGenerator } from "../helpers/index";
import { isValidLocale } from "../helpers/locale";
import { StateUpdateMessage } from "../types/collaborative/transport_service";
import {
CoreCommand,
DEFAULT_LOCALE,
ExcelSheetData,
ExcelWorkbookData,
SheetData,
UID,
WorkbookData,
} from "../types/index";
import { XlsxReader } from "../xlsx/xlsx_reader";
import { migrationStepRegistry } from "./migration_steps";
/**
* Represents the current version of the exported JSON data.
* A new version must be created whenever a breaking change is introduced in the export format.
* To define a new version, add an upgrade function to `migrationStepRegistry`.
*/
export function getCurrentVersion() {
return getSortedVersions().at(-1)!;
}
function getSortedVersions() {
return migrationStepRegistry.getKeys().sort(compareVersions);
}
const INITIAL_SHEET_ID = "Sheet1";
/**
* This function tries to load anything that could look like a valid
* workbookData object. It applies any migrations, if needed, and return a
* current, complete workbookData object.
*
* It also ensures that there is at least one sheet.
*/
export function load(data?: any, verboseImport?: boolean): WorkbookData {
if (!data) {
return createEmptyWorkbookData();
}
console.debug("### Loading data ###");
const start = performance.now();
if (data["[Content_Types].xml"]) {
const reader = new XlsxReader(data);
data = reader.convertXlsx();
if (verboseImport) {
for (let parsingError of reader.warningManager.warnings.sort()) {
console.warn(parsingError);
}
}
}
// apply migrations, if needed
if ("version" in data) {
if (isLegacyVersioning(data)) {
data.version = LEGACY_VERSION_MAPPING[data.version];
}
console.debug("Migrating data from version", data.version);
if (data.version !== getCurrentVersion()) {
data = migrate(data);
}
}
data = repairData(data);
console.debug("Data loaded in", performance.now() - start, "ms");
console.debug("###");
return data;
}
const LEGACY_VERSION_MAPPING = {
25: "18.2",
24: "18.1.1",
23: "18.1",
22: "18.0.4",
21: "18.0.3",
20: "18.0.2",
19: "18.0.1",
18: "18.0",
17: "17.4",
16: "17.3",
15: "17.2",
14: "16.4",
13: "16.3",
12: "15.4",
// not accurate starting at this point
11: "0.10",
10: "0.9",
9: "0.8",
8: "0.7",
7: "0.6",
6: "0.5",
5: "0.4",
4: "0.3",
3: "0.2",
2: "0.1",
1: "0",
};
/**
* Versions used to be an incremented integer.
* This was later changed to match release versions (matching Odoo release names).
*/
function isLegacyVersioning(data: { version: number | string }): boolean {
return typeof data.version === "number";
}
// -----------------------------------------------------------------------------
// Migrations
// -----------------------------------------------------------------------------
function compareVersions(v1: string, v2: string): number {
const version1 = v1.split(".").map(Number);
const version2 = v2.split(".").map(Number);
for (let i = 0; i < Math.max(version1.length, version2.length); i++) {
const part1 = version1[i] || 0;
const part2 = version2[i] || 0;
if (part1 > part2) {
return 1;
}
if (part1 < part2) {
return -1;
}
}
return 0;
}
function migrate(data: any): WorkbookData {
const start = performance.now();
const versions = getSortedVersions();
const index = versions.findIndex((v) => v === data.version);
for (let i = index + 1; i < versions.length; i++) {
const nextVersion = versions[i];
data = migrationStepRegistry.get(nextVersion).migrate(data);
}
console.debug("Data migrated in", performance.now() - start, "ms");
return data;
}
/**
* This function is used to repair faulty data independently of the migration.
*/
export function repairData(data: Partial<WorkbookData>): Partial<WorkbookData> {
data = forceUnicityOfFigure(data);
data = setDefaults(data);
return data;
}
/**
* Force the unicity of figure ids accross sheets
*/
function forceUnicityOfFigure(data: Partial<WorkbookData>): Partial<WorkbookData> {
if (data.uniqueFigureIds) {
return data;
}
const figureIds = new Set();
const uuidGenerator = new UuidGenerator();
for (const sheet of data.sheets || []) {
for (const figure of sheet.figures || []) {
if (figureIds.has(figure.id)) {
figure.id += uuidGenerator.smallUuid();
}
figureIds.add(figure.id);
}
}
data.uniqueFigureIds = true;
return data;
}
/**
* sanity check: try to fix missing fields/corrupted state by providing
* sensible default values
*/
function setDefaults(partialData: Partial<WorkbookData>): Partial<WorkbookData> {
const data: WorkbookData = Object.assign(createEmptyWorkbookData(), partialData, {
version: getCurrentVersion(),
});
data.sheets = data.sheets
? data.sheets.map((s, i) =>
Object.assign(createEmptySheet(`Sheet${i + 1}`, `Sheet${i + 1}`), s)
)
: [];
if (data.sheets.length === 0) {
data.sheets.push(createEmptySheet(INITIAL_SHEET_ID, "Sheet1"));
}
if (!isValidLocale(data.settings.locale)) {
data.settings!.locale = DEFAULT_LOCALE;
}
return data;
}
/**
* The goal of this function is to repair corrupted/wrong initial messages caused by
* a bug.
* The bug should obviously be fixed, but it's too late for existing spreadsheet.
*/
export function repairInitialMessages(
data: Partial<WorkbookData>,
initialMessages: StateUpdateMessage[]
): StateUpdateMessage[] {
initialMessages = fixTranslatedSheetIds(data, initialMessages);
initialMessages = dropCommands(initialMessages, "SORT_CELLS");
initialMessages = dropCommands(initialMessages, "SET_DECIMAL");
initialMessages = fixChartDefinitions(data, initialMessages);
return initialMessages;
}
/**
* When the workbook data is originally empty, a new one is generated on-the-fly.
* A bug caused the sheet id to be non-deterministic. The sheet id was propagated in
* commands.
* This function repairs initial commands with a wrong sheetId.
*/
function fixTranslatedSheetIds(
data: Partial<WorkbookData>,
initialMessages: StateUpdateMessage[]
): StateUpdateMessage[] {
// the fix is only needed when the workbook is generated on-the-fly
if (Object.keys(data).length !== 0) {
return initialMessages;
}
const sheetIds: UID[] = [];
const messages: StateUpdateMessage[] = [];
const fixSheetId = (cmd: CoreCommand) => {
if (cmd.type === "CREATE_SHEET") {
sheetIds.push(cmd.sheetId);
} else if ("sheetId" in cmd && !sheetIds.includes(cmd.sheetId)) {
return { ...cmd, sheetId: INITIAL_SHEET_ID };
}
return cmd;
};
for (const message of initialMessages) {
if (message.type === "REMOTE_REVISION") {
messages.push({
...message,
commands: message.commands.map(fixSheetId),
});
} else {
messages.push(message);
}
}
return messages;
}
function dropCommands(initialMessages: StateUpdateMessage[], commandType: string) {
const messages: StateUpdateMessage[] = [];
for (const message of initialMessages) {
if (message.type === "REMOTE_REVISION") {
messages.push({
...message,
commands: message.commands.filter((command) => command.type !== commandType),
});
} else {
messages.push(message);
}
}
return messages;
}
function fixChartDefinitions(data: Partial<WorkbookData>, initialMessages: StateUpdateMessage[]) {
const messages: StateUpdateMessage[] = [];
const map = {};
for (const sheet of data.sheets || []) {
sheet.figures?.forEach((figure) => {
if (figure.tag === "chart") {
// chart definition
map[figure.id] = figure.data;
}
});
}
for (const message of initialMessages) {
if (message.type === "REMOTE_REVISION") {
const commands: CoreCommand[] = [];
for (const cmd of message.commands) {
let command = cmd;
switch (cmd.type) {
case "CREATE_CHART":
map[cmd.id] = cmd.definition;
break;
case "UPDATE_CHART":
if (!map[cmd.id]) {
/** the chart does not exist on the map, it might have been created after a duplicate sheet.
* We don't have access to the definition, so we skip the command.
*/
console.log(`Fix chart definition: chart with id ${cmd.id} not found.`);
continue;
}
const definition = map[cmd.id];
const newDefinition = { ...definition, ...cmd.definition };
command = { ...cmd, definition: newDefinition };
map[cmd.id] = newDefinition;
break;
}
commands.push(command);
}
messages.push({
...message,
commands,
});
} else {
messages.push(message);
}
}
return messages;
}
// -----------------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------------
export function createEmptySheet(sheetId: UID, name: string): SheetData {
return {
id: sheetId,
name,
colNumber: 26,
rowNumber: 100,
cells: {},
styles: {},
formats: {},
borders: {},
cols: {},
rows: {},
merges: [],
conditionalFormats: [],
dataValidationRules: [],
figures: [],
tables: [],
isVisible: true,
};
}
export function createEmptyWorkbookData(sheetName = "Sheet1"): WorkbookData {
return {
version: getCurrentVersion(),
sheets: [createEmptySheet(INITIAL_SHEET_ID, sheetName)],
styles: {},
formats: {},
borders: {},
revisionId: DEFAULT_REVISION_ID,
uniqueFigureIds: true,
settings: { locale: DEFAULT_LOCALE },
pivots: {},
pivotNextId: 1,
customTableStyles: {},
};
}
export function createEmptyExcelSheet(sheetId: UID, name: string): ExcelSheetData {
return {
...(createEmptySheet(sheetId, name) as Omit<ExcelSheetData, "charts">),
charts: [],
images: [],
cellValues: {},
};
}
export function createEmptyExcelWorkbookData(): ExcelWorkbookData {
return {
...createEmptyWorkbookData(),
sheets: [createEmptyExcelSheet(INITIAL_SHEET_ID, "Sheet1")],
};
}