-
-
Notifications
You must be signed in to change notification settings - Fork 410
/
Copy pathmodels.js
3600 lines (3356 loc) · 135 KB
/
models.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global waitForWebfonts */
odoo.define('point_of_sale.models', function (require) {
"use strict";
var PosDB = require('point_of_sale.DB');
var config = require('web.config');
var core = require('web.core');
var field_utils = require('web.field_utils');
var time = require('web.time');
var utils = require('web.utils');
var { Gui } = require('point_of_sale.Gui');
const { batched, uuidv4 } = require("point_of_sale.utils");
const { escape } = require("@web/core/utils/strings");
const { rpcService } = require('@web/core/network/rpc_service');
const { isIOS, isIosApp } = require('@web/core/browser/feature_detection');
var QWeb = core.qweb;
var _t = core._t;
var round_di = utils.round_decimals;
var round_pr = utils.round_precision;
const Markup = utils.Markup
const Registries = require('point_of_sale.Registries');
const { markRaw, reactive } = owl;
// Container of the product images fetched during rendering
// of customer display. There is no need to observe it, thus,
// we are putting it outside of PosGlobalState.
const PRODUCT_ID_TO_IMAGE_CACHE = {};
/**
* If optimization is needed, then we should implement this
* using a Balanced Binary Tree to behave like an Object and an Array.
* But behaving like Object (indexed by cid) might not be
* needed. Let's see how it turns out.
*/
class PosCollection extends Array {
getByCID(cid) {
return this.find(item => item.cid == cid);
}
add(item) {
this.push(item);
}
remove(item) {
const index = this.findIndex(_item => item.cid == _item.cid);
if (index < 0) return index;
this.splice(index, 1);
return index;
}
reset() {
this.length = 0;
}
at(index) {
return this[index];
}
}
let nextId = 0;
class PosModel {
/**
* Create an object with cid. If no cid is in the defaultObj,
* cid is computed based on its id. Override _getCID if you
* don't want this default calculation of cid.
* @param {Object?} defaultObj its props copied to this instance.
*/
constructor(defaultObj) {
defaultObj = defaultObj || {};
if (!defaultObj.cid) {
defaultObj.cid = this._getCID(defaultObj);
}
Object.assign(this, defaultObj);
}
/**
* Default cid getter. Used as local identity of this object.
* @param {Object} obj
*/
_getCID(obj) {
if (obj.id) {
if (typeof obj.id == 'string') {
return obj.id;
} else if (typeof obj.id == 'number') {
return `c${obj.id}`;
}
}
return `c${nextId++}`;
}
}
class PosGlobalState extends PosModel {
constructor(obj) {
super(obj);
this.db = new PosDB(); // a local database used to search trough products and categories & store pending orders
this.debug = config.isDebug(); //debug mode
this.unwatched = markRaw({});
// Business data; loaded from the server at launch
this.company_logo = null;
this.company_logo_base64 = '';
this.currency = null;
this.company = null;
this.user = null;
this.partners = [];
this.taxes = [];
this.pos_session = null;
this.config = null;
this.units = [];
this.units_by_id = {};
this.uom_unit_id = null;
this.default_pricelist = null;
this.order_sequence = 1;
// Object mapping the order's name (which contains the uid) to it's server_id after
// validation (order paid then sent to the backend).
this.validated_orders_name_server_id_map = {};
this.numpadMode = 'quantity';
// Record<orderlineId, { 'qty': number, 'orderline': { qty: number, refundedQty: number, orderUid: string }, 'destinationOrderUid': string }>
this.toRefundLines = {};
this.TICKET_SCREEN_STATE = {
syncedOrders: {
currentPage: 1,
cache: {},
toShow: [],
nPerPage: 80,
totalCount: null,
},
ui: {
selectedSyncedOrderId: null,
searchDetails: this.getDefaultSearchDetails(),
filter: null,
// maps the order's backendId to it's selected orderline
selectedOrderlineIds: {},
highlightHeaderNote: false,
},
};
this.syncingOrders = new Set();
this.tempScreenIsShown = false;
// these dynamic attributes can be watched for change by other models or widgets
Object.assign(this, {
'synch': { status:'connected', pending:0 },
'orders': new PosCollection(),
'selectedOrder': null,
'selectedPartner': null,
'selectedCategoryId': null,
});
}
getDefaultSearchDetails() {
return {
fieldName: 'RECEIPT_NUMBER',
searchTerm: '',
};
}
async load_product_uom_unit() {
const params = {
model: 'ir.model.data',
method:'check_object_reference',
args: ['uom', 'product_uom_unit'],
};
const uom_id = await this.env.services.rpc(params);
this.uom_unit_id = uom_id[1];
}
shouldInvoiceNewTab(actionRecord) {
return (
(isIOS() || isIosApp()) &&
actionRecord.type === "ir.actions.report" &&
actionRecord.report_type === "qweb-pdf"
);
}
async loadInvoiceReportAction() {
try {
const future_rpc = rpcService.start({ bus: this.env.posbus });
const action = await future_rpc("/web/action/load", {
action_id: this.invoiceReportAction,
});
this.invoiceActionRecord = action;
} catch {
console.warn(
"Error loading invoice report action. In an iOS environment, " +
"invoicing an order will replace the current page which will cause reload of the app.");
}
}
async after_load_server_data(){
await this.loadInvoiceReportAction();
await this.load_product_uom_unit();
await this.load_orders();
this.set_start_order();
}
async load_server_data(){
const loadedData = await this.env.services.rpc({
model: 'pos.session',
method: 'load_pos_data',
args: [[odoo.pos_session_id]],
});
await this._processData(loadedData);
return this.after_load_server_data();
}
async _processData(loadedData) {
this.version = loadedData['version'];
this.company = loadedData['res.company'];
this.dp = loadedData['decimal.precision'];
this.units = loadedData['uom.uom'];
this.units_by_id = loadedData['units_by_id'];
this.states = loadedData['res.country.state'];
this.countries = loadedData['res.country'];
this.langs = loadedData['res.lang'];
this.taxes = loadedData['account.tax'];
this.taxes_by_id = loadedData['taxes_by_id'];
this.pos_session = loadedData['pos.session'];
this._loadPosSession();
this.config = loadedData['pos.config'];
this._loadPoSConfig();
this.bills = loadedData['pos.bill'];
this.partners = loadedData['res.partner'];
this.addPartners(this.partners);
this.picking_type = loadedData['stock.picking.type'];
this.user = loadedData['res.users'];
this.pricelists = loadedData['product.pricelist'];
this.default_pricelist = loadedData['default_pricelist'];
this.currency = loadedData['res.currency'];
this.db.add_categories(loadedData['pos.category']);
this._loadProductProduct(loadedData['product.product']);
this.db.add_packagings(loadedData['product.packaging']);
this.attributes_by_ptal_id = loadedData['attributes_by_ptal_id'];
this.cash_rounding = loadedData['account.cash.rounding'];
this.payment_methods = loadedData['pos.payment.method'];
this._loadPosPaymentMethod();
this.fiscal_positions = loadedData['account.fiscal.position'];
this.base_url = loadedData['base_url'];
await this._loadFonts();
await this._loadPictures();
}
async _getTableOrdersFromServer(tableIds) {
return await super._getTableOrdersFromServer(tableIds);
}
_loadPosSession() {
// We need to do it here, since only then the local storage has the correct uuid
this.db.save('pos_session_id', this.pos_session.id);
let orders = this.db.get_orders();
let sequences = orders.map(order => order.data.sequence_number + 1)
this.pos_session.sequence_number = Math.max(this.pos_session.sequence_number, ...sequences);
this.pos_session.login_number = odoo.login_number;
}
_loadPoSConfig() {
this.db.set_uuid(this.config.uuid);
}
addPartners(partners) {
return this.db.add_partners(partners);
}
_assignApplicableItems(pricelist, correspondingProduct, pricelistItem) {
if (!(pricelist.id in correspondingProduct.applicablePricelistItems)) {
correspondingProduct.applicablePricelistItems[pricelist.id] = [];
}
correspondingProduct.applicablePricelistItems[pricelist.id].push(pricelistItem);
}
_loadProductProduct(products) {
const productMap = {};
const productTemplateMap = {};
const modelProducts = products.map(product => {
product.pos = this;
product.applicablePricelistItems = {};
productMap[product.id] = product;
productTemplateMap[product.product_tmpl_id[0]] = (productTemplateMap[product.product_tmpl_id[0]] || []).concat(product);
return Product.create(product);
});
for (let pricelist of this.pricelists) {
for (const pricelistItem of pricelist.items) {
if (pricelistItem.product_id) {
let product_id = pricelistItem.product_id[0];
let correspondingProduct = productMap[product_id];
if (correspondingProduct) {
this._assignApplicableItems(pricelist, correspondingProduct, pricelistItem);
}
}
else if (pricelistItem.product_tmpl_id) {
let product_tmpl_id = pricelistItem.product_tmpl_id[0];
let correspondingProducts = productTemplateMap[product_tmpl_id];
for (let correspondingProduct of (correspondingProducts || [])) {
this._assignApplicableItems(pricelist, correspondingProduct, pricelistItem);
}
}
else {
for (const correspondingProduct of products) {
this._assignApplicableItems(pricelist, correspondingProduct, pricelistItem);
}
}
}
}
this.db.add_products(modelProducts)
}
_loadPosPaymentMethod() {
// need to do this for pos_iot due to reference, this is a temporary fix
this.payment_methods_by_id = {}
for (let pm of this.payment_methods) {
this.payment_methods_by_id[pm.id] = pm;
let PaymentInterface = this.electronic_payment_interfaces[pm.use_payment_terminal];
if (PaymentInterface) {
pm.payment_terminal = new PaymentInterface(this, pm);
}
}
}
async _loadFonts() {
return new Promise(function (resolve, reject) {
// Waiting for fonts to be loaded to prevent receipt printing
// from printing empty receipt while loading Inconsolata
// ( The font used for the receipt )
waitForWebfonts(['Lato','Inconsolata'], function () {
resolve();
});
// The JS used to detect font loading is not 100% robust, so
// do not wait more than 5sec
setTimeout(resolve, 5000);
});
}
async _loadPictures() {
this.company_logo = new Image();
return new Promise((resolve, reject) => {
this.company_logo.onload = () => {
let img = this.company_logo;
let ratio = 1;
let targetwidth = 300;
let maxheight = 150;
if (img.width !== targetwidth) {
ratio = targetwidth / img.width;
}
if (img.height * ratio > maxheight) {
ratio = maxheight / img.height;
}
let width = Math.floor(img.width * ratio);
let height = Math.floor(img.height * ratio);
let c = document.createElement('canvas');
c.width = width;
c.height = height;
let ctx = c.getContext('2d');
ctx.drawImage(this.company_logo,0,0, width, height);
this.company_logo_base64 = c.toDataURL();
resolve();
};
this.company_logo.onerror = () => {
reject();
};
this.company_logo.crossOrigin = "anonymous";
this.company_logo.src = `/web/image?model=res.company&id=${this.company.id}&field=logo`;
});
}
prepare_new_partners_domain(){
return [['write_date','>', this.db.get_partner_write_date()]];
}
// reload the list of partner, returns as a promise that resolves if there were
// updated partners, and fails if not
async load_new_partners(){
let search_params = { domain: this.prepare_new_partners_domain() };
if (this.env.pos.config.limited_partners_loading) {
search_params['order'] = 'write_date desc';
if (this.env.pos.config.partner_load_background) {
search_params['limit'] = this.env.pos.config.limited_partners_amount || 1;
}
else {
search_params['limit'] = 1;
}
}
let partners = await this.env.services.rpc({
model: 'pos.session',
method: 'get_pos_ui_res_partner_by_params',
args: [[odoo.pos_session_id], search_params],
}, {
timeout: 3000,
shadow: true,
})
if (this.env.pos.config.partner_load_background) {
this.loadPartnersBackground(
search_params['domain'],
this.env.pos.config.limited_partners_amount || 1,
'write_date desc'
);
}
if (this.addPartners(partners)){
return true
}
else{
return false
}
}
setSelectedCategoryId(categoryId) {
this.selectedCategoryId = categoryId;
}
/**
* Remove the order passed in params from the list of orders
* @param order
*/
removeOrder(order) {
this.orders.remove(order);
this.db.remove_unpaid_order(order);
for (const line of order.get_orderlines()) {
if (line.refunded_orderline_id) {
delete this.toRefundLines[line.refunded_orderline_id];
}
}
}
/**
* Return the current cashier (in this case, the user)
* @returns {name: string, id: int, role: string}
*/
get_cashier() {
return this.user;
}
get_cashier_user_id() {
return this.user.id;
}
cashierHasPriceControlRights() {
return !this.config.restrict_price_control || this.get_cashier().role == 'manager';
}
_onReactiveOrderUpdated(order) {
order.save_to_db();
}
createReactiveOrder(json) {
const options = {pos:this};
if (json) {
options.json = json;
}
return this.makeOrderReactive(Order.create({}, options));
}
makeOrderReactive(order) {
const batchedCallback = batched(() => {
this._onReactiveOrderUpdated(order)
});
order = reactive(order, batchedCallback);
order.save_to_db();
return order;
}
// creates a new empty order and sets it as the current order
add_new_order(){
const order = this.createReactiveOrder();
this.orders.add(order);
this.selectedOrder = order;
return order;
}
/**
* Load the locally saved unpaid orders for this PoS Config.
*
* First load all orders belonging to the current session.
* Second load all orders belonging to the same config but from other sessions,
* Only if tho order has orderlines.
*/
async load_orders(){
var jsons = this.db.get_unpaid_orders();
await this._loadMissingProducts(jsons);
await this._loadMissingPartners(jsons);
var orders = [];
for (var i = 0; i < jsons.length; i++) {
var json = jsons[i];
if (json.pos_session_id === this.pos_session.id) {
orders.push(this.createReactiveOrder(json));
}
}
for (var i = 0; i < jsons.length; i++) {
var json = jsons[i];
if (json.pos_session_id !== this.pos_session.id && (json.lines.length > 0 || json.statement_ids.length > 0)) {
orders.push(this.createReactiveOrder(json));
} else if (json.pos_session_id !== this.pos_session.id) {
this.db.remove_unpaid_order(jsons[i]);
}
}
orders = orders.sort(function(a,b){
return a.sequence_number - b.sequence_number;
});
if (orders.length) {
for (const order of orders) {
this.orders.add(order);
}
}
}
async _loadMissingProducts(orders) {
const missingProductIds = new Set([]);
for (const order of orders) {
for (const line of order.lines) {
const productId = line[2].product_id;
if (missingProductIds.has(productId)) continue;
if (!this.db.get_product_by_id(productId)) {
missingProductIds.add(productId);
}
}
}
if(!missingProductIds.size) return;
const products = await this.env.services.rpc({
model: 'pos.session',
method: 'get_pos_ui_product_product_by_params',
args: [odoo.pos_session_id, {domain: [['id', 'in', [...missingProductIds]]]}],
});
await this._loadMissingPricelistItems(products);
this._loadProductProduct(products);
}
async _loadMissingPricelistItems(products) {
if(!products.length) return;
const product_tmpl_ids = products.map(product => product.product_tmpl_id[0]);
const product_ids = products.map(product => product.id);
const pricelistItems = await this.env.services.rpc({
model: 'pos.session',
method: 'get_pos_ui_product_pricelist_item_by_product',
args: [odoo.pos_session_id, product_tmpl_ids, product_ids],
});
// Merge the loaded pricelist items with the existing pricelists
// Prioritizing the addition of newly loaded pricelist items to the start of the existing pricelists.
// This ensures that the order reflects the desired priority of items in the pricelistItems array.
// E.g. The order in the items should be: [product-pricelist-item, product-template-pricelist-item, category-pricelist-item, global-pricelist-item].
// for reference check order of the Product Pricelist Item model
for (const pricelist of this.pricelists) {
const itemIds = new Set(pricelist.items.map(item => item.id));
const _pricelistItems = pricelistItems.filter(item => {
return item.pricelist_id[0] === pricelist.id && !itemIds.has(item.id);
});
pricelist.items = [..._pricelistItems, ...pricelist.items];
}
}
// load the partners based on the ids
async _loadPartners(partnerIds) {
if (partnerIds.length > 0) {
var domain = [['id','in', partnerIds]];
const fetchedPartners = await this.env.services.rpc({
model: 'pos.session',
method: 'get_pos_ui_res_partner_by_params',
args: [[odoo.pos_session_id], {domain}],
}, {
timeout: 3000,
shadow: true,
});
this.addPartners(fetchedPartners);
}
}
async _loadMissingPartners(orders) {
const missingPartnerIds = new Set([]);
for (const order of orders) {
const partnerId = order.partner_id;
if(missingPartnerIds.has(partnerId)) continue;
if (partnerId && !this.db.get_partner_by_id(partnerId)) {
missingPartnerIds.add(partnerId);
}
}
await this._loadPartners([...missingPartnerIds]);
}
async loadProductsBackground() {
let page = 0;
let products = [];
do {
products = await this.env.services.rpc({
model: 'pos.session',
method: 'get_pos_ui_product_product_by_params',
args: [odoo.pos_session_id, {
offset: page * this.config.limited_products_amount,
limit: this.config.limited_products_amount,
}],
}, { shadow: true });
await this._loadMissingPricelistItems(products);
this._loadProductProduct(products);
page += 1;
} while(products.length == this.config.limited_products_amount);
}
async loadPartnersBackground(domain=[], offset=0, order=false) {
// Start at the first page since the first set of loaded partners are not actually in the
// same order as this background loading procedure.
let i = 0;
let partners = [];
do {
partners = await this.env.services.rpc({
model: 'pos.session',
method: 'get_pos_ui_res_partner_by_params',
args: [
[odoo.pos_session_id],
{
domain: domain,
limit: this.config.limited_partners_amount,
offset: offset + this.config.limited_partners_amount * i,
order: order,
},
],
context: this.env.session.user_context,
}, { shadow: true });
this.addPartners(partners);
i += 1;
} while(partners.length);
}
async getProductInfo(product, quantity) {
const order = this.get_order();
// check back-end method `get_product_info_pos` to see what it returns
// We do this so it's easier to override the value returned and use it in the component template later
const productInfo = await this.env.services.rpc({
model: 'product.product',
method: 'get_product_info_pos',
args: [[product.id],
product.get_price(order.pricelist, quantity),
quantity,
this.config.id],
kwargs: {context: this.env.session.user_context},
});
const priceWithoutTax = productInfo['all_prices']['price_without_tax'];
const margin = priceWithoutTax - product.standard_price;
const orderPriceWithoutTax = order.get_total_without_tax();
const orderCost = order.get_total_cost();
const orderMargin = orderPriceWithoutTax - orderCost;
const costCurrency = this.format_currency(product.standard_price);
const marginCurrency = this.format_currency(margin);
const marginPercent = priceWithoutTax ? Math.round(margin/priceWithoutTax * 10000) / 100 : 0;
const orderPriceWithoutTaxCurrency = this.format_currency(orderPriceWithoutTax);
const orderCostCurrency = this.format_currency(orderCost);
const orderMarginCurrency = this.format_currency(orderMargin);
const orderMarginPercent = orderPriceWithoutTax ? Math.round(orderMargin/orderPriceWithoutTax * 10000) / 100 : 0;
return {
costCurrency, marginCurrency, marginPercent, orderPriceWithoutTaxCurrency,
orderCostCurrency, orderMarginCurrency, orderMarginPercent,productInfo
}
}
async getClosePosInfo() {
const closingData = await this.env.services.rpc({
model: 'pos.session',
method: 'get_closing_control_data',
args: [[this.pos_session.id]]
});
const ordersDetails = closingData.orders_details;
const paymentsAmount = closingData.payments_amount;
const payLaterAmount = closingData.pay_later_amount;
const openingNotes = closingData.opening_notes;
const defaultCashDetails = closingData.default_cash_details;
const otherPaymentMethods = closingData.other_payment_methods;
const isManager = closingData.is_manager;
const amountAuthorizedDiff = closingData.amount_authorized_diff;
const cashControl = this.config.cash_control;
// component state and refs definition
const state = {notes: '', acceptClosing: false, payments: {}};
if (cashControl) {
state.payments[defaultCashDetails.id] = {counted: 0, difference: -defaultCashDetails.amount, number: 0};
}
if (otherPaymentMethods.length > 0) {
otherPaymentMethods.forEach(pm => {
if (pm.type === 'bank') {
state.payments[pm.id] = {counted: this.round_decimals_currency(pm.amount), difference: 0, number: pm.number}
}
})
}
return {
ordersDetails, paymentsAmount, payLaterAmount, openingNotes, defaultCashDetails, otherPaymentMethods,
isManager, amountAuthorizedDiff, state, cashControl
}
}
set_start_order(){
if (this.orders.length && !this.selectedOrder) {
this.selectedOrder = this.orders[0]
} else {
this.add_new_order();
}
}
// return the current order
get_order(){
return this.selectedOrder;
}
// change the current order
set_order(order, options){
this.selectedOrder = order;
}
// return the list of unpaid orders
get_order_list(){
return this.orders;
}
computePriceAfterFp(price, taxes){
const order = this.get_order();
if(order && order.fiscal_position) {
let mapped_included_taxes = [];
let new_included_taxes = [];
const self = this;
_(taxes).each(function(tax) {
const line_taxes = self.get_taxes_after_fp([tax.id], order.fiscal_position);
if (line_taxes.length && line_taxes[0].price_include){
new_included_taxes = new_included_taxes.concat(line_taxes);
}
if(tax.price_include && !_.contains(line_taxes, tax)){
mapped_included_taxes.push(tax);
}
});
if (mapped_included_taxes.length > 0) {
if (new_included_taxes.length > 0) {
//If previous tax and new tax where both included in price. The price including tax is the same
return price;
}
else{
return this.compute_all(mapped_included_taxes, price, 1, this.currency.rounding, true).total_excluded;
}
}
}
return price;
}
getTaxesByIds(taxIds) {
let taxes = [];
for (let i = 0; i < taxIds.length; i++) {
if (this.taxes_by_id[taxIds[i]]) {
taxes.push(this.taxes_by_id[taxIds[i]]);
}
}
return taxes;
}
_convert_product_img_to_base64 (product, url) {
return new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this,0,0);
var dataURL = canvas.toDataURL('image/jpeg');
canvas = null;
resolve([product, dataURL]);
};
img.crossOrigin = 'use-credentials';
img.src = url;
});
}
get customer_display() {
return this.unwatched.customer_display;
}
set customer_display(value) {
this.unwatched.customer_display = markRaw(value);
}
send_current_order_to_customer_facing_display() {
var self = this;
if (!this.config.iface_customer_facing_display) return;
this.render_html_for_customer_facing_display().then((rendered_html) => {
if (self.env.pos.customer_display) {
var $renderedHtml = $('<div>').html(rendered_html);
$(self.env.pos.customer_display.document.body).html($renderedHtml.find('.pos-customer_facing_display'));
var orderlines = $(self.env.pos.customer_display.document.body).find('.pos_orderlines_list');
orderlines.scrollTop(orderlines.prop("scrollHeight"));
} else if (this.config.iface_customer_facing_display_via_proxy && this.env.proxy.posbox_supports_display) {
this.env.proxy.update_customer_facing_display(rendered_html);
}
});
}
/**
* @returns {Promise<string>}
*/
render_html_for_customer_facing_display () {
var self = this;
var order = this.get_order();
// If we're using an external device like the IoT Box, we
// cannot get /web/image?model=product.product because the
// IoT Box is not logged in and thus doesn't have the access
// rights to access product.product. So instead we'll base64
// encode it and embed it in the HTML.
var get_image_promises = [];
if (order) {
order.get_orderlines().forEach(function (orderline) {
var product = orderline.product;
var image_url = `/web/image?model=product.product&field=image_128&id=${product.id}&unique=${product.__last_update}`;
// only download and convert image if we haven't done it before
if (!(product.id in PRODUCT_ID_TO_IMAGE_CACHE)) {
get_image_promises.push(self._convert_product_img_to_base64(product, image_url));
}
});
}
return Promise.all(get_image_promises).then(function (productIdImagePairs) {
for (let [product, image] of productIdImagePairs) {
PRODUCT_ID_TO_IMAGE_CACHE[product.id] = image;
}
// Collect the product images that will be used in rendering the customer display template.
const productImages = {};
if (order) {
for (const line of order.get_orderlines()) {
productImages[line.product.id] = PRODUCT_ID_TO_IMAGE_CACHE[line.product.id];
}
}
return QWeb.render('CustomerFacingDisplayOrder', {
pos: self,
origin: window.location.origin,
order: order,
productImages
});
});
}
// To be used in the context of closing the POS
// Saves the order locally and try to send it to the backend.
// If there is an error show a popup and ask to continue the closing or not
// return a successful promise on sync or if user decides to contine else reject
async push_orders_with_closing_popup (order, opts) {
try {
return await this.push_orders(order, opts);
} catch (error) {
console.warn(error);
const reason = this.env.pos.failed
? this.env._t(
'Some orders could not be submitted to ' +
'the server due to configuration errors. ' +
'You can exit the Point of Sale, but do ' +
'not close the session before the issue ' +
'has been resolved.'
)
: this.env._t(
'Some orders could not be submitted to ' +
'the server due to internet connection issues. ' +
'You can exit the Point of Sale, but do ' +
'not close the session before the issue ' +
'has been resolved.'
);
const { confirmed } = await Gui.showPopup('ConfirmPopup', {
title: this.env._t('Offline Orders'),
body: reason,
confirmText: this.env._t('Close anyway'),
cancelText: this.env._t('Do not close'),
});
return confirmed ? Promise.resolve(true) : Promise.reject();
}
}
// saves the order locally and try to send it to the backend.
// it returns a promise that succeeds after having tried to send the order and all the other pending orders.
push_orders (order, opts) {
opts = opts || {};
var self = this;
if (order) {
this.db.add_order(order.export_as_JSON());
}
return new Promise((resolve, reject) => {
this.env.posMutex.exec(async () => {
try {
resolve(await self._flush_orders(self.db.get_orders(), opts));
} catch (error) {
reject(error);
}
});
});
}
push_single_order (order, opts) {
opts = opts || {};
const self = this;
const order_id = self.db.add_order(order.export_as_JSON());
return new Promise((resolve, reject) => {
this.env.posMutex.exec(async () => {
const order = self.db.get_order(order_id);
try {
resolve(await self._flush_orders([order], opts));
} catch (error) {
reject(error);
}
});
});
}
// Send validated orders to the backend.
// Resolves to the backend ids of the synced orders.
_flush_orders(orders, options) {
var self = this;
return this._save_to_server(orders, options).then(function (server_ids) {
for (let i = 0; i < server_ids.length; i++) {
self.validated_orders_name_server_id_map[server_ids[i].pos_reference] = server_ids[i].id;
}
return server_ids;
}).catch(function(error) {
if (self._isRPCError(error)) {
if (orders.length > 1) {
return self._flush_orders_retry(orders, options);
} else {
self.set_synch('error');
throw error;
}
} else {
self.set_synch('disconnected');
throw error;
}
}).finally(function() {
self._after_flush_orders(orders);
});
}
// Attempts to send the orders to the server one by one if an RPC error is encountered.
async _flush_orders_retry(orders, options) {
let successfulOrders = 0;
let lastError;
let serverIds = [];
for (let order of orders) {
try {
let server_ids = await this._save_to_server([order], options);
successfulOrders++;
this.validated_orders_name_server_id_map[server_ids[0].pos_reference] = server_ids[0].id;
serverIds.push(server_ids[0]);
} catch (err) {
lastError = err;
}
}
if (successfulOrders === orders.length) {
this.set_synch('connected');
return serverIds;
}
if (this._isRPCError(lastError)) {
this.set_synch('error');
} else {
this.set_synch('disconnected');
}
throw lastError;
}
_isRPCError(err) {
return err.message && err.message.name === 'RPC_ERROR';
}
/**
* Hook method after _flush_orders resolved or rejected.
* It aims to:
* - remove the refund orderlines from toRefundLines
* - invalidate cache of refunded synced orders
*/
_after_flush_orders(orders) {
const refundedOrderIds = new Set();
for (const order of orders) {
for (const line of order.data.lines) {
const refundDetail = this.toRefundLines[line[2].refunded_orderline_id];
if (!refundDetail) continue;
// Collect the backend id of the refunded orders.
refundedOrderIds.add(refundDetail.orderline.orderBackendId);
// Reset the refund detail for the orderline.
delete this.toRefundLines[refundDetail.orderline.id];
}
}
this._invalidateSyncedOrdersCache([...refundedOrderIds]);
}
_invalidateSyncedOrdersCache(ids) {
for (const id of ids) {
delete this.TICKET_SCREEN_STATE.syncedOrders.cache[id];
}
}
set_synch(status, pending) {
if (['connected', 'connecting', 'error', 'disconnected'].indexOf(status) === -1) {
console.error(status, ' is not a known connection state.');
}
pending = pending || this.db.get_orders().length + this.db.get_ids_to_remove_from_server().length;
this.synch = { status, pending };
}
// send an array of orders to the server
// available options:
// - timeout: timeout for the rpc call in ms
// returns a promise that resolves with the list of
// server generated ids for the sent orders
_save_to_server (orders, options) {
if (!orders || !orders.length) {
return Promise.resolve([]);
}
// Filter out orders that are already being synced
const ordersToSync = orders.filter(order => !this.syncingOrders.has(order.id));
if (!ordersToSync.length) {
return Promise.resolve([]);
}
// Add these order IDs to the syncing set
ordersToSync.forEach(order => this.syncingOrders.add(order.id));