Debian Codegraph @

addons/point_of_sale/static/src/utils.js

raw
1 /* global QRCode */
2
3 import { session } from "@web/session";
4 import { getDataURLFromFile } from "@web/core/utils/urls";
5 import { deserializeDateTime } from "@web/core/l10n/dates";
6 /*
7 * comes from o_spreadsheet.js
8 * https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
9 * */
10 export function uuidv4() {
11 // mainly for jest and other browsers that do not have the crypto functionality
12 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
13 const r = (Math.random() * 16) | 0,
14 v = c == "x" ? r : (r & 0x3) | 0x8;
15 return v.toString(16);
16 });
17 }
18
19 /**
20 * Formats the given `url` with correct protocol and port.
21 * Useful for communicating to local iot box instance.
22 * @param {string} url
23 * @returns {string}
24 */
25 export function deduceUrl(url) {
26 const protocol = odoo.use_lna ? "http:" : window.location.protocol;
27 if (!url.includes("//")) {
28 url = `${protocol}//${url}`;
29 }
30 if (url.indexOf(":", 6) < 0) {
31 url += ":" + (protocol === "https:" ? 443 : 8069);
32 }
33 return url;
34 }
35
36 export function constructAttributeString(line) {
37 let attributeString = "";
38
39 if (line.attribute_value_ids && line.attribute_value_ids.length > 0) {
40 for (const value of line.attribute_value_ids) {
41 if (value.is_custom) {
42 const customValue = line.custom_attribute_value_ids.find(
43 (cus) =>
44 cus.custom_product_template_attribute_value_id?.id == parseInt(value.id)
45 );
46 if (customValue) {
47 attributeString += `${value.attribute_id.name}: ${value.name}: ${customValue.custom_value}, `;
48 }
49 } else {
50 attributeString += `${value.name}, `;
51 }
52 }
53
54 attributeString = attributeString.slice(0, -2);
55 } else if (
56 attributeString === "" &&
57 line?.product_id?.product_template_variant_value_ids?.length > 0
58 ) {
59 attributeString = line.product_id.product_template_variant_value_ids
60 ?.map((attr) => attr.name)
61 .join(", ");
62 }
63
64 return attributeString;
65 }
66
67 export function constructFullProductName(line) {
68 const attributeString = constructAttributeString(line);
69 return attributeString
70 ? `${line?.product_id?.name} (${attributeString})`
71 : `${line?.product_id?.name}`;
72 }
73 /**
74 * Returns a random 5 digits alphanumeric code
75 * @returns {string}
76 */
77 export function random5Chars() {
78 let code = "";
79 while (code.length != 5) {
80 code = Math.random().toString(36).slice(2, 7);
81 }
82 return code;
83 }
84
85 export function qrCodeSrc(url, { size = 200 } = {}) {
86 return `/report/barcode/QR/${encodeURIComponent(url)}?width=${size}&height=${size}`;
87 }
88
89 /**
90 * @template T
91 * @param {T[]} entries - The array of objects to search through.
92 * @param {Function} [criterion=(x) => x] - A function that returns a number for each entry. The entry with the highest value of this function will be returned. If not provided, defaults to an identity function that returns the entry itself.
93 * @param {boolean} [inverted=false] - If true, the entry with the lowest value of the criterion function will be returned instead.
94 * @returns {T} The entry with the highest or lowest value of the criterion function, depending on the value of `inverted`.
95 */
96 export function getMax(entries, { criterion = (x) => x, inverted = false } = {}) {
97 return entries.reduce((prev, current) => {
98 const res = criterion(prev) > criterion(current);
99 return (inverted ? !res : res) ? prev : current;
100 });
101 }
102 export function getMin(entries, options) {
103 return getMax(entries, { ...options, inverted: true });
104 }
105 export function getOnNotified(bus, channel) {
106 bus.addChannel(channel);
107 return (notif, callback) => bus.subscribe(`${channel}-${notif}`, callback);
108 }
109
110 /**
111 * Loading image is converted to a Promise to allow await when
112 * loading an image. It resolves to the loaded image if successful,
113 * else, resolves to false.
114 *
115 * [Source](https://stackoverflow.com/questions/45788934/how-to-turn-this-callback-into-a-promise-using-async-await)
116 */
117 export function loadImage(url, options = {}) {
118 return new Promise((resolve, reject) => {
119 const img = new Image();
120 img.addEventListener("load", () => resolve(img));
121 img.addEventListener("error", () => {
122 if (options.onError) {
123 options.onError();
124 }
125 reject(new Error(`Failed to load image at ${url}`));
126 });
127 img.src = url;
128 });
129 }
130
131 /**
132 * Load all images in the given element.
133 * @param {HTMLElement} el
134 */
135
136 export function waitImages(containerElement, timeoutMs = 3000) {
137 return new Promise((resolve) => {
138 const images = containerElement.querySelectorAll("img");
139 const total = images.length;
140 let loadedCount = 0;
141 let timedOut = false;
142
143 if (total === 0) {
144 resolve({ timedOut: false });
145 return;
146 }
147
148 const timeoutId = setTimeout(() => {
149 timedOut = true;
150 resolve({ timedOut: true });
151 }, timeoutMs);
152
153 const onLoadOrError = () => {
154 loadedCount++;
155 if (loadedCount === total && !timedOut) {
156 clearTimeout(timeoutId);
157 resolve({ timedOut: false });
158 }
159 };
160
161 images.forEach((img) => {
162 if (img.complete) {
163 onLoadOrError();
164 } else {
165 img.addEventListener("load", onLoadOrError);
166 img.addEventListener("error", onLoadOrError);
167 }
168 });
169 });
170 }
171
172 export class Counter {
173 constructor(start = 0) {
174 this.value = start;
175 }
176 next() {
177 this.value++;
178 return this.value;
179 }
180 }
181
182 export function isValidEmail(email) {
183 return email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
184 }
185
186 export const LONG_PRESS_DURATION = session.test_mode ? 100 : 500;
187
188 export async function getImageDataUrl(imageUrl) {
189 const res = await fetch(imageUrl);
190 const blob = await res.blob();
191 return await getDataURLFromFile(blob);
192 }
193
194 export function orderUsageUTCtoLocalUtil(data) {
195 const result = {};
196 for (const [datetime, usage] of Object.entries(data)) {
197 const dt = deserializeDateTime(datetime);
198 const formattedDt = dt.toFormat("yyyy-MM-dd HH:mm:ss");
199 result[formattedDt] = usage;
200 }
201 return result;
202 }
203
204 /**
205 * Generates a QR code as a data URL in SVG format for a given URL.
206 *
207 * @param {string} url - The URL or text to encode in the QR code.
208 * @param {Object} [options={}] - Optional configuration for the QR code.
209 * @param {number} [options.width=150] - The width of the QR code.
210 * @param {number} [options.height=150] - The height of the QR code.
211 * @param {number} [options.correctLevel=QRCode.CorrectLevel.L] - The error correction level for the QR code.
212 * @param {boolean} [options.useSVG=true] - Whether to generate the QR code as SVG.
213 * @param {Object} [options.rest] - Additional options to pass to the QRCode constructor.
214 * @returns {string} The QR code as a data URL in SVG format.
215 */
216 export function generateQRCodeDataUrl(
217 url,
218 { width = 150, height = 150, correctLevel = QRCode.CorrectLevel.L, ...rest } = {}
219 ) {
220 const tempDiv = document.createElement("div");
221 const options = { width, height, correctLevel, ...rest };
222
223 new QRCode(tempDiv, { text: url, useSVG: true, ...options });
224
225 const svg = tempDiv.querySelector("svg");
226 svg.setAttribute("width", width);
227 svg.setAttribute("height", height);
228
229 const qr_code_svg = new XMLSerializer().serializeToString(svg);
230 return "data:image/svg+xml;base64," + window.btoa(qr_code_svg);
231 }