Debian Codegraph @

addons/pos_glory_cash/static/src/glory_service.js

raw
1 import {
2 serializeGloryXml,
3 parseGloryXml,
4 makeGloryHeader,
5 parseGloryResult,
6 parseVerificationInfo,
7 } from "@pos_glory_cash/utils/glory_xml";
8 import {
9 GLORY_STATUS,
10 GLORY_CURRENCY_STATUS,
11 WEBSOCKET_REQUESTS,
12 XML_REQUESTS,
13 } from "@pos_glory_cash/utils/constants";
14 import { SocketIoService } from "@pos_glory_cash/utils/socket_io";
15 import { reactive } from "@odoo/owl";
16 import { sortBy } from "@web/core/utils/arrays";
17 import { browser } from "@web/core/browser/browser";
18 import { Logger } from "@bus/workers/bus_worker_utils";
19 import { uuid } from "@web/core/utils/strings";
20
21 const { DateTime } = luxon;
22
23 const WEBSOCKET_PORT = browser.location.protocol === "https:" ? 3001 : 3000;
24 const WEBSOCKET_PROTOCOL = browser.location.protocol === "https:" ? "wss:" : "ws:";
25 const WEBSOCKET_URL = "/socket.io/?transport=websocket&EIO=3";
26
27 const convertObjectValuesToInt = (object) =>
28 Object.fromEntries(Object.entries(object).map(([key, value]) => [key, parseInt(value)]));
29
30 export class GloryService {
31 /**
32 * @param {(status: string) => void} onStatusChange
33 */
34 constructor(onStatusChange) {
35 this.setup(...arguments);
36 }
37
38 /**
39 * @param {(status: string) => void} onStatusChange
40 */
41 setup(onStatusChange) {
42 this.logger = new Logger("pos_glory_cash");
43 this.eventHandlers = {
44 StatusChangeEvent: this._statusChangeHandler.bind(this),
45 InventoryResponse: this._inventoryChangeHandler.bind(this),
46 SpecialDeviceError: this._deviceErrorHandler.bind(this),
47 };
48 this.onStatusChange = onStatusChange;
49 this.socketIo = new SocketIoService({
50 onConnect: () => this._onConnect(),
51 onClose: () => {
52 this.status = "DISCONNECTED";
53 },
54 onEvent: ([responseType, data]) => {
55 if (this.resolvers[responseType]) {
56 this.resolvers[responseType](data);
57 }
58 },
59 onBinaryEvent: (data) =>
60 parseGloryXml(data).then((response) => {
61 this._logXml("RECV", response);
62 const message = response.firstChild;
63 if (this.resolvers[message.tagName]) {
64 this.resolvers[message.tagName](message);
65 } else if (this.eventHandlers[message.tagName]) {
66 this.eventHandlers[message.tagName](message);
67 }
68 }),
69 });
70 this._resetState();
71 }
72
73 /**
74 * @param {string} ip
75 * @param {string} [username]
76 * @param {string} [password]
77 */
78 connect(ip, username, password) {
79 this._resetState();
80 this.username = username;
81 this.password = password;
82 const websocketEndpoint = `${WEBSOCKET_PROTOCOL}//${ip}:${WEBSOCKET_PORT}${WEBSOCKET_URL}`;
83 this.socketIo.connect(websocketEndpoint);
84 }
85
86 async reset() {
87 if (this.settings.OccupyEnable && !this.occupied) {
88 await this._occupy();
89 }
90
91 await this._sendXmlRequest(XML_REQUESTS.reset);
92
93 if (this.occupied) {
94 await this._release();
95 }
96 }
97
98 /**
99 * @param {number} amountInCents
100 * @returns {Promise<{ status: string, cashGiven?: number, cashReturned?: number, transactionId?: string }>}
101 */
102 async sendPaymentRequest(amountInCents) {
103 if (
104 [
105 "DISCONNECTED",
106 "BAD_CREDENTIALS",
107 "ERROR",
108 "WAITING_ERROR_RECOVERY",
109 "WAITING_REPLENISHMENT",
110 "COLLECTING",
111 ].includes(this.status)
112 ) {
113 return {
114 status: this.status,
115 };
116 }
117
118 if (this.settings.OccupyEnable) {
119 await this._occupy();
120 }
121
122 this.state.amountInserted = 0;
123 this.paymentInProgress = true;
124 this._newSequenceNumber();
125
126 const { xmlResponse } = await this._sendXmlRequest(XML_REQUESTS.startPayment, [
127 {
128 name: "Amount",
129 children: [amountInCents.toString()],
130 },
131 {
132 // Option Type 1 = Enable cancellation when there is insufficient change
133 name: "Option",
134 attributes: { type: "1" },
135 },
136 ]);
137
138 const result = await this._handlePaymentResponse(xmlResponse);
139
140 if (this.occupied) {
141 await this._release();
142 }
143 this.paymentInProgress = false;
144
145 return result;
146 }
147
148 async initiatePaymentCancel() {
149 if (this.status === "DISCONNECTED") {
150 return this.status;
151 }
152
153 if (this.settings.OccupyEnable && !this.occupied) {
154 const occupyResult = await this._occupy();
155 if (occupyResult !== "SUCCESS") {
156 return occupyResult;
157 }
158 }
159
160 const { statusCode } = await this._sendXmlRequest(XML_REQUESTS.cancelPayment);
161
162 if (this.occupied && !this.paymentInProgress) {
163 await this._release();
164 }
165
166 return statusCode;
167 }
168
169 get status() {
170 return this.state.status;
171 }
172 set status(newStatus) {
173 if (newStatus === this.state.status) {
174 return;
175 }
176 this.state.status = newStatus;
177 this.onStatusChange(newStatus);
178 }
179
180 _resetState() {
181 /**
182 * @type {import("models").GlorySettings}
183 */
184 this.settings = null;
185 /**
186 * @type {import("models").GloryUser}
187 */
188 this.gloryUser = null;
189 this.username = null;
190 this.password = null;
191 this.sequenceNumber = 0;
192 this.sessionId = null;
193 this.occupied = false;
194 this.paymentInProgress = false;
195
196 /** @type {import("models".GloryState)} */
197 this.state = reactive({
198 status: "DISCONNECTED",
199 inventory: [],
200 amountInserted: 0,
201 lastDeviceError: null,
202 });
203
204 this.resolvers = {};
205 }
206
207 async _onConnect() {
208 await this._login();
209
210 if (!this.settings) {
211 const settings = await this._sendWebsocketRequest(WEBSOCKET_REQUESTS.getSettings);
212 this.settings = convertObjectValuesToInt(settings.FunctionSetting);
213 }
214
215 if (this.settings.SessionEnable) {
216 await this._refreshSession();
217 }
218
219 await this._setDateAndTime();
220 await this._checkStatusAndVerifyIfNeeded();
221
222 const { xmlResponse } = await this._sendXmlRequest(XML_REQUESTS.getInventory, [
223 // Option Type 2 = 'Payable' inventory, see p76 of the IF Specification document
224 { name: "Option", attributes: { type: "2" } },
225 ]);
226 this._inventoryChangeHandler(xmlResponse);
227 }
228
229 async _login() {
230 if (this.username) {
231 const response = await this._sendWebsocketRequest(
232 WEBSOCKET_REQUESTS.login,
233 this.username,
234 this.password
235 );
236 if (response.ret === 0) {
237 this.gloryUser = response;
238 }
239 }
240
241 // If access control is enabled and we don't have a valid user/pass, we receive this 'credential ng' message
242 this._waitForResponseWithType("credential ng").then(() => {
243 this.status = "BAD_CREDENTIALS";
244 });
245 await this._sendWebsocketRequest(
246 WEBSOCKET_REQUESTS.checkCredentials,
247 this.gloryUser?.session_id
248 );
249 }
250
251 async _refreshSession() {
252 const data = await this._sendWebsocketRequest(WEBSOCKET_REQUESTS.openSession);
253 this.sessionId = data.SessionID;
254 }
255
256 async _setDateAndTime() {
257 const now = DateTime.now();
258 await this._sendXmlRequest(XML_REQUESTS.setDateAndTime, [
259 {
260 name: "Date",
261 attributes: {
262 year: now.year.toString(),
263 month: now.month.toString(),
264 day: now.day.toString(),
265 },
266 },
267 {
268 name: "Time",
269 attributes: {
270 hour: now.hour.toString(),
271 minute: now.minute.toString(),
272 second: now.second.toString(),
273 },
274 },
275 ]);
276 }
277
278 async _checkStatusAndVerifyIfNeeded() {
279 const firstConnection = this.state.inventory.length === 0;
280 const { xmlResponse } = await this._sendXmlRequest(XML_REQUESTS.getStatus, [
281 { name: "RequireVerification", attributes: { type: "1" } },
282 ]);
283 this._statusChangeHandler(xmlResponse);
284
285 const requireVerifyType = parseVerificationInfo(xmlResponse);
286 if (!firstConnection || !requireVerifyType) {
287 return;
288 }
289
290 const { statusCode } = await this._sendXmlRequest(XML_REQUESTS.collect, [
291 { name: "RequireVerification", attributes: { type: requireVerifyType.toString() } },
292 ]);
293
294 return statusCode;
295 }
296
297 /**
298 * @param {Element} statusResponse
299 */
300 _statusChangeHandler(statusResponse) {
301 const statusCodeElement =
302 statusResponse.getElementsByTagName("Code")[0] ??
303 statusResponse.getElementsByTagName("Status")[0];
304
305 this.status = GLORY_STATUS[statusCodeElement.textContent];
306
307 if (!["ERROR", "WAITING_ERROR_RECOVERY"].includes(this.status)) {
308 this.state.lastDeviceError = null;
309 }
310
311 if (this.status === "COUNTING") {
312 const amount = statusResponse.getElementsByTagName("Amount")[0].textContent;
313 this.state.amountInserted = parseInt(amount);
314 }
315 }
316
317 /**
318 * @param {Element} inventoryResponse
319 */
320 _inventoryChangeHandler(inventoryResponse) {
321 const cashElements = Array.from(inventoryResponse.getElementsByTagName("Cash"));
322 const dispensableCash = cashElements.find(
323 (cashElement) => cashElement.getAttribute("type") === "4"
324 );
325 if (!dispensableCash) {
326 return;
327 }
328
329 const denominations = this._parseGloryCashElement(dispensableCash);
330 this.state.inventory = sortBy(denominations, "value");
331 }
332
333 /**
334 * @param {Element} deviceErrorResponse
335 */
336 _deviceErrorHandler(deviceErrorResponse) {
337 const errorMessageElement = deviceErrorResponse.getElementsByTagName("ErrorMessage")[0];
338 this.state.lastDeviceError = errorMessageElement.textContent;
339 }
340
341 /**
342 * @param {Element} cashElement
343 */
344 _parseGloryCashElement(cashElement) {
345 const denominationElements = Array.from(cashElement.getElementsByTagName("Denomination"));
346 return denominationElements.map((denomination) => ({
347 value: parseInt(denomination.getAttribute("fv")),
348 amount: parseInt(denomination.getElementsByTagName("Piece")[0].textContent),
349 status: GLORY_CURRENCY_STATUS[
350 denomination.getElementsByTagName("Status")[0].textContent
351 ],
352 }));
353 }
354
355 /**
356 * @param {Element} cashElement
357 * @returns {number}
358 */
359 _getTotalFromGloryCashElement(cashElement) {
360 const denominations = this._parseGloryCashElement(cashElement);
361 return denominations.reduce((total, next) => total + next.amount * next.value, 0);
362 }
363
364 _newSequenceNumber() {
365 this.sequenceNumber = uuid().replace("-", "").slice(0, 11);
366 }
367
368 /**
369 * @param {Element} paymentResponse
370 * @returns {Promise<{ status: string, cashGiven?: number, cashReturned?: number, transactionId?: string }>}
371 */
372 async _handlePaymentResponse(paymentResponse) {
373 const baseResponse = {
374 status: parseGloryResult(paymentResponse),
375 };
376 if (["SUCCESS", "CHANGE_SHORTAGE"].includes(baseResponse.status)) {
377 return {
378 ...baseResponse,
379 ...this._getTransactionInfo(paymentResponse),
380 };
381 }
382 return baseResponse;
383 }
384
385 /**
386 * @param {Element} paymentResponse
387 */
388 _getTransactionInfo(paymentResponse) {
389 const cashElements = Array.from(paymentResponse.getElementsByTagName("Cash"));
390 const cashGivenElement = cashElements.find(
391 (cashElement) => cashElement.getAttribute("type") === "1"
392 );
393 const cashReturnedElement = cashElements.find(
394 (cashElement) => cashElement.getAttribute("type") === "2"
395 );
396 const cashGiven = this._getTotalFromGloryCashElement(cashGivenElement);
397 const cashReturned = this._getTotalFromGloryCashElement(cashReturnedElement);
398 const transactionId = paymentResponse.getElementsByTagName("TransactionId")[0].textContent;
399
400 return {
401 cashGiven,
402 cashReturned,
403 transactionId,
404 };
405 }
406
407 async _occupy() {
408 const { statusCode } = await this._sendXmlRequest(XML_REQUESTS.occupy);
409 if (statusCode === "SUCCESS") {
410 this.occupied = true;
411 }
412 return statusCode;
413 }
414
415 async _release() {
416 await this._sendXmlRequest(XML_REQUESTS.release);
417 this.occupied = false;
418 }
419
420 /**
421 * @param {import("models").GloryRequestInfo} request
422 * @param {any[]} params
423 */
424 _sendWebsocketRequest(request, ...params) {
425 const resultPromise = this._waitForResponseWithType(request.responseName);
426 this.socketIo.sendMessage([request.requestName, ...params]);
427 return resultPromise;
428 }
429
430 /**
431 * @param {import("models").GloryRequestInfo} request
432 * @param {import("models").GloryXmlElement[]?} children
433 * @returns {Promise<{ statusCode: string, xmlResponse: Element }>}
434 */
435 async _sendXmlRequest(request, children, secondAttempt = false) {
436 const xmlElement = {
437 name: request.requestName,
438 children: [
439 ...makeGloryHeader(this.sequenceNumber, this.sessionId),
440 ...(children ?? []),
441 ],
442 };
443 const xmlString = serializeGloryXml(xmlElement);
444 this._logXml("SEND", xmlString);
445 this.socketIo.sendMessage(["xml send", xmlString]);
446
447 const xmlResponse = await this._waitForResponseWithType(request.responseName);
448 const statusCode = parseGloryResult(xmlResponse);
449
450 if (
451 !secondAttempt &&
452 (statusCode === "SESSION_TIMEOUT" || statusCode === "INVALID_SESSION")
453 ) {
454 await this._refreshSession();
455 return this._sendXmlRequest(request, children, true);
456 }
457
458 return { statusCode, xmlResponse };
459 }
460
461 /**
462 * @param {string} type
463 * @returns {Promise<Element>}
464 */
465 async _waitForResponseWithType(type) {
466 const responsePromise = new Promise((resolve) => {
467 this.resolvers[type] = resolve;
468 });
469 const result = await responsePromise;
470 this.resolvers[type] = null;
471 return result;
472 }
473
474 _logXml(message, xml) {
475 if (typeof xml === "string") {
476 xml = xml.replace("\0", "");
477 } else {
478 xml = new XMLSerializer().serializeToString(xml);
479 }
480
481 this.logger.log(
482 `${luxon.DateTime.now().toFormat("yyyy-LL-dd HH:mm:ss")} ${message}: ${xml}`
483 );
484 }
485 }