| 1 |
import { uuidv4 } from "@point_of_sale/utils"; |
| 2 |
import { TrapDisabler } from "@point_of_sale/proxy_trap"; |
| 3 |
import { RecordStore } from "./record_store"; |
| 4 |
import { |
| 5 |
RELATION_TYPES, |
| 6 |
X2MANY_TYPES, |
| 7 |
DATE_TIME_TYPE, |
| 8 |
RAW_SYMBOL, |
| 9 |
STORE_SYMBOL, |
| 10 |
mapObj, |
| 11 |
convertDateTimeToRaw, |
| 12 |
convertDateToRaw, |
| 13 |
BACKREF_PREFIX, |
| 14 |
PARENT_X2MANY_TYPES, |
| 15 |
SERIALIZED_UI_STATE_PROP, |
| 16 |
AggregatedUpdates, |
| 17 |
} from "./utils"; |
| 18 |
import { Base } from "./base"; |
| 19 |
import { processModelDefs } from "./model_defs"; |
| 20 |
import { createExtraField, processModelClasses } from "./model_classes"; |
| 21 |
import { ormSerialization } from "./serialization"; |
| 22 |
|
| 23 |
const AVAILABLE_EVENT = ["create", "update", "delete"]; |
| 24 |
|
| 25 |
export function createRelatedModels(modelDefs, modelClasses = {}, opts = {}) { |
| 26 |
const database = opts.databaseTable || {}; |
| 27 |
const dynamicModels = opts.dynamicModels || []; |
| 28 |
const store = new RecordStore(Object.keys(modelDefs), opts.databaseIndex); |
| 29 |
const [inverseMap, processedModelDefs] = processModelDefs(modelDefs); |
| 30 |
processModelClasses(processedModelDefs, modelClasses); |
| 31 |
const callbacks = mapObj(processedModelDefs, () => []); |
| 32 |
const commands = mapObj(processedModelDefs, () => ({ |
| 33 |
delete: new Map(), |
| 34 |
unlink: new Map(), |
| 35 |
})); |
| 36 |
function getFields(model) { |
| 37 |
return processedModelDefs[model]; |
| 38 |
} |
| 39 |
const disabler = new TrapDisabler(); |
| 40 |
|
| 41 |
// A cache for the backlink indexed maps: Map<RelationName, Map<ParentId, Record[]>> |
| 42 |
const backlinkIndexes = new Map(); |
| 43 |
|
| 44 |
/** |
| 45 |
* A model (e.g. pos.order) points to an instance of this class. |
| 46 |
*/ |
| 47 |
class Model { |
| 48 |
constructor(name) { |
| 49 |
this.name = name; |
| 50 |
// Ensures reactivity by accessing the recordStore directly from the instance |
| 51 |
this[STORE_SYMBOL] = store; |
| 52 |
this.records = store.getRecordsMap(this.name); // Used by some modules... |
| 53 |
} |
| 54 |
|
| 55 |
get models() { |
| 56 |
return models; |
| 57 |
} |
| 58 |
|
| 59 |
get fields() { |
| 60 |
return getFields(this.name); |
| 61 |
} |
| 62 |
|
| 63 |
get orderedRecords() { |
| 64 |
return this[STORE_SYMBOL].getOrderedRecords(this.name); |
| 65 |
} |
| 66 |
|
| 67 |
exists(id) { |
| 68 |
return !!this[STORE_SYMBOL].getById(this.name, id); |
| 69 |
} |
| 70 |
|
| 71 |
create(vals) { |
| 72 |
return disabler.call((...args) => this._create(...args), vals); |
| 73 |
} |
| 74 |
|
| 75 |
deserialize(vals) { |
| 76 |
return this.create(vals); |
| 77 |
} |
| 78 |
|
| 79 |
createMany(valsList) { |
| 80 |
const result = []; |
| 81 |
for (const vals of valsList) { |
| 82 |
result.push(this.create(vals)); |
| 83 |
} |
| 84 |
return result; |
| 85 |
} |
| 86 |
|
| 87 |
update(record, vals, opts = {}) { |
| 88 |
return disabler.call((...args) => this._update(...args), record, vals, { |
| 89 |
...opts, |
| 90 |
}); |
| 91 |
} |
| 92 |
|
| 93 |
delete(record, opts = {}) { |
| 94 |
return disabler.call((...args) => this._delete(...args), record, opts); |
| 95 |
} |
| 96 |
|
| 97 |
deleteMany(toDelete, opts = {}) { |
| 98 |
const result = []; |
| 99 |
for (const d of toDelete) { |
| 100 |
result.push(this.delete(d, opts)); |
| 101 |
} |
| 102 |
return result; |
| 103 |
} |
| 104 |
|
| 105 |
read(value) { |
| 106 |
const id = /^\d+$/.test(value) ? parseInt(value) : value; // In case of ID came from an input |
| 107 |
return this[STORE_SYMBOL].getById(this.name, id); |
| 108 |
} |
| 109 |
|
| 110 |
readFirst() { |
| 111 |
return this.orderedRecords[0]; |
| 112 |
} |
| 113 |
|
| 114 |
readBy(key, val) { |
| 115 |
return this[STORE_SYMBOL].get(this.name, key, val); |
| 116 |
} |
| 117 |
|
| 118 |
readAll() { |
| 119 |
return this.orderedRecords; |
| 120 |
} |
| 121 |
|
| 122 |
readAllBy(key) { |
| 123 |
return this[STORE_SYMBOL].getRecordsByIds(this.name, key); |
| 124 |
} |
| 125 |
|
| 126 |
readMany(ids) { |
| 127 |
return ids.map((value) => this.read(value)).filter(Boolean); |
| 128 |
} |
| 129 |
|
| 130 |
// aliases |
| 131 |
getAllBy() { |
| 132 |
return this.readAllBy(...arguments); |
| 133 |
} |
| 134 |
|
| 135 |
getAllIds() { |
| 136 |
return this[STORE_SYMBOL].getRecordsIds(this.name); |
| 137 |
} |
| 138 |
|
| 139 |
getAll() { |
| 140 |
return this.readAll(...arguments); |
| 141 |
} |
| 142 |
|
| 143 |
getBy() { |
| 144 |
return this.readBy(...arguments); |
| 145 |
} |
| 146 |
|
| 147 |
get() { |
| 148 |
return this.read(...arguments); |
| 149 |
} |
| 150 |
|
| 151 |
getFirst() { |
| 152 |
return this.readFirst(...arguments); |
| 153 |
} |
| 154 |
|
| 155 |
// array prototype |
| 156 |
map(fn) { |
| 157 |
return this.orderedRecords.map(fn); |
| 158 |
} |
| 159 |
|
| 160 |
reduce(fn, initialValue) { |
| 161 |
return this.orderedRecords.reduce(fn, initialValue); |
| 162 |
} |
| 163 |
|
| 164 |
flatMap(fn) { |
| 165 |
return this.orderedRecords.flatMap(fn); |
| 166 |
} |
| 167 |
|
| 168 |
forEach(fn) { |
| 169 |
return this.orderedRecords.forEach(fn); |
| 170 |
} |
| 171 |
|
| 172 |
some(fn) { |
| 173 |
return this.orderedRecords.some(fn); |
| 174 |
} |
| 175 |
|
| 176 |
every(fn) { |
| 177 |
return this.orderedRecords.every(fn); |
| 178 |
} |
| 179 |
|
| 180 |
find(fn) { |
| 181 |
return this.orderedRecords.find(fn); |
| 182 |
} |
| 183 |
|
| 184 |
filter(fn) { |
| 185 |
return this.orderedRecords.filter(fn); |
| 186 |
} |
| 187 |
|
| 188 |
sort(fn) { |
| 189 |
return this.orderedRecords.sort(fn); |
| 190 |
} |
| 191 |
|
| 192 |
indexOf(record) { |
| 193 |
return this.orderedRecords.indexOf(record); |
| 194 |
} |
| 195 |
|
| 196 |
get length() { |
| 197 |
return this[STORE_SYMBOL].getRecordCount(this.name); |
| 198 |
} |
| 199 |
|
| 200 |
getParentFields() { |
| 201 |
return Object.values(getFields(this.name)).filter((field) => { |
| 202 |
if (field.dummy || !PARENT_X2MANY_TYPES.has(field.type)) { |
| 203 |
return false; |
| 204 |
} |
| 205 |
const inverseField = inverseMap.get(field); |
| 206 |
return inverseField && !inverseField.dummy; |
| 207 |
}); |
| 208 |
} |
| 209 |
|
| 210 |
// External callbacks |
| 211 |
addEventListener(event, callback) { |
| 212 |
if (!AVAILABLE_EVENT.includes(event)) { |
| 213 |
throw new Error(`Event '${event}' is not available`); |
| 214 |
} |
| 215 |
|
| 216 |
if (!(event in callbacks[this.name])) { |
| 217 |
callbacks[this.name][event] = new Map(); |
| 218 |
} |
| 219 |
|
| 220 |
const key = uuidv4(); |
| 221 |
callbacks[this.name][event].set(key, callback); |
| 222 |
return () => callbacks[this.name][event].delete(key); |
| 223 |
} |
| 224 |
|
| 225 |
triggerEvents(event, data) { |
| 226 |
if ( |
| 227 |
!(event in callbacks[this.name]) || |
| 228 |
callbacks[this.name][event].size === 0 || |
| 229 |
!data |
| 230 |
) { |
| 231 |
return; |
| 232 |
} |
| 233 |
|
| 234 |
for (const callback of callbacks[this.name][event].values()) { |
| 235 |
callback(data); |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
_sanitizeRawData(vals, options = {}) { |
| 240 |
const { connectRecords = true, serverData = false, existingRecord = false } = options; |
| 241 |
let dataToConnect; |
| 242 |
if (!vals.uuid && database[this.name]?.key === "uuid") { |
| 243 |
vals.uuid = uuidv4(); |
| 244 |
} |
| 245 |
vals.id = vals["id"] ?? (vals.uuid || uuidv4()); |
| 246 |
const rawData = { |
| 247 |
id: vals.id, |
| 248 |
}; |
| 249 |
const fields = getFields(this.name); |
| 250 |
const fieldKeys = Object.keys(fields); |
| 251 |
for (let i = 0; i < fieldKeys.length; i++) { |
| 252 |
const fieldName = fieldKeys[i]; |
| 253 |
const field = fields[fieldName]; |
| 254 |
const value = vals[fieldName]; |
| 255 |
if (field.required && (value === undefined || value === null)) { |
| 256 |
throw new Error( |
| 257 |
`'${fieldName}' field is required when creating '${this.name}' record.` |
| 258 |
); |
| 259 |
} |
| 260 |
if (RELATION_TYPES.has(field.type)) { |
| 261 |
if (field.dummy) { |
| 262 |
continue; |
| 263 |
} |
| 264 |
const isX2Many = X2MANY_TYPES.has(field.type); |
| 265 |
const rawValue = isX2Many ? new Set(value) : value; |
| 266 |
const data = existingRecord?.[field.name]; |
| 267 |
let localIds = []; |
| 268 |
if (isX2Many && existingRecord && opts.databaseTable[field.relation]?.key) { |
| 269 |
localIds = data.filter((r) => r.isSynced === false)?.map((r) => r.id) || []; |
| 270 |
} |
| 271 |
|
| 272 |
if (connectRecords) { |
| 273 |
if (!dataToConnect) { |
| 274 |
dataToConnect = { |
| 275 |
updateFields: {}, |
| 276 |
rawValues: {}, |
| 277 |
}; |
| 278 |
} |
| 279 |
dataToConnect.updateFields[field.name] = value; |
| 280 |
if (serverData && !isX2Many) { |
| 281 |
dataToConnect.rawValues[field.name] = rawValue; |
| 282 |
} else if (serverData) { |
| 283 |
dataToConnect.rawValues[field.name] = new Set([ |
| 284 |
...localIds, |
| 285 |
...rawValue, |
| 286 |
]); |
| 287 |
} |
| 288 |
|
| 289 |
if (isX2Many) { |
| 290 |
rawData[field.name] = new Set(); //Default value |
| 291 |
} |
| 292 |
} else { |
| 293 |
if (isX2Many) { |
| 294 |
rawData[field.name] = new Set([...localIds, ...rawValue]); |
| 295 |
} else { |
| 296 |
rawData[field.name] = rawValue; |
| 297 |
} |
| 298 |
} |
| 299 |
} else { |
| 300 |
rawData[fieldName] = DATE_TIME_TYPE.has(field.type) |
| 301 |
? field.type === "datetime" |
| 302 |
? convertDateTimeToRaw(value) |
| 303 |
: convertDateToRaw(value) |
| 304 |
: value; |
| 305 |
} |
| 306 |
} |
| 307 |
//Add other backend fields |
| 308 |
const fieldNames = new Set(fieldKeys); |
| 309 |
let uiState; |
| 310 |
let extraFields; |
| 311 |
for (const key in vals) { |
| 312 |
if (fieldNames.has(key)) { |
| 313 |
continue; |
| 314 |
} |
| 315 |
if (key === SERIALIZED_UI_STATE_PROP) { |
| 316 |
uiState = JSON.parse(vals[key]); |
| 317 |
} else if (serverData) { |
| 318 |
rawData[key] = vals[key]; |
| 319 |
} |
| 320 |
|
| 321 |
if (key[0] === "_" && key[1] !== "_") { |
| 322 |
if (!extraFields) { |
| 323 |
extraFields = []; |
| 324 |
} |
| 325 |
extraFields.push(key); |
| 326 |
} |
| 327 |
} |
| 328 |
return { rawData, uiState, extraFields, dataToConnect }; |
| 329 |
} |
| 330 |
|
| 331 |
_create(vals, opts = {}) { |
| 332 |
const { connectRecords = true, serverData = false, delaySetup = false } = opts; |
| 333 |
const { rawData, uiState, extraFields, dataToConnect } = this._sanitizeRawData(vals, { |
| 334 |
serverData, |
| 335 |
connectRecords, |
| 336 |
}); |
| 337 |
const ModelRecordClass = modelClasses[this.name]; |
| 338 |
let record = new ModelRecordClass({ |
| 339 |
model: this, |
| 340 |
raw: rawData, |
| 341 |
}); |
| 342 |
if (extraFields) { |
| 343 |
createExtraField(record, extraFields, serverData, vals); |
| 344 |
} |
| 345 |
|
| 346 |
//The record store is assigned to each instance to enable store detection changes in the lazy getters |
| 347 |
record[STORE_SYMBOL] = this[STORE_SYMBOL]; |
| 348 |
record = this[STORE_SYMBOL].add(record); |
| 349 |
|
| 350 |
if (dataToConnect) { |
| 351 |
this._connectRecords(record, dataToConnect); |
| 352 |
} |
| 353 |
|
| 354 |
if (!delaySetup) { |
| 355 |
setupRecord(record, vals, uiState); |
| 356 |
record.model.triggerEvents("create", { ids: [record.id] }); |
| 357 |
return record; |
| 358 |
} |
| 359 |
return { record, uiState }; |
| 360 |
} |
| 361 |
|
| 362 |
_connectRecords(record, data) { |
| 363 |
// Connect related records |
| 364 |
this._update(record, data.updateFields, { silent: true }); |
| 365 |
|
| 366 |
// Make sure RAW contains all the ids (some records may not be already loaded) |
| 367 |
// Must be done after connecting related records to ensure correct disconnection from previous records |
| 368 |
// and connection to new ones. |
| 369 |
if (data.rawValues) { |
| 370 |
Object.assign(record[RAW_SYMBOL], data.rawValues); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
_update(record, vals, opts = {}) { |
| 375 |
const ownFields = getFields(this.name); |
| 376 |
let reIndexRecord = false; |
| 377 |
const aggregatedUpdates = new AggregatedUpdates(); |
| 378 |
|
| 379 |
for (const name in vals) { |
| 380 |
if (name === "id" || (name === "uuid" && ownFields[name])) { |
| 381 |
// id can be only updated using loadData |
| 382 |
continue; |
| 383 |
} |
| 384 |
|
| 385 |
const field = ownFields[name]; |
| 386 |
if (!field) { |
| 387 |
if (opts.omitUnknownField) { |
| 388 |
continue; |
| 389 |
} |
| 390 |
throw new Error(`The field '${name}' does not exist in model '${this.name}'`); |
| 391 |
} |
| 392 |
const coModelName = field.relation; |
| 393 |
const coModel = this.models[coModelName]; |
| 394 |
if (field.dummy) { |
| 395 |
throw new Error(`The field '${field.name}' cannot be updated`); |
| 396 |
} |
| 397 |
if (this[STORE_SYMBOL].hasIndex(this.name, field.name)) { |
| 398 |
reIndexRecord = true; |
| 399 |
} |
| 400 |
if (coModel) { |
| 401 |
if (X2MANY_TYPES.has(field.type)) { |
| 402 |
const commands = convertToX2ManyCommands(vals[name], opts.strict); |
| 403 |
for (const cmd of commands) { |
| 404 |
const [command, ...records] = cmd; |
| 405 |
if (command === "unlink") { |
| 406 |
for (const record2 of records) { |
| 407 |
models._disconnect(field, record, record2, aggregatedUpdates); |
| 408 |
} |
| 409 |
} else if (command === "clear") { |
| 410 |
const linkedRecs = record[name]; |
| 411 |
for (const record2 of [...linkedRecs]) { |
| 412 |
models._disconnect(field, record, record2, aggregatedUpdates); |
| 413 |
} |
| 414 |
} else if (command === "create") { |
| 415 |
const newRecords = records.map((vals) => coModel.create(vals)); |
| 416 |
for (const record2 of newRecords) { |
| 417 |
models._connect(field, record, record2, aggregatedUpdates); |
| 418 |
} |
| 419 |
} else if (command === "link") { |
| 420 |
for (const record2 of records) { |
| 421 |
models._connect(field, record, record2, aggregatedUpdates); |
| 422 |
} |
| 423 |
} else if (command === "set") { |
| 424 |
const linkedRecs = record[name]; |
| 425 |
for (const record2 of [...linkedRecs]) { |
| 426 |
models._disconnect(field, record, record2, aggregatedUpdates); |
| 427 |
} |
| 428 |
for (const record2 of records) { |
| 429 |
models._connect(field, record, record2, aggregatedUpdates); |
| 430 |
} |
| 431 |
} else { |
| 432 |
throw new Error("Command '" + command + "' not supported"); |
| 433 |
} |
| 434 |
} |
| 435 |
} else if (field.type === "many2one") { |
| 436 |
const value = vals[name]; |
| 437 |
if (value) { |
| 438 |
const id = value.id || value; |
| 439 |
const exist = coModel.exists(id); |
| 440 |
if (exist) { |
| 441 |
models._connect(field, record, id, aggregatedUpdates); |
| 442 |
} else if (this.models[field.relation] && typeof value === "object") { |
| 443 |
const newRecord = coModel.create(value); |
| 444 |
models._connect(field, record, newRecord, aggregatedUpdates); |
| 445 |
} |
| 446 |
} else if (record[name]) { |
| 447 |
models._disconnect(field, record, record[name], aggregatedUpdates); |
| 448 |
} |
| 449 |
} else { |
| 450 |
throw new Error(`Relation type '${field.type}' not supported`); |
| 451 |
} |
| 452 |
} else { |
| 453 |
const oldValue = record[RAW_SYMBOL][name]; |
| 454 |
let newValue = vals[name]; |
| 455 |
if (DATE_TIME_TYPE.has(field.type)) { |
| 456 |
newValue = |
| 457 |
field.type === "datetime" |
| 458 |
? convertDateTimeToRaw(newValue) |
| 459 |
: convertDateToRaw(newValue); |
| 460 |
} |
| 461 |
if (newValue !== oldValue) { |
| 462 |
record[RAW_SYMBOL][name] = newValue; |
| 463 |
aggregatedUpdates.add(record, name); |
| 464 |
} |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
if (reIndexRecord) { |
| 469 |
this[STORE_SYMBOL].remove(record); |
| 470 |
this[STORE_SYMBOL].add(record); |
| 471 |
} |
| 472 |
|
| 473 |
aggregatedUpdates.fireEventAndDirty({ |
| 474 |
silentModels: opts.silent ? [record.model.name] : [], |
| 475 |
}); |
| 476 |
} |
| 477 |
|
| 478 |
_delete(record, opts = {}) { |
| 479 |
const id = record.id; |
| 480 |
const ownFields = getFields(this.name); |
| 481 |
const handleCommand = (inverse, field, record, backend = false) => { |
| 482 |
if (inverse && !inverse.dummy && record.isSynced) { |
| 483 |
const modelCommands = commands[field.relation]; |
| 484 |
const map = backend ? modelCommands.delete : modelCommands.unlink; |
| 485 |
const oldVal = map.get(inverse.name); |
| 486 |
map.set(inverse.name, [ |
| 487 |
...(oldVal || []), |
| 488 |
{ id: record.id, parentId: record[field.name].id }, |
| 489 |
]); |
| 490 |
} |
| 491 |
}; |
| 492 |
this[STORE_SYMBOL].remove(record); |
| 493 |
const aggregatedUpdates = new AggregatedUpdates(); |
| 494 |
for (const name in ownFields) { |
| 495 |
const field = ownFields[name]; |
| 496 |
const inverse = inverseMap.get(field); |
| 497 |
if (field.dummy) { |
| 498 |
continue; |
| 499 |
} |
| 500 |
if (X2MANY_TYPES.has(field.type)) { |
| 501 |
const records = record[name]; |
| 502 |
if (records) { |
| 503 |
for (const record2 of [...records]) { |
| 504 |
handleCommand(inverse, field, record, opts.backend); |
| 505 |
models._disconnect(field, record, record2, aggregatedUpdates); |
| 506 |
} |
| 507 |
} |
| 508 |
} else if (field.type === "many2one" && typeof record[name] === "object") { |
| 509 |
handleCommand(inverse, field, record, opts.backend); |
| 510 |
models._disconnect(field, record, record[name], aggregatedUpdates); |
| 511 |
} |
| 512 |
} |
| 513 |
|
| 514 |
aggregatedUpdates.remove(record); |
| 515 |
aggregatedUpdates.fireEventAndDirty({ |
| 516 |
silentModels: opts.silent ? [record.model.name] : [], |
| 517 |
}); |
| 518 |
const key = database[this.name]?.key || "id"; |
| 519 |
this.triggerEvents("delete", { key: record[key], id: record.id }); |
| 520 |
return id; |
| 521 |
} |
| 522 |
|
| 523 |
backLink(record, link) { |
| 524 |
if (!link.startsWith(BACKREF_PREFIX)) { |
| 525 |
link = BACKREF_PREFIX + link; |
| 526 |
} |
| 527 |
if (link in record) { |
| 528 |
return record[link]; |
| 529 |
} |
| 530 |
const field = this.fields[link]; |
| 531 |
if (!field) { |
| 532 |
return undefined; |
| 533 |
} |
| 534 |
const relation = field.relation; |
| 535 |
const inverseField = field.inverse_name; |
| 536 |
const backLinkKey = this.name + field.name; |
| 537 |
if (!backlinkIndexes.has(backLinkKey)) { |
| 538 |
const recordsMap = record[STORE_SYMBOL].getRecordsMap(relation, "id"); |
| 539 |
|
| 540 |
const index = new Map(); |
| 541 |
for (const relRecord of recordsMap.values()) { |
| 542 |
const parentId = relRecord[RAW_SYMBOL][inverseField]; |
| 543 |
const parentIds = parentId instanceof Set ? parentId : [parentId]; |
| 544 |
|
| 545 |
for (const id of parentIds) { |
| 546 |
if (!id) { |
| 547 |
continue; |
| 548 |
} |
| 549 |
if (!index.has(id)) { |
| 550 |
index.set(id, []); |
| 551 |
} |
| 552 |
index.get(id).push(relRecord); |
| 553 |
} |
| 554 |
} |
| 555 |
backlinkIndexes.set(backLinkKey, index); |
| 556 |
|
| 557 |
const unsubscribers = []; |
| 558 |
unsubscribers.push( |
| 559 |
record.model.addEventListener("delete", (data) => { |
| 560 |
index.delete(data.id); |
| 561 |
}) |
| 562 |
); |
| 563 |
|
| 564 |
const cleanup = () => { |
| 565 |
backlinkIndexes.delete(backLinkKey); |
| 566 |
for (const unsubscribe of unsubscribers) { |
| 567 |
unsubscribe?.(); |
| 568 |
} |
| 569 |
unsubscribers.length = 0; |
| 570 |
}; |
| 571 |
|
| 572 |
const relationModel = record.models[relation]; |
| 573 |
for (const operation of ["update", "create", "delete"]) { |
| 574 |
unsubscribers.push(relationModel.addEventListener(operation, cleanup)); |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
const currentIndex = backlinkIndexes.get(backLinkKey); |
| 579 |
return currentIndex.get(record.id) || []; |
| 580 |
} |
| 581 |
|
| 582 |
serializeForORM(record, opts = {}) { |
| 583 |
return ormSerialization(record, { dynamicModels, ...opts }); |
| 584 |
} |
| 585 |
serializeForIndexedDB(record) { |
| 586 |
const serialized = { ...record.raw }; |
| 587 |
const state = record.serializeState(); |
| 588 |
if (state) { |
| 589 |
serialized[SERIALIZED_UI_STATE_PROP] = JSON.stringify(state); |
| 590 |
} |
| 591 |
return serialized; |
| 592 |
} |
| 593 |
} |
| 594 |
|
| 595 |
class Models { |
| 596 |
constructor(processedModelDefs) { |
| 597 |
Object.assign( |
| 598 |
this, |
| 599 |
mapObj(processedModelDefs, (modelName) => new Model(modelName)) |
| 600 |
); |
| 601 |
this[STORE_SYMBOL] = store; |
| 602 |
} |
| 603 |
|
| 604 |
get commands() { |
| 605 |
return commands; |
| 606 |
} |
| 607 |
|
| 608 |
/** |
| 609 |
* Loads data that is already fully connected, meaning relationships do not need to be computed. |
| 610 |
* This method is typically used when loading the initial dataset from the backend. |
| 611 |
* |
| 612 |
* @param {Object} data - The dataset to load. |
| 613 |
* @param {Array<string>} [modelsToLoad=[]] - The names of the models to be loaded. |
| 614 |
* @returns {Array<Base>} - The list of loaded records. |
| 615 |
*/ |
| 616 |
loadConnectedData(data, modelsToLoad = []) { |
| 617 |
return disabler.call((...args) => this._loadData(...args), data, modelsToLoad, { |
| 618 |
connectRecords: false, |
| 619 |
serverData: true, |
| 620 |
}); |
| 621 |
} |
| 622 |
|
| 623 |
/** |
| 624 |
* Loads data that is not fully connected, meaning some records have already been loaded, |
| 625 |
* and relationships need to be computed to maintain consistency. |
| 626 |
* |
| 627 |
* @param {Object} data - The dataset to load. |
| 628 |
* @param {boolean} [serverData=true] - If true, data not declared as a model field is stored as raw. |
| 629 |
* If false, such data is ignored. |
| 630 |
* @returns {Array<Base>} - The list of loaded records. |
| 631 |
*/ |
| 632 |
connectNewData(data, serverData = true) { |
| 633 |
return disabler.call((...args) => this._loadData(...args), data, [], { |
| 634 |
connectRecords: true, |
| 635 |
serverData: serverData, |
| 636 |
}); |
| 637 |
} |
| 638 |
|
| 639 |
_loadData(rawData, modelsToLoad = [], opts = {}) { |
| 640 |
this._loadingData = true; |
| 641 |
try { |
| 642 |
const results = {}; |
| 643 |
const { serverData = true, connectRecords = true } = opts; |
| 644 |
for (const model in rawData) { |
| 645 |
if (!modelsToLoad.includes(model) && modelsToLoad.length !== 0) { |
| 646 |
continue; |
| 647 |
} else if (!results[model]) { |
| 648 |
results[model] = []; |
| 649 |
} |
| 650 |
const modelKey = database[model]?.key || "id"; |
| 651 |
const valsArray = rawData[model]; |
| 652 |
const recordStore = this[STORE_SYMBOL]; |
| 653 |
const modelInstance = this[model]; |
| 654 |
for (const vals of valsArray) { |
| 655 |
const existingRecord = recordStore.get(model, modelKey, vals[modelKey]); |
| 656 |
let record, |
| 657 |
uiState, |
| 658 |
isUpdate = false; |
| 659 |
if (existingRecord) { |
| 660 |
const { |
| 661 |
rawData, |
| 662 |
uiState: newUiState, |
| 663 |
dataToConnect, |
| 664 |
} = modelInstance._sanitizeRawData(vals, { |
| 665 |
connectRecords, |
| 666 |
serverData, |
| 667 |
existingRecord, |
| 668 |
}); |
| 669 |
|
| 670 |
// Remove olds references (id string -> id number) |
| 671 |
recordStore.remove(existingRecord); |
| 672 |
existingRecord[RAW_SYMBOL] = rawData; |
| 673 |
recordStore.add(existingRecord); |
| 674 |
if (dataToConnect) { |
| 675 |
modelInstance._connectRecords(existingRecord, dataToConnect); |
| 676 |
} |
| 677 |
record = existingRecord; |
| 678 |
uiState = newUiState; |
| 679 |
isUpdate = true; |
| 680 |
} else { |
| 681 |
({ record, uiState } = this[model]._create(vals, { |
| 682 |
connectRecords, |
| 683 |
serverData, |
| 684 |
delaySetup: true, |
| 685 |
})); |
| 686 |
} |
| 687 |
results[model].push({ record, vals, uiState, isUpdate }); |
| 688 |
} |
| 689 |
} |
| 690 |
// Call setup and restore UI state after all records are loaded / connected |
| 691 |
const finalResults = {}; |
| 692 |
for (const model in results) { |
| 693 |
const entries = results[model]; |
| 694 |
const createdIds = []; |
| 695 |
const resultsArray = []; |
| 696 |
finalResults[model] = resultsArray; |
| 697 |
const modelEvents = this[model]; |
| 698 |
for (let i = 0; i < entries.length; i++) { |
| 699 |
const { record, vals, uiState, isUpdate } = entries[i]; |
| 700 |
setupRecord(record, vals, uiState, isUpdate); |
| 701 |
if (!isUpdate) { |
| 702 |
createdIds.push(record.id); |
| 703 |
} else { |
| 704 |
modelEvents.triggerEvents("update", { |
| 705 |
id: record.id, |
| 706 |
fields: Object.keys(rawData), |
| 707 |
}); |
| 708 |
} |
| 709 |
resultsArray.push(record); |
| 710 |
} |
| 711 |
modelEvents.triggerEvents("create", { ids: createdIds }); |
| 712 |
} |
| 713 |
return finalResults; |
| 714 |
} finally { |
| 715 |
this._loadingData = false; |
| 716 |
} |
| 717 |
} |
| 718 |
|
| 719 |
serializeForORM(record, opts) { |
| 720 |
return ormSerialization(record, { dynamicModels, ...opts }); |
| 721 |
} |
| 722 |
|
| 723 |
_connect(field, ownerRecord, recordOrId, aggregatedUpdates) { |
| 724 |
if (!this[STORE_SYMBOL].hasIndex(field.relation, "id")) { |
| 725 |
// Not supported model |
| 726 |
return; |
| 727 |
} |
| 728 |
const inverse = inverseMap.get(field); |
| 729 |
const recordToConnect = this._getRecord(field.relation, recordOrId); |
| 730 |
if (!recordToConnect) { |
| 731 |
return; |
| 732 |
} |
| 733 |
if (field.type === "many2one") { |
| 734 |
const prevConnectedRecordId = ownerRecord[RAW_SYMBOL][field.name]; |
| 735 |
if (prevConnectedRecordId === recordToConnect.id) { |
| 736 |
return; |
| 737 |
} |
| 738 |
if (!inverse.dummy && inverse.name in recordToConnect) { |
| 739 |
this._addItem(recordToConnect, inverse, ownerRecord, aggregatedUpdates); |
| 740 |
} |
| 741 |
if (prevConnectedRecordId && !inverse.dummy) { |
| 742 |
const prevRecord = this[STORE_SYMBOL].getById( |
| 743 |
field.relation, |
| 744 |
prevConnectedRecordId |
| 745 |
); |
| 746 |
this._removeItem(prevRecord, inverse, ownerRecord, aggregatedUpdates); |
| 747 |
} |
| 748 |
ownerRecord[RAW_SYMBOL][field.name] = recordToConnect.id; |
| 749 |
aggregatedUpdates.add(ownerRecord, field.name); |
| 750 |
} else if (field.type === "one2many") { |
| 751 |
if (!inverse.dummy) { |
| 752 |
this._connect(inverse, recordToConnect, ownerRecord, aggregatedUpdates); |
| 753 |
} else { |
| 754 |
this._addItem(ownerRecord, field, recordToConnect, aggregatedUpdates); |
| 755 |
} |
| 756 |
} else if (field.type === "many2many") { |
| 757 |
this._addItem(ownerRecord, field, recordToConnect, aggregatedUpdates); |
| 758 |
this._addItem(recordToConnect, inverse, ownerRecord, aggregatedUpdates); |
| 759 |
} |
| 760 |
} |
| 761 |
|
| 762 |
_disconnect(field, ownerRecord, recordOrId, aggregatedUpdates) { |
| 763 |
if (!this[STORE_SYMBOL].hasIndex(field.relation, "id")) { |
| 764 |
// Not supported model |
| 765 |
return; |
| 766 |
} |
| 767 |
|
| 768 |
const inverse = inverseMap.get(field); |
| 769 |
const recordToDisconnect = this._getRecord(field.relation, recordOrId); |
| 770 |
if (!recordToDisconnect) { |
| 771 |
return; |
| 772 |
} |
| 773 |
|
| 774 |
if (field.type === "many2one") { |
| 775 |
const prevConnectedRecordId = ownerRecord[RAW_SYMBOL][field.name]; |
| 776 |
if (prevConnectedRecordId === recordToDisconnect.id) { |
| 777 |
ownerRecord[RAW_SYMBOL][field.name] = undefined; |
| 778 |
aggregatedUpdates.add(ownerRecord, field.name); |
| 779 |
this._removeItem(recordToDisconnect, inverse, ownerRecord, aggregatedUpdates); |
| 780 |
} |
| 781 |
} else if (field.type === "one2many") { |
| 782 |
if (!inverse.dummy) { |
| 783 |
this._disconnect(inverse, recordToDisconnect, ownerRecord, aggregatedUpdates); |
| 784 |
} else { |
| 785 |
this._removeItem(ownerRecord, field, recordToDisconnect, aggregatedUpdates); |
| 786 |
} |
| 787 |
} else if (field.type === "many2many") { |
| 788 |
this._removeItem(ownerRecord, field, recordToDisconnect, aggregatedUpdates); |
| 789 |
this._removeItem(recordToDisconnect, inverse, ownerRecord, aggregatedUpdates); |
| 790 |
} |
| 791 |
} |
| 792 |
|
| 793 |
_getRecord(model, recordOrId) { |
| 794 |
if (!recordOrId) { |
| 795 |
throw new Error(`Record '${model}' is undefined`); |
| 796 |
} |
| 797 |
if (recordOrId instanceof Base) { |
| 798 |
return recordOrId; |
| 799 |
} |
| 800 |
return this[STORE_SYMBOL].getById(model, recordOrId); |
| 801 |
} |
| 802 |
|
| 803 |
_removeItem(ownerRecord, field, recordToRemove, aggregatedUpdates) { |
| 804 |
if (field.dummy || !ownerRecord) { |
| 805 |
return; |
| 806 |
} |
| 807 |
if (!recordToRemove.id) { |
| 808 |
return; |
| 809 |
} |
| 810 |
ownerRecord[RAW_SYMBOL][field.name].delete(recordToRemove.id); |
| 811 |
aggregatedUpdates.add(ownerRecord, field.name); |
| 812 |
} |
| 813 |
|
| 814 |
_addItem(ownerRecord, field, recordToAdd, aggregatedUpdates) { |
| 815 |
if (field.dummy || !ownerRecord) { |
| 816 |
return; |
| 817 |
} |
| 818 |
const recordIds = ownerRecord[RAW_SYMBOL][field.name]; |
| 819 |
const idToAdd = recordToAdd.id; |
| 820 |
if (idToAdd && !recordIds.has(idToAdd)) { |
| 821 |
recordIds.add(idToAdd); |
| 822 |
aggregatedUpdates.add(ownerRecord, field.name); |
| 823 |
} |
| 824 |
} |
| 825 |
} |
| 826 |
|
| 827 |
const models = new Models(processedModelDefs); |
| 828 |
return { models }; |
| 829 |
} |
| 830 |
|
| 831 |
function setupRecord(record, vals, uiState, isUpdate = false) { |
| 832 |
record.setup(vals); |
| 833 |
if (uiState) { |
| 834 |
record.restoreState(uiState); |
| 835 |
} else if (!isUpdate) { |
| 836 |
record.initState(); |
| 837 |
} |
| 838 |
} |
| 839 |
|
| 840 |
/** |
| 841 |
* Converts [l1, l2] into [["set", l1, l2]] or [] to ["clear"] if necessary. |
| 842 |
* If values are already arrays, they are added as-is. |
| 843 |
* Otherwise, a default "set" command is created to group individual values. |
| 844 |
*/ |
| 845 |
function convertToX2ManyCommands(values, strict = false) { |
| 846 |
const commands = []; |
| 847 |
let defaultCommand; |
| 848 |
if (!values || values.length === 0) { |
| 849 |
return [["clear"]]; |
| 850 |
} |
| 851 |
if (!Array.isArray(values)) { |
| 852 |
throw new Error("The value must be an array"); |
| 853 |
} |
| 854 |
for (const val of values) { |
| 855 |
if (Array.isArray(val)) { |
| 856 |
commands.push(val); |
| 857 |
} else { |
| 858 |
if (strict) { |
| 859 |
throw new Error("Only an array of commands is supported"); |
| 860 |
} |
| 861 |
if (!defaultCommand) { |
| 862 |
defaultCommand = ["set"]; |
| 863 |
commands.push(defaultCommand); |
| 864 |
} |
| 865 |
defaultCommand.push(val); |
| 866 |
} |
| 867 |
} |
| 868 |
return commands; |
| 869 |
} |
| 870 |
|
| 871 |
export { Base } from "./base"; |