/
basic_fields.js
4364 lines (4043 loc) · 142 KB
/
basic_fields.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 ace */
odoo.define('web.basic_fields', function (require) {
"use strict";
/**
* This module contains most of the basic (meaning: non relational) field
* widgets. Field widgets are supposed to be used in views inheriting from
* BasicView, so, they can work with the records obtained from a BasicModel.
*/
var AbstractField = require('web.AbstractField');
var config = require('web.config');
var core = require('web.core');
var datepicker = require('web.datepicker');
var deprecatedFields = require('web.basic_fields.deprecated');
var dom = require('web.dom');
var Domain = require('web.Domain');
var DomainSelector = require('web.DomainSelector');
var DomainSelectorDialog = require('web.DomainSelectorDialog');
var ModelFieldSelectorPopover = require("web.ModelFieldSelectorPopover");
var framework = require('web.framework');
var py_utils = require('web.py_utils');
var session = require('web.session');
var utils = require('web.utils');
var view_dialogs = require('web.view_dialogs');
var field_utils = require('web.field_utils');
var time = require('web.time');
const {ColorpickerDialog} = require('web.Colorpicker');
const { hidePDFJSButtons } = require('@web/legacy/js/libs/pdfjs');
let FieldBoolean = deprecatedFields.FieldBoolean;
require("web.zoomodoo");
var qweb = core.qweb;
var _t = core._t;
var _lt = core._lt;
var TranslatableFieldMixin = {
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
* @returns {jQuery}
*/
_renderTranslateButton: function () {
if (_t.database.multi_lang && this.field.translate) {
var lang = _t.database.parameters.code.split('_')[0].toUpperCase();
return $(`<span class="o_field_translate btn btn-link">${lang}</span>`)
.on('click', this._onTranslate.bind(this));
}
return $();
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* open the translation view for the current field
*
* @param {MouseEvent} ev
* @private
*/
_onTranslate: function (ev) {
ev.preventDefault();
this.trigger_up('translate', {
fieldName: this.name,
id: this.dataPointID,
isComingFromTranslationAlert: false,
});
},
};
var DynamicPlaceholderFieldMixin = {
DYNAMIC_PLACEHOLDER_TRIGGER_KEY: '#',
/**
* Overridable method that ensure the modelSelectorPopover is
* positioned properly.
*
* @public
* @param {ModelFieldSelectorPopover} modelSelector
*/
positionModelSelector: function (modelSelector) {
let relativeParent = this.el.closest('div.modal-content');
if (!relativeParent) {
relativeParent = this.el;
while(!relativeParent || !['absolute', 'relative'].includes(getComputedStyle(relativeParent).position)) {
relativeParent = relativeParent.offsetParent;
}
}
const relatedElementPosition = this.el.getBoundingClientRect();
const relativeParentPosition = relativeParent.getBoundingClientRect();
let topPosition = relatedElementPosition.top + relatedElementPosition.height - relativeParentPosition.top
let leftPosition = relatedElementPosition.left - relativeParentPosition.left;
modelSelector.el.style.top = topPosition + 'px';
modelSelector.el.style.left = leftPosition + 'px';
},
/**
* Open and return new Model Field Selector with the provided options
*
* @private
* @param {String} baseModel
* @param {Array} chain
* @param {Function} onFieldChanged
* @param {Function} onFieldCancel
*
* @returns {ModelFieldSelectorPopover}
*/
_openNewModelSelector: async function (baseModel, chain, onFieldChanged = null, onFieldCancel = null) {
const triggerKeyReplaceRegex = new RegExp(`${this.DYNAMIC_PLACEHOLDER_TRIGGER_KEY}$`);
const modelSelector = new ModelFieldSelectorPopover(
this,
baseModel,
[],
{
readonly: false,
needDefaultValue: true,
cancelOnEscape: true,
chainedTitle: true,
filter: (model) => !["one2many", "boolean", "many2many"].includes(model.type)
}
);
if (!onFieldChanged) {
onFieldChanged = (ev) => {
this.$el.focus();
if (ev.data.chain.length) {
let dynamicPlaceholder = "{{object." + ev.data.chain.join('.');
const defaultValue = ev.data.defaultValue;
dynamicPlaceholder += defaultValue && defaultValue !== '' ? ` or '''${defaultValue}'''}}` : '}}';
this.el.value =
this.el.value.replace(triggerKeyReplaceRegex, '') + dynamicPlaceholder;
}
modelSelector.destroy();
};
}
if (onFieldCancel === null) {
onFieldCancel = () => {
this.$el.focus();
modelSelector.destroy();
};
}
modelSelector.on("field_chain_changed", undefined, onFieldChanged);
modelSelector.on("field_chain_cancel", undefined, onFieldCancel);
// If we are inside a modal environment,
// we need to append the ModelFieldSelectorPopover outside the
// modal body, to be sure the overflow will be visible.
const modalParent = this.el.closest('div.modal-content');
if (modalParent) {
await modelSelector.appendTo(modalParent);
} else {
await modelSelector.insertAfter(this.el);
}
this.positionModelSelector(modelSelector);
modelSelector.open(chain, true);
return modelSelector;
},
};
var DebouncedField = AbstractField.extend({
/**
* For field widgets that may have a large number of field changes quickly,
* it could be a good idea to debounce the changes. In that case, this is
* the suggested value.
*/
DEBOUNCE: 1000000000,
/**
* Override init to debounce the field "_doAction" method (by creating a new
* one called "_doDebouncedAction"). By default, this method notifies the
* current value of the field and we do not want that to happen for each
* keystroke. Note that this is done here and not on the prototype, so that
* each DebouncedField has its own debounced function to work with. Also, if
* the debounce value is set to 0, no debouncing is done, which is really
* useful for the unit tests.
*
* @constructor
* @override
*/
init: function () {
this._super.apply(this, arguments);
// _isDirty is used to detect that the user interacted at least
// once with the widget, so that we can prevent it from triggering a
// field_changed in commitChanges if the user didn't change anything
this._isDirty = false;
if (this.mode === 'edit') {
if (this.DEBOUNCE) {
this._doDebouncedAction = _.debounce(this._doAction, this.DEBOUNCE);
} else {
this._doDebouncedAction = this._doAction;
}
var self = this;
var debouncedFunction = this._doDebouncedAction;
this._doDebouncedAction = function () {
self._isDirty = true;
debouncedFunction.apply(self, arguments);
};
}
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* This field main action is debounced and might sets the field's value.
* When the changes are asked to be commited, the debounced action has to
* be done immediately.
*
* @override
*/
commitChanges: function () {
if (this._isDirty && this.mode === 'edit') {
return this._doAction();
}
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* By default, notifies the outside world of the new value (checked from the
* DOM). This method has an automatically-created (@see init) associated
* debounced version called _doDebouncedAction.
*
* @private
*/
_doAction: function () {
// as _doAction may be debounced, it may happen that it is called after
// the widget has been destroyed, and in this case, we don't want it to
// do anything (commitChanges ensures that if it has local changes, they
// are triggered up before the widget is destroyed, if necessary).
if (!this.isDestroyed()) {
return this._setValue(this._getValue());
}
},
/**
* Should return the current value of the field, in the DOM (for example,
* the content of the input)
*
* @abstract
* @private
* @returns {*}
*/
_getValue: function () {},
/**
* Should make an action on lost focus.
*
* @abstract
* @private
* @returns {*}
*/
_onBlur: function () {},
});
var InputField = DebouncedField.extend({
custom_events: _.extend({}, DebouncedField.prototype.custom_events, {
field_changed: '_onFieldChanged',
}),
events: _.extend({}, DebouncedField.prototype.events, {
'input': '_onInput',
'change': '_onChange',
'blur' : '_onBlur',
}),
/**
* Prepares the rendering so that it creates an element the user can type
* text into in edit mode.
*
* @override
*/
init: function () {
this._super.apply(this, arguments);
this.nodeOptions.isPassword = 'password' in this.attrs;
if (this.mode === 'edit') {
this.tagName = 'input';
}
// We need to know if the widget is dirty (i.e. if the user has changed
// the value, and those changes haven't been acknowledged yet by the
// environment), to prevent erasing that new value on a reset (e.g.
// coming by an onchange on another field)
this.isDirty = false;
this.lastChangeEvent = undefined;
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Returns the associated <input/> element.
*
* @override
*/
getFocusableElement: function () {
return this.$input || $();
},
/**
* Re-renders the widget if it isn't dirty. The widget is dirty if the user
* changed the value, and that change hasn't been acknowledged yet by the
* environment. For example, another field with an onchange has been updated
* and this field is updated before the onchange returns. Two '_setValue'
* are done (this is sequential), the first one returns and this widget is
* reset. However, it has pending changes, so we don't re-render.
*
* @override
*/
reset: function (record, event) {
this._reset(record, event);
if (!event || event === this.lastChangeEvent) {
this.isDirty = false;
}
if (this.isDirty || (event && event.target === this &&
event.data.changes &&
event.data.changes[this.name] === this.value)) {
if (this.attrs.decorations) {
// if a field is modified, then it could have triggered an onchange
// which changed some of its decorations. Since we bypass the
// render function, we need to apply decorations here to make
// sure they are recomputed.
this._applyDecorations();
}
return Promise.resolve();
} else {
return this._render();
}
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @override
* @returns {string} the content of the input
*/
_getValue: function () {
return this.$input.val();
},
/**
* By default this only calls a debounced method to notify the outside world
* of the changes if the actual value is not the same than the previous one.
* @see _doDebouncedAction
*/
_notifyChanges() {
this.isDirty = !this._isLastSetValue(this.$input.val());
this._doDebouncedAction();
},
/**
* Formats an input element for edit mode. This is in a separate function so
* extending widgets can use it on their input without having input as tagName.
*
* @private
* @param {jQuery|undefined} $input
* The <input/> element to prepare and save as the $input attribute.
* If no element is given, the <input/> is created.
* @returns {jQuery} the prepared this.$input element
*/
_prepareInput: function ($input) {
this.$input = $input || $("<input/>");
this.$input.addClass('o_input');
var inputAttrs = { placeholder: this.attrs.placeholder || "" };
var inputVal;
if (this.nodeOptions.isPassword) {
inputAttrs = _.extend(inputAttrs, { type: 'password', autocomplete: this.attrs.autocomplete || 'new-password' });
inputVal = this.value || '';
} else {
inputAttrs = _.extend(inputAttrs, { type: 'text', autocomplete: this.attrs.autocomplete || 'off'});
inputVal = this._formatValue(this.value);
}
this.$input.attr(inputAttrs);
this.$input.val(inputVal);
return this.$input;
},
/**
* Formats the HTML input tag for edit mode and stores selection status.
*
* @override
* @private
*/
_renderEdit: function () {
// Keep a reference to the input so $el can become something else
// without losing track of the actual input.
this._prepareInput(this.$el);
},
/**
* Resets the content to the formated value in readonly mode.
*
* @override
* @private
*/
_renderReadonly: function () {
this.$el.text(this._formatValue(this.value));
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* We immediately notify the outside world when this field confirms its
* changes.
*
* @private
*/
_onChange: function () {
this._doAction();
},
/**
* Listens to events 'field_changed' to keep track of the last event that
* has been trigerred. This allows to detect that all changes have been
* acknowledged by the environment.
*
* @param {OdooEvent} event 'field_changed' event
*/
_onFieldChanged: function (event) {
this.lastChangeEvent = event;
},
/**
* Called when the user is typing text
* @see _notifyChanges
*
* @private
*/
_onInput() {
this._notifyChanges();
},
/**
* Stops the left/right navigation move event if the cursor is not at the
* start/end of the input element.
*
* @private
* @param {OdooEvent} ev
*/
_onNavigationMove: function (ev) {
this._super.apply(this, arguments);
// the following code only makes sense in edit mode, with an input
if (this.mode === 'edit' && ev.data.direction !== 'cancel') {
var input = this.$input[0];
var selecting = (input.selectionEnd !== input.selectionStart);
if ((ev.data.direction === "left" && (selecting || input.selectionStart !== 0))
|| (ev.data.direction === "right" && (selecting || input.selectionStart !== input.value.length))) {
ev.stopPropagation();
}
if (ev.data.direction ==='next' &&
this.attrs.modifiersValue &&
this.attrs.modifiersValue.required &&
this.viewType !== 'list') {
if (!this.$input.val()){
this.setInvalidClass();
ev.stopPropagation();
} else {
this.removeInvalidClass();
}
}
}
},
});
var NumericField = InputField.extend({
tagName: 'span',
/**
* @override
*/
init() {
this._super.apply(this, arguments);
this.shouldFormat = Boolean(
JSON.parse('format' in this.nodeOptions ? this.nodeOptions.format : true)
);
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* For numeric fields, 0 is a valid value.
*
* @override
*/
isSet: function () {
return this.value === 0 || this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Evaluate a string representing a simple formula,
* a formula is composed of numbers and arithmetic operations
* (ex: 4+3*2)
*
* Supported arithmetic operations: + - * / ^ ( )
* Since each number in the formula can be expressed in user locale,
* we parse each float value inside the formula using the user context
* This function uses py_eval to safe eval the formula.
* We assume that this function is used as a calculator so operand ^ (xor)
* is replaced by operand ** (power) so that users that are used to
* excel or libreoffice are not confused
*
* @private
* @param expr
* @return a float representing the result of the evaluated formula
* @throws error if formula can't be evaluated
*/
_evalFormula: function (expr, context) {
// remove extra space
var val = expr.replace(new RegExp(/( )/g), '');
var safeEvalString = '';
for (let v of val.split(new RegExp(/([-+*/()^])/g))) {
if (!['+','-','*','/','(',')','^'].includes(v) && v.length) {
// check if this is a float and take into account user delimiter preference
v = field_utils.parse.float(v);
}
if (v === '^') {
v = '**';
}
safeEvalString += v;
};
return py_utils.py_eval(safeEvalString, context);
},
/**
* Format numerical value (integer or float)
*
* Note: We have to overwrite this method to skip the format if we are into
* edit mode on a input type number.
*
* @override
* @private
*/
_formatValue: function (value) {
if (!this.shouldFormat || (this.mode === 'edit' && this.nodeOptions.type === 'number')) {
return value;
}
return this._super.apply(this, arguments);
},
/**
* Parse numerical value (integer or float)
*
* Note: We have to overwrite this method to skip the format if we are into
* edit mode on a input type number.
*
* @override
* @private
*/
_parseValue: function (value) {
if (this.mode === 'edit' && this.nodeOptions.type === 'number') {
return Number(value);
}
return this._super.apply(this, arguments);
},
/**
* Formats an input element for edit mode. This is in a separate function so
* extending widgets can use it on their input without having input as tagName.
*
* Note: We have to overwrite this method to set the input's type to number if
* option setted into the field.
*
* @override
* @private
*/
_prepareInput: function ($input) {
var result = this._super.apply(this, arguments);
if (this.nodeOptions.type === 'number') {
this.$input.attr({type: 'number'});
}
if (this.nodeOptions.step) {
this.$input.attr({step: this.nodeOptions.step});
}
return result;
},
/**
* Evaluate value set by user if starts with =
*
* @override
* @private
* @param {any} value
* @param {Object} [options]
*/
_setValue: function (value, options) {
var originalValue = value;
value = value.trim();
if (value.startsWith('=')) {
try {
// Evaluate the formula
value = this._evalFormula(value.substr(1));
// Format back the value in user locale
value = this._formatValue(value);
// Set the computed value in the input
this.$input.val(value);
} catch (_err) {
// in case of exception, set value as the original value
// that way the Webclient will show an error as
// it is expecting a numeric value.
value = originalValue;
}
}
return this._super(value, options);
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* Replace the decimal separator of the numpad decimal key
* by the decimal separator from the user's language setting.
*
* @private
* @param {OdooEvent} ev
*/
_onKeydown(ev) {
const kbdEvt = ev.originalEvent;
if (kbdEvt && utils.isNumpadDecimalSeparatorKey(kbdEvt)) {
const inputField = this.$input[0];
if (inputField.type === 'number') {
return this._super(...arguments);
}
const curVal = inputField.value;
const from = inputField.selectionStart;
const to = inputField.selectionEnd;
const point = _t.database.parameters.decimal_point;
// Make sure the correct decimal separator
// from the user's settings is inserted
inputField.value = curVal.slice(0, from) + point + curVal.slice(to);
// Put the user caret at the right place
inputField.selectionStart = inputField.selectionEnd = from + point.length;
// Tell the world we made some changes and
// return preventing event default behaviour.
this._notifyChanges();
kbdEvt.preventDefault();
return;
}
return this._super(...arguments);
},
});
var FieldChar = InputField.extend(TranslatableFieldMixin, DynamicPlaceholderFieldMixin, {
description: _lt("Text"),
className: 'o_field_char',
tagName: 'span',
supportedFieldTypes: ['char'],
isQuickEditable: true,
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @override
*/
init: function () {
this._super(...arguments);
if (this.nodeOptions && this.nodeOptions.dynamic_placeholder) {
// When the dynamic placeholder is active, the recordData
// need to be updated when `mailing_model_real` change
this.resetOnAnyFieldChange = true;
}
},
/**
* Open the dynamic placeholder if trigger key match
*
* @private
* @override
* @param {KeyboardEvent} ev
*/
async _onKeydown(ev) {
this._super(...arguments);
if (this.nodeOptions &&
this.nodeOptions.dynamic_placeholder &&
ev.key === this.DYNAMIC_PLACEHOLDER_TRIGGER_KEY) {
ev.preventDefault();
const baseModel = this.recordData && this.recordData.mailing_model_real ? this.recordData.mailing_model_real : undefined;
if (baseModel) {
await this._openNewModelSelector(baseModel);
}
this.el.value += ev.key;
}
},
/**
* Add translation button
*
* @override
* @private
*/
_renderEdit: function () {
var def = this._super.apply(this, arguments);
if (this.field.size && this.field.size > 0) {
this.$el.attr('maxlength', this.field.size);
}
if (this.field.translate) {
this.$el = this.$el.add(this._renderTranslateButton());
this.$el.addClass('o_field_translate');
}
return def;
},
/**
* Trim the value input by the user.
*
* @override
* @private
* @param {any} value
* @param {Object} [options]
*/
_setValue: function (value, options) {
if (this.field.trim) {
value = value.trim();
}
return this._super(value, options);
},
});
var FieldDateRange = InputField.extend({
className: 'o_field_date_range',
tagName: 'span',
jsLibs: [
'/web/static/lib/daterangepicker/daterangepicker.js',
'/web/static/src/legacy/js/libs/daterangepicker.js',
],
supportedFieldTypes: ['date', 'datetime'],
isQuickEditable: true,
/**
* @override
*/
init: function () {
this._super.apply(this, arguments);
this.formatType = this.nodeOptions.format_type || this.formatType;
this.isDateField = this.formatType === 'date';
this.dateRangePickerOptions = _.defaults(
{},
this.nodeOptions.picker_options || {},
{
timePicker: !this.isDateField,
timePicker24Hour: _t.database.parameters.time_format.search('%H') !== -1,
autoUpdateInput: false,
timePickerIncrement: 5,
locale: {
applyLabel: _t('Apply'),
cancelLabel: _t('Cancel'),
format: this.isDateField ? time.getLangDateFormat() : time.getLangDatetimeFormat(),
},
}
);
this.relatedEndDate = this.nodeOptions.related_end_date;
this.relatedStartDate = this.nodeOptions.related_start_date;
},
/**
* @override
*/
destroy: function () {
if (this.$pickerContainer) {
this.$pickerContainer.remove();
}
if (this._onScroll) {
window.removeEventListener('scroll', this._onScroll, true);
}
this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Field widget is valid if value entered can convered to date/dateime value
* while parsing input value to date/datetime throws error then widget considered
* invalid
*
* @override
*/
isValid: function () {
const value = this.mode === "readonly" ? this.value : this.$input.val();
try {
return field_utils.parse[this.formatType](value, this.field, { timezone: true }) || true;
} catch (_error) {
return false;
}
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Return the date written in the input, in UTC.
*
* @private
* @returns {Moment|false}
*/
_getValue: function () {
try {
// user may enter manual value in input and it may not be parsed as date/datetime value
this.removeInvalidClass();
return field_utils.parse[this.formatType](this.$input.val(), this.field, { timezone: true });
} catch (_error) {
this.setInvalidClass();
return false;
}
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
* @param {Event} ev
* @param {Object} picker
*/
_applyChanges: function (ev, picker) {
var changes = {};
var displayStartDate = field_utils.format[this.formatType](picker.startDate, {}, {timezone: false});
var displayEndDate = field_utils.format[this.formatType](picker.endDate, {}, {timezone: false});
var changedStartDate = picker.startDate;
var changedEndDate = picker.endDate;
if (this.isDateField) {
// In date mode, the library will give moment object of start and end date having
// time at 00:00:00. So, Odoo will consider it as UTC. To fix this added browser
// timezone offset in dates to get a correct selected date.
changedStartDate = picker.startDate.add(session.getTZOffset(picker.startDate), 'minutes');
changedEndDate = picker.endDate.startOf('day').add(session.getTZOffset(picker.endDate), 'minutes');
}
if (this.relatedEndDate) {
this.$el.val(displayStartDate);
changes[this.name] = this._parseValue(changedStartDate);
changes[this.relatedEndDate] = this._parseValue(changedEndDate);
}
if (this.relatedStartDate) {
this.$el.val(displayEndDate);
changes[this.name] = this._parseValue(changedEndDate);
changes[this.relatedStartDate] = this._parseValue(changedStartDate);
}
this.trigger_up('field_changed', {
dataPointID: this.dataPointID,
viewType: this.viewType,
changes: changes,
});
},
/**
* @override
*/
_renderEdit: function () {
this._super.apply(this, arguments);
var self = this;
const [startDate, endDate] = this._getDateRangeFromInputField();
this.dateRangePickerOptions.startDate = startDate || moment();
this.dateRangePickerOptions.endDate = endDate || moment();
this.$el.daterangepicker(this.dateRangePickerOptions);
this.$el.on('apply.daterangepicker', this._applyChanges.bind(this));
this.$el.on('show.daterangepicker', this._onDateRangePickerShow.bind(this));
this.$el.on('hide.daterangepicker', this._onDateRangePickerHide.bind(this));
this.$el.off('keyup.daterangepicker');
this.$pickerContainer = this.$el.data('daterangepicker').container;
// Prevent from leaving the edition of a row in editable list view
this.$pickerContainer.on('click', function (ev) {
ev.stopPropagation();
if ($(ev.target).hasClass('applyBtn')) {
self.$el.data('daterangepicker').hide();
}
});
// Prevent bootstrap from focusing on modal (which breaks hours drop-down in firefox)
this.$pickerContainer.on('focusin.bs.modal', 'select', function (ev) {
ev.stopPropagation();
});
},
/**
* @private
* @override
*/
_quickEdit: function () {
if (this.$el) {
this.$el.click()
}
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* Unbind the scroll event handler when the daterangepicker is closed.
*
* @private
*/
_onDateRangePickerHide() {
if (this._onScroll) {
window.removeEventListener('scroll', this._onScroll, true);
}
},
/**
* Bind the scroll event handle when the daterangepicker is open.
* Update the begin and end date with the dates from the input values
*
* @private
*/
_onDateRangePickerShow() {
const daterangepicker = this.$el.data('daterangepicker');
this._onScroll = ev => {
if (!config.device.isMobile && !this.$pickerContainer.get(0).contains(ev.target)) {
daterangepicker.hide();
}
};
window.addEventListener('scroll', this._onScroll, true);
const [startDate, endDate] = this._getDateRangeFromInputField();
daterangepicker.setStartDate(startDate? startDate.utcOffset(session.getTZOffset(startDate)): moment());
daterangepicker.setEndDate(endDate? endDate.utcOffset(session.getTZOffset(endDate)): moment());
daterangepicker.updateView();
},
/**
* Get the startDate and endDate of the daterangepicker from the input fields
* @returns [Date (moment object), Date (moment object)]
* @private
*/
_getDateRangeFromInputField() {
let startDate, endDate;
if (this.relatedEndDate) {
startDate = this.value;
endDate = this.recordData[this.relatedEndDate];
}
if (this.relatedStartDate) {
startDate = this.recordData[this.relatedStartDate];
endDate = this.value;
}
return [startDate, endDate];
},
});
var FieldDate = InputField.extend({
description: _lt("Date"),
className: "o_field_date",
tagName: "span",
supportedFieldTypes: ['date', 'datetime'],
isQuickEditable: true,
// we don't need to listen on 'input' nor 'change' events because the
// datepicker widget is already listening, and will correctly notify changes
events: AbstractField.prototype.events,
/**
* @override
*/
init: function () {
this._super.apply(this, arguments);
// use the session timezone when formatting dates
this.formatOptions.timezone = true;
this.datepickerOptions = _.defaults(
{},
this.nodeOptions.datepicker || {},
{defaultDate: this.value}
);
},
/**
* In edit mode, instantiates a DateWidget datepicker and listen to changes.
*
* @override
*/
start: function () {
var self = this;
var prom;
if (this.mode === 'edit') {
this.datewidget = this._makeDatePicker();
this.datewidget.on('datetime_changed', this, function () {
var value = this._getValue();
if ((!value && this.value) || (value && !this._isSameValue(value))) {
this._setValue(value);
}
});
prom = this.datewidget.appendTo('<div>').then(function () {