Debian Codegraph @

addons/point_of_sale/static/src/app/utils/devices_synchronisation.js

raw
1 import { Domain } from "@web/core/domain";
2 import { logPosMessage } from "./pretty_console_log";
3
4 const CONSOLE_COLOR = "#b56be3";
5 /**
6 * Class representing the synchronization of records.
7 * This class handles the setup and management of dynamic (flexible) models
8 * that can be created in the frontend and static models that are predefined.
9 */
10 export default class DevicesSynchronisation {
11 constructor(dynamicModels, staticModels, posStore) {
12 this.setup(dynamicModels, staticModels, posStore);
13 }
14
15 /**
16 * Setup the record synchronization with dynamic and static models.
17 * @param {Array} dynamicModels - Models that can be created in the frontend.
18 * @param {Array} staticModels - Predefined models that are static.
19 * @param {Object} posStore - The posStore instance.
20 */
21 setup(dynamicModels, staticModels, posStore) {
22 this.dynamicModels = new Set(dynamicModels);
23 this.staticModels = new Set(staticModels);
24 this.pos = posStore;
25 this.models = posStore.models;
26
27 // Connect websocket to receive synchronisation notification
28 this.pos.data.connectWebSocket("SYNCHRONISATION", this.collect.bind(this));
29 }
30
31 /**
32 * Dispatch the synchronization of records.
33 * This method will dispatch the synchronization of records to the
34 * backend to inform others devices that a record has been updated,
35 * @param {Object} data - The data that needs to be synchronized.
36 */
37 async dispatch(data) {
38 const recordIds = Object.entries(data).reduce((acc, [model, records]) => {
39 if (!this.staticModels.has(model)) {
40 return acc;
41 }
42 acc[model] = records.map((record) => record.id);
43 return acc;
44 }, {});
45
46 logPosMessage("Synchronisation", "dispatch", "Disptaching synchronization", CONSOLE_COLOR);
47 await this.pos.data.call("pos.config", "notify_synchronisation", [
48 odoo.pos_config_id,
49 odoo.pos_session_id,
50 this.pos.device.identifier,
51 recordIds,
52 ]);
53 }
54
55 /**
56 * Collect the synchronization of records.
57 * This method will collect the synchronization of records from the backend
58 * to update the records in the frontend.
59 * @param {Object} data - The data that needs to be synchronized.
60 * @param {String} data.device_identifier - Session login number.
61 * @param {Number} data.session_id - Current session id.
62 * @param {Object} data.static_records - Records data that need to be synchronized.
63 */
64 async collect(data) {
65 const { static_records, session_id, device_identifier } = data;
66 const isSameDevice =
67 odoo.pos_session_id != session_id || device_identifier == this.pos.device.identifier;
68
69 logPosMessage(
70 "Synchronisation",
71 "collect",
72 `Incoming synchronization from ${isSameDevice ? "this" : "another"} device`,
73 CONSOLE_COLOR
74 );
75
76 if (isSameDevice) {
77 return;
78 }
79
80 if (Object.keys(static_records).length) {
81 this.processStaticRecords(static_records);
82 }
83
84 return await this.readDataFromServer();
85 }
86
87 /**
88 * Read data from the server.
89 * This method will read the data from the server to update the records in the frontend
90 * and synchronize the records with other devices.
91 */
92 async readDataFromServer() {
93 const serverOpenOrders = this.pos.getOpenOrders().filter((o) => o.isSynced);
94 const { domain, recordIds } = this.constructOrdersDomain(serverOpenOrders);
95 let response = {};
96 try {
97 response = await this.pos.data.call("pos.config", "read_config_open_orders", [
98 odoo.pos_config_id,
99 domain,
100 recordIds,
101 ]);
102 } catch (error) {
103 logPosMessage(
104 "Synchronisation",
105 "readDataFromServer",
106 `Error reading open orders data from server: ${error}`,
107 CONSOLE_COLOR
108 );
109 return;
110 }
111
112 if (Object.keys(response.dynamic_records).length) {
113 const missing = await this.pos.data.missingRecursive(response.dynamic_records);
114 const { dynamicR, staticR } = Object.entries(missing).reduce(
115 (acc, [model, records]) => {
116 if (this.dynamicModels.has(model)) {
117 acc.dynamicR[model] = records;
118 } else if (this.staticModels.has(model)) {
119 acc.staticR[model] = records;
120 }
121 return acc;
122 },
123 { dynamicR: {}, staticR: {} }
124 );
125
126 this.processStaticRecords(staticR);
127 const res = await this.processDynamicRecords(dynamicR);
128 if (res && res["pos.order"]) {
129 const config = this.pos.config;
130 const session = this.models["pos.session"].get(odoo.pos_session_id);
131
132 for (const order of res["pos.order"]) {
133 // Clear commands
134 order.serializeForORM();
135 order.config_id = config;
136 order.session_id = session;
137 }
138 }
139 }
140
141 if (Object.keys(response.deleted_record_ids).length) {
142 this.processDeletedRecords(response.deleted_record_ids);
143 }
144 }
145
146 /**
147 * Process the static records.
148 * This method will process the static records to update the records in the frontend.
149 * @param {Object} staticRecords - Records data that need to be synchronized.
150 */
151 processStaticRecords(staticRecords) {
152 return this.models.connectNewData(staticRecords);
153 }
154
155 /**
156 * Process the dynamic records.
157 * This method will process the dynamic records to update the records in the frontend.
158 * @param {Object} dynamicRecords - Record write dates by ids and models.
159 */
160 async processDynamicRecords(dynamicRecords) {
161 return this.models.connectNewData(dynamicRecords);
162 }
163
164 /**
165 * Process the deleted records.
166 * This method will process the deleted records to update the records in the frontend.
167 * @param {Object} deletedRecords - Ids of inexisting records in the backend by models.
168 */
169 processDeletedRecords(deletedRecords) {
170 for (const [model, ids] of Object.entries(deletedRecords)) {
171 const records = this.models[model].readMany(ids);
172 this.models[model].deleteMany(records.filter(Boolean), { silent: true });
173 }
174 }
175
176 /**
177 * Get the open orders.
178 * This method will get local open orders with a server id.
179 * @returns {Array} - Array of domain conditions.
180 */
181 constructOrdersDomain() {
182 const dynamicModels = this.dynamicModels;
183 const recordsToCheck = Array.from(dynamicModels).reduce((acc, model) => {
184 acc[model] = this.models[model].filter(
185 (r) => !this.pos.data.opts.databaseTable[model]?.condition(r)
186 );
187 return acc;
188 }, {});
189
190 const recordIdsByModel = {};
191 const domainByModel = Object.entries(recordsToCheck).reduce((acc, [model, records]) => {
192 const serverRecs = records.filter((r) => r.isSynced);
193 const ids = serverRecs.map((r) => r.id);
194 const config = this.pos.config;
195 const domains = [];
196
197 if (ids.length === 0 && model !== "pos.order") {
198 return acc;
199 }
200
201 recordIdsByModel[model] = ids;
202 for (const record of serverRecs) {
203 const recordDateTime = record.write_date.plus({ seconds: 1 }).toUTC();
204 const recordDateTimeString = recordDateTime.toFormat("yyyy-MM-dd HH:mm:ss", {
205 numberingSystem: "latn",
206 });
207
208 let domain = new Domain([
209 ["id", "=", record.id],
210 ["write_date", ">=", recordDateTimeString],
211 ]);
212
213 if (model === "pos.order") {
214 domain = Domain.or([
215 domain,
216 new Domain([
217 ["id", "=", record.id],
218 ["state", "!=", record.state],
219 ]),
220 ]);
221 }
222
223 domains.push(domain);
224 }
225
226 let domain = Domain.or(domains);
227 if (model === "pos.order") {
228 domain = Domain.or([
229 domain,
230 new Domain([
231 ["id", "not in", ids],
232 ["state", "=", "draft"],
233 ["config_id", "in", [config.id, ...config.raw.trusted_config_ids]],
234 ]),
235 ]);
236
237 acc[model] = domain.toList();
238 }
239
240 return acc;
241 }, {});
242
243 return { domain: domainByModel, recordIds: recordIdsByModel };
244 }
245 }