Debian Codegraph @

addons/point_of_sale/static/src/app/services/data_service.js

raw
1 import { Reactive } from "@web/core/utils/reactive";
2 import { Base, createRelatedModels } from "@point_of_sale/app/models/related_models";
3 import { registry } from "@web/core/registry";
4 import { Mutex } from "@web/core/utils/concurrency";
5 import { markRaw } from "@odoo/owl";
6 import { debounce } from "@web/core/utils/timing";
7 import IndexedDB from "../models/utils/indexed_db";
8 import { DataServiceOptions } from "../models/data_service_options";
9 import { getOnNotified, uuidv4 } from "@point_of_sale/utils";
10 import { browser } from "@web/core/browser/browser";
11 import { ConnectionLostError, rpc, RPCError } from "@web/core/network/rpc";
12 import { _t } from "@web/core/l10n/translation";
13 import DeviceIdentifierSequence from "../utils/devices_identifier_sequence";
14 import { logPosMessage } from "../utils/pretty_console_log";
15
16 const { DateTime } = luxon;
17 const CONSOLE_COLOR = "#28ffeb";
18
19 export class PosData extends Reactive {
20 static modelToLoad = []; // When empty all models are loaded
21 static serviceDependencies = ["orm", "bus_service"];
22
23 constructor() {
24 super();
25 this.ready = this.setup(...arguments).then(() => this);
26 }
27
28 async setup(env, { orm, bus_service }) {
29 this.orm = orm;
30 this.bus = bus_service;
31 this.relations = [];
32 this.custom = {};
33 this.syncInProgress = false;
34 this.mutex = markRaw(new Mutex());
35 this.records = {};
36 this.opts = new DataServiceOptions();
37 this.channels = [];
38 this.debouncedSynchronizeLocalDataInIndexedDB = debounce(
39 this.synchronizeLocalDataInIndexedDB.bind(this),
40 300
41 );
42
43 this.network = {
44 warningTriggered: false,
45 offline: false,
46 loading: true,
47 unsyncData: [],
48 };
49
50 if (!navigator.onLine) {
51 await this.checkConnectivity();
52 }
53
54 this.initializeWebsocket();
55 await this.initializeDeviceIdentifier();
56 await this.intializeDataRelation();
57
58 browser.addEventListener("online", () => this.checkConnectivity());
59 browser.addEventListener("offline", () => this.checkConnectivity());
60 this.bus.addEventListener("BUS:CONNECT", this.reconnectWebSocket.bind(this));
61 }
62
63 async initializeDeviceIdentifier() {
64 this.device = new DeviceIdentifierSequence({ orm: this.orm });
65 await this.device.initialize();
66 }
67
68 async checkConnectivity() {
69 try {
70 clearTimeout(this.checkConnectivityTimeout);
71 this.checkConnectivityTimeout = null;
72 // Runbot tests will soon be run in dockers with no access to the outside world,
73 // so all their interfaces will be disconnected. The problem is that the browser
74 // considers itself offline when no interface is connected. However, in this case,
75 // if the Odoo server is still accessible.
76 //
77 // This method also makes it possible to run local tests when no connection is
78 // available and an Odoo server is running locally.
79 //
80 // A ping is required to verify that the connection to the server is not possible.
81 this.network.offline = false;
82 this.network.warningTriggered = false;
83
84 await rpc("/pos/ping");
85 await this.syncData();
86 window.dispatchEvent(new CustomEvent("pos-network-online"));
87 } catch (error) {
88 if (error instanceof ConnectionLostError) {
89 this.network.offline = true;
90 if (navigator.onLine) {
91 this.checkConnectivityTimeout = setTimeout(
92 () => this.checkConnectivity(),
93 2000
94 );
95 }
96 }
97 }
98 }
99
100 initializeWebsocket() {
101 this.onNotified = getOnNotified(this.bus, odoo.access_token);
102 }
103
104 reconnectWebSocket() {
105 this.initializeWebsocket();
106 const channels = [...this.channels];
107 this.channels = [];
108 while (channels.length) {
109 const channel = channels.pop();
110 this.connectWebSocket(channel.channel, channel.method);
111
112 logPosMessage(
113 "DataService",
114 "reconnectWebSocket",
115 `Reconnecting to channe ${channel.channel}`,
116 CONSOLE_COLOR
117 );
118 }
119 }
120
121 connectWebSocket(channel, method) {
122 this.channels.push({
123 channel,
124 method,
125 });
126
127 this.onNotified(channel, method);
128 }
129
130 get databaseName() {
131 return `point-of-sale-${odoo.pos_config_id}-${odoo.info?.db}`;
132 }
133
134 async resetIndexedDB() {
135 // Remove data_server_date since it's used to determine the last time the data was loaded
136 await this.indexedDB.reset();
137 }
138
139 async initIndexedDB(relations) {
140 // This method initializes indexedDB with all models loaded into the PoS. The default key is ID.
141 // But some models have another key configured in data_service_options.js. These models are
142 // generally those that can be created in the frontend.
143 const allModelNames = Array.from(
144 new Set([...Object.keys(relations), ...Object.keys(this.opts.databaseTable)])
145 );
146 const models = allModelNames.map((model) => {
147 const key = this.opts.databaseTable[model]?.key || "id";
148 return [key, model];
149 });
150
151 return new Promise((resolve) => {
152 this.indexedDB = new IndexedDB(this.databaseName, false, models, resolve);
153 });
154 }
155
156 async synchronizeLocalDataInIndexedDB() {
157 // This methods will synchronize local data and state in indexedDB. This methods is mostly
158 // used with models like pos.order, pos.order.line, pos.payment etc. These models are created
159 // in the frontend and are not loaded from the backend.
160 const modelsParams = Object.entries(this.opts.databaseTable);
161 const data = {};
162 for (const [model, params] of modelsParams) {
163 const put = [];
164 const remove = [];
165 const modelData = this.models[model].getAll();
166
167 for (const record of modelData) {
168 const isToRemove = params.condition(record);
169
170 if (isToRemove === undefined || isToRemove === true) {
171 if (record[params.key]) {
172 remove.push(record[params.key]);
173 }
174 } else {
175 put.push(record.serializeForIndexedDB());
176 }
177 }
178
179 await this.indexedDB.delete(model, remove);
180 await this.indexedDB.create(model, put);
181 data[model] = put;
182
183 if (remove.length) {
184 await this.indexedDB.delete(model, remove);
185 }
186
187 if (put.length) {
188 await this.indexedDB.create(model, put);
189 }
190 }
191
192 return data;
193 }
194
195 async synchronizeServerDataInIndexedDB(serverData = {}) {
196 try {
197 const clone = JSON.parse(JSON.stringify(serverData));
198 for (const [model, data] of Object.entries(clone)) {
199 try {
200 await this.indexedDB.create(model, data);
201 } catch {
202 logPosMessage(
203 "DataService",
204 "synchronizeServerDataInIndexedDB",
205 `Error while updating ${model} in indexedDB.`,
206 CONSOLE_COLOR
207 );
208 }
209 }
210 } catch {
211 logPosMessage(
212 "DataService",
213 "synchronizeServerDataInIndexedDB",
214 "Error while synchronizing server data in indexedDB.",
215 CONSOLE_COLOR
216 );
217 }
218 }
219
220 async getLocalDataFromIndexedDB(data = false) {
221 // Used to retrieve models containing states from the indexedDB.
222 // This method will load the records directly via loadData.
223 const models = Object.keys(this.opts.databaseTable);
224
225 if (!data) {
226 data = await this.indexedDB.readAll(models);
227 }
228
229 if (!data) {
230 return;
231 }
232
233 const newData = {};
234 for (const model of models) {
235 const rawRec = data[model];
236
237 if (rawRec) {
238 newData[model] = rawRec.filter((r) => !this.models[model].get(r.id));
239 }
240 }
241
242 const preLoadData = await this.preLoadData(data);
243 const missing = await this.missingRecursive(preLoadData);
244 const results = this.models.loadConnectedData(missing, []);
245
246 await this.checkAndDeleteMissingOrders(results);
247
248 return results;
249 }
250
251 async getCachedServerDataFromIndexedDB() {
252 // Used to load models that have not yet been loaded into related_models.
253 // These models have been sent to the indexedDB directly after the RPC load_data.
254 const data = await this.indexedDB.readAll();
255 const modelToIgnore = Object.keys(this.opts.databaseTable);
256 const results = {};
257
258 for (const name in data) {
259 if (name in modelToIgnore) {
260 continue;
261 }
262 results[name] = data[name];
263 }
264
265 return results;
266 }
267
268 async loadInitialData() {
269 let localData = await this.getCachedServerDataFromIndexedDB();
270 const session = localData?.["pos.session"]?.[0];
271
272 if (
273 (!this.network.offline && session?.state !== "opened") ||
274 session?.id !== odoo.pos_session_id ||
275 odoo.from_backend
276 ) {
277 try {
278 const limitedLoading = this.isLimitedLoading();
279 const serverDate = localData["pos.config"]?.[0]?._data_server_date;
280 const lastConfigChange = DateTime.fromSQL(odoo.last_data_change);
281 const serverDateTime = DateTime.fromSQL(serverDate);
282
283 if (serverDateTime < lastConfigChange) {
284 await this.resetIndexedDB();
285 await this.initIndexedDB(this.relations);
286 localData = [];
287 }
288
289 const data = await this.orm.call(
290 "pos.session",
291 "load_data",
292 [odoo.pos_session_id, PosData.modelToLoad],
293 {
294 context: {
295 pos_last_server_date: serverDateTime > lastConfigChange && serverDate,
296 pos_limited_loading: limitedLoading,
297 },
298 }
299 );
300
301 const local_records_to_filter = {};
302 for (const model of this.opts.cleanupModels) {
303 const local = localData[model] || [];
304 if (local.length > 0) {
305 local_records_to_filter[model] = local.map((r) => r.id);
306 }
307 }
308
309 const data_to_remove = await this.orm.call("pos.session", "filter_local_data", [
310 odoo.pos_session_id,
311 local_records_to_filter,
312 ]);
313
314 for (const [model, values] of Object.entries(data)) {
315 let local = localData[model] || [];
316
317 if (this.opts.uniqueModels.includes(model) && values.length > 0) {
318 this.indexedDB.delete(
319 model,
320 local.map((r) => r.id)
321 );
322 localData[model] = values;
323 } else {
324 if (data_to_remove[model] && data_to_remove[model].length > 0) {
325 const remove_ids = data_to_remove[model];
326 local = local.filter((r) => !remove_ids.includes(r.id));
327 this.indexedDB.delete(model, remove_ids);
328 }
329 localData[model] = local.concat(values);
330 }
331 }
332
333 this.synchronizeServerDataInIndexedDB(localData);
334 } catch (error) {
335 let message = _t("An error occurred while loading the Point of Sale: \n");
336 if (error instanceof RPCError) {
337 message += error.data.message;
338 } else {
339 message += error.message;
340 }
341 window.alert(message);
342 return localData;
343 }
344 }
345
346 return localData;
347 }
348
349 async initData(hard = false, limit = true) {
350 const data = await this.loadInitialData(hard, limit);
351 const order = data["pos.order"] || [];
352 const orderlines = data["pos.order.line"] || [];
353
354 delete data["pos.order"];
355 delete data["pos.order.line"];
356
357 this.models.loadConnectedData(data, this.modelToLoad);
358 this.models.loadConnectedData({ "pos.order": order, "pos.order.line": orderlines }, []);
359 this.sanitizeData();
360 }
361
362 async sanitizeData() {
363 const order_to_delete = this.models["pos.order"].filter((order) =>
364 order.lines.some((line) => line.is_reward_line && !line.coupon_id && !line.reward_id)
365 );
366 for (const order of order_to_delete) {
367 for (let i = order.lines.length - 1; i >= 0; i--) {
368 order.lines[i].delete();
369 }
370 }
371 }
372
373 async loadFieldsAndRelations() {
374 const key = `pos_data_params_${odoo.pos_config_id}`;
375 if (this.network.offline) {
376 return JSON.parse(localStorage.getItem(key));
377 }
378
379 try {
380 const params = await this.orm.call("pos.session", "load_data_params", [
381 odoo.pos_session_id,
382 ]);
383 localStorage.setItem(key, JSON.stringify(params));
384 return params;
385 } catch {
386 return JSON.parse(localStorage.getItem(key));
387 }
388 }
389
390 async intializeDataRelation() {
391 // Here the order is important. loadFieldsAndRelations will load all the information
392 // about the models loaded in the PoS. Then initIndexedDB needs it to update/create
393 // the indexedDB. loadInitialData needs indexedDB, so it comes at the end.
394 const modelClasses = {};
395 const fields = {};
396 const relations = {};
397 const dataParams = await this.loadFieldsAndRelations();
398 await this.initIndexedDB(dataParams);
399
400 for (const [model, values] of Object.entries(dataParams)) {
401 relations[model] = values.relations;
402 fields[model] = values.fields;
403 }
404
405 for (const posModel of registry.category("pos_available_models").getAll()) {
406 const pythonModel = posModel.pythonModel;
407 const extraFields = posModel.extraFields || {};
408
409 modelClasses[pythonModel] = posModel;
410 relations[pythonModel] = {
411 ...relations[pythonModel],
412 ...extraFields,
413 };
414 }
415
416 const { models } = createRelatedModels(relations, modelClasses, this.opts);
417
418 this.fields = fields;
419 this.relations = relations;
420 this.models = models;
421
422 if (odoo.debug === "assets") {
423 window.performance.mark("pos_data_service_init");
424 }
425
426 await this.initData();
427 await this.getLocalDataFromIndexedDB();
428 this.initListeners();
429
430 if (odoo.debug === "assets") {
431 window.performance.mark("pos_data_service_init_end");
432 this.debugInfos();
433 }
434
435 this.network.loading = false;
436 }
437
438 debugInfos() {
439 const measure = window.performance.measure(
440 "pos_loading",
441 "pos_data_service_init",
442 "pos_data_service_init_end"
443 );
444
445 logPosMessage(
446 "DataService",
447 "debugInfos",
448 `PosDataService initialized in ${measure.duration.toFixed(2)}ms`,
449 CONSOLE_COLOR
450 );
451 }
452
453 initListeners() {
454 for (const dynamicModel of this.opts.dynamicModels) {
455 if (!this.models[dynamicModel]) {
456 continue;
457 }
458
459 this.models[dynamicModel].addEventListener(
460 "update",
461 this.debouncedSynchronizeLocalDataInIndexedDB.bind(this)
462 );
463 }
464
465 const ignore = Object.keys(this.opts.databaseTable);
466 for (const model of Object.keys(this.relations)) {
467 if (ignore.includes(model)) {
468 continue;
469 }
470
471 this.models[model].addEventListener("delete", (params) => {
472 this.indexedDB.delete(model, [params.key]);
473 });
474
475 this.models[model].addEventListener("update", (params) => {
476 const record = this.models[model].get(params.id)?.raw;
477 if (!record) {
478 return; // the record may be deleted
479 }
480 for (const [key, value] of Object.entries(record)) {
481 if (value instanceof Base) {
482 record[key] = value.id;
483 } else if (Array.isArray(value) && value[0] instanceof Base) {
484 record[key] = value.map((v) => v.id);
485 }
486 }
487
488 this.synchronizeServerDataInIndexedDB({ [model]: [record] });
489 });
490 }
491 }
492
493 async execute({
494 type,
495 model,
496 ids,
497 values,
498 method,
499 queue,
500 args = [],
501 kwargs = {},
502 fields = [],
503 options = [],
504 uuid = "",
505 }) {
506 this.network.loading = true;
507
508 try {
509 if (this.network.offline) {
510 throw new ConnectionLostError();
511 }
512
513 let result = true;
514 let limitedFields = false;
515 if (fields.length === 0) {
516 fields = this.fields[model] || [];
517 }
518
519 if (
520 this.fields[model] &&
521 fields.sort().join(",") !== this.fields[model].sort().join(",")
522 ) {
523 limitedFields = true;
524 }
525
526 switch (type) {
527 case "write":
528 result = await this.orm.write(model, ids, values);
529 break;
530 case "delete":
531 result = await this.orm.unlink(model, ids);
532 break;
533 case "call":
534 result = await this.orm.call(model, method, args, kwargs);
535 break;
536 case "read":
537 queue = false;
538 result = await this.orm.read(model, ids, fields, {
539 ...options,
540 load: false,
541 });
542 break;
543 case "search_read":
544 queue = false;
545 result = await this.orm.searchRead(model, args, fields, {
546 ...options,
547 load: false,
548 });
549 }
550
551 if (type === "create") {
552 const response = await this.orm.create(model, values);
553 values[0].id = response[0];
554 result = values;
555 }
556
557 const nonExistentRecords = [];
558 if (limitedFields) {
559 const X2MANY_TYPES = new Set(["many2many", "one2many"]);
560
561 for (const record of result) {
562 const localRecord = this.models[model].get(record.id);
563
564 if (localRecord) {
565 const formattedForUpdate = {};
566 for (const [field, value] of Object.entries(record)) {
567 const fieldsParams = this.relations[model][field];
568
569 if (!fieldsParams) {
570 logPosMessage(
571 "DataService",
572 "execute",
573 "Warning, attempt to load a non-existent field.",
574 CONSOLE_COLOR
575 );
576 continue;
577 }
578
579 if (X2MANY_TYPES.has(fieldsParams.type)) {
580 formattedForUpdate[field] = value
581 .filter((id) => this.models[fieldsParams.relation].get(id))
582 .map((id) => [
583 "link",
584 this.models[fieldsParams.relation].get(id),
585 ]);
586 } else if (fieldsParams.type === "many2one") {
587 if (this.models[fieldsParams.relation].get(value)) {
588 formattedForUpdate[field] = [
589 "link",
590 this.models[fieldsParams.relation].get(value),
591 ];
592 }
593 } else {
594 formattedForUpdate[field] = value;
595 }
596 }
597
598 localRecord.update(formattedForUpdate, { omitUnknownField: true });
599 this.synchronizeServerDataInIndexedDB({ [model]: [localRecord.raw] });
600 } else {
601 nonExistentRecords.push(record);
602 }
603 }
604
605 if (nonExistentRecords.length) {
606 logPosMessage(
607 "DataService",
608 "execute",
609 "Warning, attempt to load a non-existent record with limited fields.",
610 CONSOLE_COLOR
611 );
612 result = nonExistentRecords;
613 }
614 }
615
616 if (
617 this.models[model] &&
618 this.opts.autoLoadedOrmMethods.includes(type) &&
619 (!limitedFields || nonExistentRecords.length)
620 ) {
621 const data = await this.missingRecursive({ [model]: result });
622 this.synchronizeServerDataInIndexedDB(data);
623 const results = this.models.connectNewData(data);
624 result = results[model];
625 } else if (type === "write") {
626 const localRecord = this.models[model].get(ids[0]);
627 if (localRecord) {
628 localRecord.update(values, { omitUnknownField: true });
629 this.synchronizeServerDataInIndexedDB({ [model]: [localRecord.raw] });
630 }
631 }
632
633 if (result === null || result === undefined) {
634 // if request does not return something, we consider it went well
635 return true;
636 }
637 return result;
638 } catch (error) {
639 let throwErr = true;
640 const uuids = this.network.unsyncData.map((d) => d.uuid);
641 if (
642 queue &&
643 !uuids.includes(uuid) &&
644 method !== "sync_from_ui" &&
645 error instanceof ConnectionLostError
646 ) {
647 this.network.unsyncData.push({
648 args: [...arguments],
649 date: DateTime.now(),
650 try: 1,
651 uuid: uuidv4(),
652 });
653
654 throwErr = false;
655 }
656
657 if (throwErr) {
658 throw error;
659 }
660 } finally {
661 this.network.loading = false;
662 }
663 }
664
665 async missingRecursive(recordMap, idsMap = {}, acc = {}) {
666 if (this.network.offline) {
667 return acc;
668 }
669
670 const missingRecords = {};
671 const recordInMapByModelIds = Object.entries(recordMap).reduce((acc, [model, records]) => {
672 acc[model] = new Set(records.map((r) => r.id));
673 return acc;
674 }, {});
675
676 for (const [model, records] of Object.entries(recordMap)) {
677 if (!acc[model]) {
678 acc[model] = records;
679 } else {
680 acc[model] = acc[model].concat(records);
681 }
682
683 if (!this.relations[model]) {
684 continue;
685 }
686
687 const relations = Object.entries(this.relations[model]).filter(
688 ([, rel]) => rel.relation && rel.type && this.models[rel.relation]
689 );
690
691 for (const [, rel] of relations) {
692 if (this.opts.pohibitedAutoLoadedModels.includes(rel.relation)) {
693 continue;
694 }
695
696 if (this.opts.prohibitedAutoLoadedFields[rel.model]?.includes(rel.name)) {
697 continue;
698 }
699
700 const values = records.map((record) => record[rel.name]).flat();
701 const missing = values.filter((value) => {
702 if (!value || typeof value !== "number" || idsMap[rel.relation]?.has(value)) {
703 return false;
704 }
705
706 const record = this.models[rel.relation].get(value);
707 return (
708 (!record || !record.id) && !recordInMapByModelIds[rel.relation]?.has(value)
709 );
710 });
711
712 if (missing.length > 0) {
713 if (!missingRecords[rel.relation]) {
714 missingRecords[rel.relation] = new Set(missing);
715 } else {
716 missingRecords[rel.relation] = new Set([
717 ...missingRecords[rel.relation],
718 ...missing,
719 ]);
720 }
721 }
722 }
723 }
724
725 const newRecordMap = {};
726 for (const [model, ids] of Object.entries(missingRecords)) {
727 if (!idsMap[model]) {
728 idsMap[model] = new Set(ids);
729 } else {
730 idsMap[model] = idsMap[model] = new Set([...idsMap[model], ...ids]);
731 }
732
733 try {
734 if (["product.product", "product.template"].includes(model)) {
735 const domain = model === "product.product" ? "product_variant_ids.id" : "id";
736 await this.callRelated(
737 "product.template",
738 "load_product_from_pos",
739 [odoo.pos_config_id, [[domain, "in", Array.from(ids)]], 0, 0],
740 {
741 context: {
742 load_archived: true,
743 },
744 }
745 );
746 continue;
747 }
748
749 const data = await this.orm.read(model, Array.from(ids), this.fields[model], {
750 load: false,
751 });
752 newRecordMap[model] = data;
753 } catch {
754 newRecordMap[model] = [];
755 }
756 }
757
758 if (Object.keys(newRecordMap).length > 0) {
759 return await this.missingRecursive(newRecordMap, idsMap, acc);
760 } else {
761 return acc;
762 }
763 }
764
765 async syncData() {
766 this.syncInProgress = true;
767
768 await this.mutex.exec(async () => {
769 while (this.network.unsyncData.length > 0) {
770 const data = this.network.unsyncData[0];
771 const result = await this.execute({ ...data.args[0], uuid: data.uuid });
772
773 if (result) {
774 this.network.unsyncData.shift();
775 } else {
776 this.network.unsyncData[0].try += 1;
777 break;
778 }
779 }
780 });
781
782 this.syncInProgress = false;
783 }
784
785 async loadServerOrders(domain) {
786 const result = await this.callRelated(
787 "pos.order",
788 "read_pos_orders",
789 [domain],
790 {},
791 false,
792 true
793 );
794 const config = this.models["pos.config"].get(odoo.pos_config_id);
795 const session = this.models["pos.session"].get(odoo.pos_session_id);
796 const orders = result["pos.order"] || [];
797 for (const order of orders) {
798 // Clear commands
799 order.serializeForORM();
800 order.config_id = config;
801 order.session_id = session;
802 }
803 return orders;
804 }
805
806 async checkAndDeleteMissingOrders(results) {
807 if (results && results["pos.order"]) {
808 const ids = new Set(results["pos.order"].filter((o) => o.isSynced).map((o) => o.id));
809 if (ids.size) {
810 const orders = await this.loadServerOrders([["id", "in", [...ids]]]);
811 const serverIds = orders.map((r) => r.id);
812 for (const id of [...ids]) {
813 if (!serverIds.includes(id)) {
814 this.localDeleteCascade(this.models["pos.order"].get(id));
815 }
816 }
817 }
818 }
819 }
820
821 write(model, ids, vals) {
822 const records = [];
823
824 for (const id of ids) {
825 const record = this.models[model].get(id);
826 delete vals.id;
827 record.update(vals, { omitUnknownField: true });
828
829 const dataToUpdate = {};
830 const keysToUpdate = Object.keys(vals);
831
832 for (const key of keysToUpdate) {
833 dataToUpdate[key] = vals[key];
834 }
835
836 records.push(record);
837 if (typeof id === "number") {
838 this.ormWrite(model, [record.id], dataToUpdate);
839 }
840 }
841
842 return records;
843 }
844
845 delete(model, ids) {
846 const deleted = [];
847 for (const id of ids) {
848 const record = this.models[model].get(id);
849 deleted.push(id);
850 record.delete();
851 }
852
853 this.ormDelete(model, ids);
854 return deleted;
855 }
856
857 async searchRead(model, domain = [], fields = [], options = {}, queue = false) {
858 return await this.execute({
859 type: "search_read",
860 model,
861 args: domain,
862 fields,
863 options,
864 queue,
865 });
866 }
867
868 async read(model, ids, fields = [], options = [], queue = false) {
869 return await this.execute({ type: "read", model, ids, fields, options, queue });
870 }
871
872 async call(model, method, args = [], kwargs = {}, queue = false) {
873 return await this.execute({ type: "call", model, method, args, kwargs, queue });
874 }
875
876 // In a silent call we ignore the error and return false instead
877 async silentCall(model, method, args = [], kwargs = {}, queue = false) {
878 try {
879 return await this.execute({ type: "call", model, method, args, kwargs, queue });
880 } catch (e) {
881 logPosMessage("DataService", "silentCall", "Silent call failed", CONSOLE_COLOR, [e]);
882 return false;
883 }
884 }
885
886 async callRelated(
887 model,
888 method,
889 args = [],
890 kwargs = {},
891 queue = true,
892 loadMessingRecords = false
893 ) {
894 let data = await this.execute({ type: "call", model, method, args, kwargs, queue });
895
896 if (loadMessingRecords) {
897 data = await this.missingRecursive(data);
898 }
899
900 if (data) {
901 this.deviceSync?.dispatch && this.deviceSync.dispatch(data);
902 const result = this.models.connectNewData(data);
903 this.synchronizeServerDataInIndexedDB(data);
904 return result;
905 }
906 return false;
907 }
908
909 async create(model, values, queue = true) {
910 return await this.execute({ type: "create", model, values, queue });
911 }
912
913 async ormWrite(model, ids, values, queue = true) {
914 const result = await this.execute({ type: "write", model, ids, values, queue });
915 this.deviceSync?.dispatch &&
916 this.deviceSync.dispatch({ [model]: ids.map((id) => ({ id })) });
917 return result;
918 }
919
920 async ormDelete(model, ids, queue = true) {
921 return await this.execute({ type: "delete", model, ids, queue });
922 }
923
924 localDeleteCascade(record, removeFromServer = false) {
925 const recordModel = record.constructor.pythonModel;
926
927 const relationsToDelete = Object.values(this.relations[recordModel])
928 .filter((rel) => this.opts.cascadeDeleteModels.includes(rel.relation))
929 .map((rel) => rel.name);
930 const recordsToDelete = relationsToDelete.flatMap((relation) => record[relation]);
931
932 // Delete all children records before main record
933 this.indexedDB.delete(recordModel, [record.uuid]);
934 for (const item of recordsToDelete) {
935 this.indexedDB.delete(item.model.name, [item.uuid]);
936 item.delete({ silent: !removeFromServer });
937 }
938
939 // Delete the main record
940 const result = record.delete({ silent: !removeFromServer });
941 return result;
942 }
943
944 async preLoadData(data) {
945 return data;
946 }
947
948 isLimitedLoading() {
949 const url = new URL(window.location.href);
950 const limitedLoading = url.searchParams.get("limited_loading") === "0" ? false : true;
951
952 if (!limitedLoading) {
953 url.searchParams.delete("limited_loading");
954 window.history.replaceState({}, "", url);
955 }
956
957 return limitedLoading;
958 }
959 }
960
961 export const PosDataService = {
962 dependencies: PosData.serviceDependencies,
963 async start(env, deps) {
964 return new PosData(env, deps).ready;
965 },
966 };
967
968 registry.category("services").add("pos_data", PosDataService);