Debian Codegraph @

addons/pos_glory_cash/static/src/app/payment_glory.js

raw
1 import { PaymentInterface } from "@point_of_sale/app/utils/payment/payment_interface";
2 import { CancelDialog } from "@pos_glory_cash/app/components/cancel_dialog";
3 import { GLORY_STATUS_STRING } from "@pos_glory_cash/utils/constants";
4 import { AlertDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
5 import { _t } from "@web/core/l10n/translation";
6 import { GloryService } from "@pos_glory_cash/glory_service";
7
8 const CONNECT_TIMEOUT_MS = 5000;
9
10 export class PaymentGlory extends PaymentInterface {
11 setup() {
12 super.setup(...arguments);
13 this.dialog = this.env.services.dialog;
14 this.cancellationResolver = null;
15 this.gloryService = new GloryService(this.onStatusChange.bind(this));
16 this.gloryService.connect(
17 this.payment_method_id.glory_websocket_address,
18 this.payment_method_id.glory_username,
19 this.payment_method_id.glory_password
20 );
21
22 setTimeout(() => {
23 if (this.gloryService.status === "DISCONNECTED") {
24 this.onStatusChange("DISCONNECTED");
25 }
26 }, CONNECT_TIMEOUT_MS);
27 }
28
29 onStatusChange(newStatus) {
30 switch (newStatus) {
31 case "IDLE": {
32 const isFirstStatus = this.gloryService.state.inventory.length === 0;
33 if (isFirstStatus && this.paymentLine) {
34 // In this case we have a stale payment
35 this.pos.getOrder().removePaymentline(this.paymentLine);
36 }
37 return;
38 }
39 case "DISCONNECTED": {
40 this.showError(
41 _t(
42 "Failed to connect to Glory cash machine, please ensure it is switched on and connected to the network."
43 )
44 );
45 return;
46 }
47 case "BAD_CREDENTIALS": {
48 this.showError(
49 _t(
50 "Failed to login to Glory cash machine, please check the configured username and password."
51 )
52 );
53 return;
54 }
55 case "WAITING_ERROR_RECOVERY": {
56 this.showError(this.currentErrorMessage);
57 return;
58 }
59 case "WAITING_CANCEL": {
60 if (this.paymentLine) {
61 this.showCancelDialog(
62 _t(
63 "There is insufficient change in the cash machine to handle the payment. It must be cancelled to continue."
64 )
65 );
66 }
67 return;
68 }
69 }
70 }
71
72 get status() {
73 return GLORY_STATUS_STRING[this.gloryService.status] ?? this.gloryService.status;
74 }
75
76 get amountInserted() {
77 return this.gloryAmountToPosAmount(this.gloryService.state.amountInserted);
78 }
79
80 get paymentLine() {
81 const order = this.pos.getOrder();
82 if (!order) {
83 return null;
84 }
85
86 const gloryPaymentLines = order.payment_ids.filter(
87 (line) => line.payment_method_id === this.payment_method_id
88 );
89
90 return gloryPaymentLines.find((line) =>
91 ["waiting", "waitingCancel"].includes(line.payment_status)
92 );
93 }
94
95 getDenominationsWithStatus(status) {
96 return this.gloryService.state.inventory
97 .filter((denomination) => denomination.status === status)
98 .map((denomination) => ({
99 ...denomination,
100 value: this.gloryAmountToPosAmount(denomination.value),
101 }));
102 }
103
104 get currentErrorMessage() {
105 if (
106 this.gloryService.status !== "ERROR" &&
107 this.gloryService.status !== "WAITING_ERROR_RECOVERY"
108 ) {
109 return null;
110 }
111 return (
112 this.gloryService.state.lastDeviceError ??
113 _t("The cash machine has an error, please consult its display for details.")
114 );
115 }
116
117 async sendPaymentRequest() {
118 if (!this.paymentLine) {
119 return false;
120 }
121
122 if (this.paymentLine.amount < 0 && this.pos.getCashier()._role !== "manager") {
123 this.showError(_t("Only managers can withdraw cash from the cash machine."));
124 return false;
125 }
126
127 const amountInCents = Math.round(
128 this.paymentLine.amount * Math.pow(10, this.pos.currency.decimal_places)
129 );
130 const paymentResult = await this.gloryService.sendPaymentRequest(amountInCents);
131
132 if (!this.paymentLine) {
133 console.warn("Glory payment response received, but no payment in progress");
134 return false;
135 }
136
137 if (this.cancellationResolver) {
138 this.cancellationResolver();
139 this.cancellationResolver = null;
140 }
141
142 switch (paymentResult.status) {
143 case "DISCONNECTED":
144 case "BAD_CREDENTIALS": {
145 this.showError(_t("The cash machine is disconnected."));
146 return false;
147 }
148 case "ERROR":
149 case "WAITING_ERROR_RECOVERY": {
150 this.showError(this.currentErrorMessage);
151 return false;
152 }
153 case "COLLECTING":
154 case "WAITING_REPLENISHMENT": {
155 this.showError(
156 _t(
157 "The cash machine is currently in collection/replenishment mode, please finish this process on the machine before making a payment."
158 )
159 );
160 return false;
161 }
162 case "SUCCESS": {
163 this.setPaymentInfo(paymentResult, true);
164 return true;
165 }
166 case "CHANGE_SHORTAGE":
167 this.setPaymentInfo(paymentResult, false);
168 await this.pos.printReceipt({ printBillActionTriggered: true });
169 this.showError(_t("There is insufficient cash in the machine to give change."));
170 return false;
171 case "OCCUPIED_BY_OTHER":
172 this.showError(_t("The cash machine is in use by another POS."));
173 return false;
174 case "EXCLUSIVE_ERROR": {
175 this.showCancelDialog(
176 _t("The cash machine is busy with another operation. Do you want to cancel it?")
177 );
178 return false;
179 }
180 case "AUTO_RECOVERY_FAILURE": {
181 this.showError(
182 _t(
183 "The payment failed due to an unrecoverable error - see the cash machine screen for details."
184 )
185 );
186 return false;
187 }
188 case "CANCEL": {
189 return false;
190 }
191 default: {
192 this.showError(
193 _t("The payment failed for an unknown reason: %s", paymentResult.status)
194 );
195 return false;
196 }
197 }
198 }
199
200 async sendPaymentCancel() {
201 const cancelResult = await this.gloryService.initiatePaymentCancel();
202
203 if (cancelResult === "DISCONNECTED") {
204 this.showError(_t("The cash machine is disconnected."));
205 return false;
206 }
207
208 const cancelPromise = new Promise((resolve) => {
209 this.cancellationResolver = resolve;
210 });
211 return await cancelPromise;
212 }
213
214 /**
215 * @param {{ status: string, cashGiven?: number, cashReturned?: number, transactionId?: string }} paymentResponse
216 */
217 setPaymentInfo(paymentResponse) {
218 const isSuccessful = paymentResponse.status === "SUCCESS";
219 const { transactionId, cashGiven, cashReturned } = paymentResponse;
220 this.paymentLine.transaction_id = transactionId;
221 this.paymentLine.setAmount(this.gloryAmountToPosAmount(cashGiven));
222 this.paymentLine.setReceiptInfo(
223 this.makeReceiptMessage(transactionId, cashGiven, cashReturned, isSuccessful)
224 );
225 }
226
227 /**
228 * @param {string} transactionId
229 * @param {number} amountDeposited
230 * @param {number} amountReturned
231 * @param {boolean} isSuccessful
232 * @returns {string}
233 */
234 makeReceiptMessage(transactionId, amountDeposited, amountReturned, isSuccessful) {
235 const header = isSuccessful
236 ? _t("GLORY TRANSACTION SUCCESSFUL")
237 : _t("GLORY TRANSACTION CANCELLED");
238 const transactionIdLine = _t("Transaction ID: %s", transactionId);
239 const depositedLine = _t(
240 "Cash deposited: %s",
241 this.env.utils.formatCurrency(this.gloryAmountToPosAmount(amountDeposited))
242 );
243 const changeGivenLine = _t(
244 "Change given: %s",
245 this.env.utils.formatCurrency(this.gloryAmountToPosAmount(amountReturned))
246 );
247
248 return `${header}\n${transactionIdLine}\n${depositedLine}\n${changeGivenLine}\n\n`;
249 }
250
251 gloryAmountToPosAmount(amountInCents) {
252 const amount = amountInCents / Math.pow(10, this.pos.currency.decimal_places);
253 return this.env.utils.roundCurrency(amount);
254 }
255
256 showError(msg, title) {
257 if (!title) {
258 title = _t("Cash Machine Error");
259 }
260 this.dialog.add(AlertDialog, {
261 title: title,
262 body: msg,
263 });
264 }
265
266 showCancelDialog(message) {
267 this.dialog.add(CancelDialog, {
268 message,
269 cancel: async () => {
270 const cancelStatus = await this.gloryService.initiatePaymentCancel();
271 if (
272 cancelStatus !== "SUCCESS" &&
273 !["IDLE", "RESETTING"].includes(this.gloryService.status)
274 ) {
275 await this.gloryService.reset();
276 }
277 },
278 });
279 }
280 }