/
basic_model.js
4828 lines (4673 loc) · 199 KB
/
basic_model.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
odoo.define('web.BasicModel', function (require) {
"use strict";
/**
* Basic Model
*
* This class contains all the logic necessary to communicate between the
* python models and the web client. More specifically, its job is to give a
* simple unified API to the rest of the web client (in particular, the views and
* the field widgets) to query and modify actual records in db.
*
* From a high level perspective, BasicModel is essentially a hashmap with
* integer keys and some data and metadata object as value. Each object in this
* hashmap represents a piece of data, and can be reloaded and modified by using
* its id as key in many methods.
*
* Here is a description of what those data point look like:
* var dataPoint = {
* _cache: {Object|undefined}
* _changes: {Object|null},
* aggregateValues: {Object},
* context: {Object},
* count: {integer},
* data: {Object|Object[]},
* domain: {*[]},
* fields: {Object},
* fieldsInfo: {Object},
* getContext: {function},
* getDomain: {function},
* getFieldNames: {function},
* groupedBy: {string[]},
* id: {integer},
* isOpen: {boolean},
* loadMoreOffset: {integer},
* limit: {integer},
* model: {string},
* offset: {integer},
* openGroupByDefault: {boolean},
* orderedBy: {Object[]},
* orderedResIDs: {integer[]},
* parentID: {string},
* rawContext: {Object},
* relationField: {string},
* res_id: {integer|null},
* res_ids: {integer[]},
* specialData: {Object},
* _specialDataCache: {Object},
* static: {boolean},
* type: {string} 'record' | 'list'
* value: ?,
* };
*
* Notes:
* - id: is totally unrelated to res_id. id is a web client local concept
* - res_id: if set to a number or a virtual id (a virtual id is a character
* string composed of an integer and has a dash and other information), it
* is an actual id for a record in the server database. If set to
* 'virtual_' + number, it is a record not yet saved (so, in create mode).
* - res_ids: if set, it represent the context in which the data point is actually
* used. For example, a given record in a form view (opened from a list view)
* might have a res_id = 2 and res_ids = [1,2,3]
* - offset: this is mainly used for pagination. Useful when we need to load
* another page, then we can simply change the offset and reload.
* - count is basically the number of records being manipulated. We can't use
* res_ids, because we might have a very large number of records, or a
* domain, and the res_ids would be the current page, not the full set.
* - model is the actual name of a (odoo) model, such as 'res.partner'
* - fields contains the description of all the fields from the model. Note that
* these properties might have been modified by a view (for example, with
* required=true. So, the fields kind of depends of the context of the
* data point.
* - field_names: list of some relevant field names (string). Usually, it
* denotes the fields present in the view. Only those fields should be
* loaded.
* - _cache and _changes are private, they should not leak out of the basicModel
* and be used by anyone else.
*
* Commands:
* commands are the base commands for x2many (0 -> 6), but with a
* slight twist: each [0, _, values] command is augmented with a virtual id:
* it means that when the command is added in basicmodel, it generates an id
* looking like this: 'virtual_' + number, and uses this id to identify the
* element, so it can be edited later.
*/
var AbstractModel = require('web.AbstractModel');
var concurrency = require('web.concurrency');
var Context = require('web.Context');
var core = require('web.core');
var Domain = require('web.Domain');
var session = require('web.session');
var utils = require('web.utils');
var viewUtils = require('web.viewUtils');
var _t = core._t;
var x2ManyCommands = {
// (0, virtualID, {values})
CREATE: 0,
create: function (virtualID, values) {
delete values.id;
return [x2ManyCommands.CREATE, virtualID || false, values];
},
// (1, id, {values})
UPDATE: 1,
update: function (id, values) {
delete values.id;
return [x2ManyCommands.UPDATE, id, values];
},
// (2, id[, _])
DELETE: 2,
delete: function (id) {
return [x2ManyCommands.DELETE, id, false];
},
// (3, id[, _]) removes relation, but not linked record itself
FORGET: 3,
forget: function (id) {
return [x2ManyCommands.FORGET, id, false];
},
// (4, id[, _])
LINK_TO: 4,
link_to: function (id) {
return [x2ManyCommands.LINK_TO, id, false];
},
// (5[, _[, _]])
DELETE_ALL: 5,
delete_all: function () {
return [5, false, false];
},
// (6, _, ids) replaces all linked records with provided ids
REPLACE_WITH: 6,
replace_with: function (ids) {
return [6, false, ids];
}
};
var BasicModel = AbstractModel.extend({
// constants
OPEN_GROUP_LIMIT: 10, // after this limit, groups are automatically folded
// list of models for which the DataManager's cache should be cleared on
// create, update and delete operations
noCacheModels: [
'ir.actions.act_window',
'ir.filters',
'ir.ui.view',
],
/**
* @override
*/
init: function () {
// this mutex is necessary to make sure some operations are done
// sequentially, for example, an onchange needs to be completed before a
// save is performed.
this.mutex = new concurrency.Mutex();
this.localData = Object.create(null);
this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Add a default record to a list object. This method actually makes a new
* record with the _makeDefaultRecord method, then adds it to the list object.
* The default record is added in the data directly. This is meant to be used
* by list or kanban controllers (i.e. not for x2manys in form views, as in
* this case, we store changes as commands).
*
* @param {string} listID a valid handle for a list object
* @param {Object} [options]
* @param {string} [options.position=top] if the new record should be added
* on top or on bottom of the list
* @returns {Promise<string>} resolves to the id of the new created record
*/
addDefaultRecord: function (listID, options) {
var self = this;
var list = this.localData[listID];
var context = _.extend({}, this._getDefaultContext(list), this._getContext(list));
var position = (options && options.position) || 'top';
var params = {
context: context,
fields: list.fields,
fieldsInfo: list.fieldsInfo,
parentID: list.id,
position: position,
viewType: list.viewType,
};
return this._makeDefaultRecord(list.model, params).then(function (id) {
list.count++;
if (position === 'top') {
list.data.unshift(id);
} else {
list.data.push(id);
}
var record = self.localData[id];
list._cache[record.res_id] = id;
return id;
});
},
/**
* Completes the fields and fieldsInfo of a dataPoint with the given ones.
* It is useful for the cases where a record element is shared between
* various views, such as a one2many with a tree and a form view.
*
* @param {string} recordID a valid element ID
* @param {Object} viewInfo
* @param {Object} viewInfo.fields
* @param {Object} viewInfo.fieldsInfo
*/
addFieldsInfo: function (recordID, viewInfo) {
var record = this.localData[recordID];
record.fields = _.extend({}, record.fields, viewInfo.fields);
// complete the given fieldsInfo with the fields of the main view, so
// that those field will be reloaded if a reload is triggered by the
// secondary view
var fieldsInfo = _.mapObject(viewInfo.fieldsInfo, function (fieldsInfo) {
return _.defaults({}, fieldsInfo, record.fieldsInfo[record.viewType]);
});
record.fieldsInfo = _.extend({}, record.fieldsInfo, fieldsInfo);
},
/**
* Add and process default values for a given record. Those values are
* parsed and stored in the '_changes' key of the record. For relational
* fields, sub-dataPoints are created, and missing relational data is
* fetched. Also generate default values for fields with no given value.
* Typically, this function is called with the result of a 'default_get'
* RPC, to populate a newly created dataPoint. It may also be called when a
* one2many subrecord is open in a form view (dialog), to generate the
* default values for the fields displayed in the o2m form view, but not in
* the list or kanban (mainly to correctly create sub-dataPoints for
* relational fields).
*
* @param {string} recordID local id for a record
* @param {Object} values dict of default values for the given record
* @param {Object} [options]
* @param {string} [options.viewType] current viewType. If not set, we will
* assume main viewType from the record
* @param {Array} [options.fieldNames] list of field names for which a
* default value must be generated (used to complete the values dict)
* @returns {Promise}
*/
applyDefaultValues: function (recordID, values, options) {
options = options || {};
var record = this.localData[recordID];
var viewType = options.viewType || record.viewType;
var fieldNames = options.fieldNames || Object.keys(record.fieldsInfo[viewType]);
var field;
var fieldName;
record._changes = record._changes || {};
// ignore values for non requested fields (for instance, fields that are
// not in the view)
values = _.pick(values, fieldNames);
// fill default values for missing fields
for (var i = 0; i < fieldNames.length; i++) {
fieldName = fieldNames[i];
if (!(fieldName in values) && !(fieldName in record._changes)) {
field = record.fields[fieldName];
if (field.type === 'float' ||
field.type === 'integer' ||
field.type === 'monetary') {
values[fieldName] = 0;
} else if (field.type === 'one2many' || field.type === 'many2many') {
values[fieldName] = [];
} else {
values[fieldName] = null;
}
}
}
// parse each value and create dataPoints for relational fields
var defs = [];
for (fieldName in values) {
field = record.fields[fieldName];
record.data[fieldName] = null;
var dp;
if (field.type === 'many2one' && values[fieldName]) {
dp = this._makeDataPoint({
context: record.context,
data: {id: values[fieldName]},
modelName: field.relation,
parentID: record.id,
});
record._changes[fieldName] = dp.id;
} else if (field.type === 'reference' && values[fieldName]) {
var ref = values[fieldName].split(',');
dp = this._makeDataPoint({
context: record.context,
data: {id: parseInt(ref[1])},
modelName: ref[0],
parentID: record.id,
});
defs.push(this._fetchNameGet(dp));
record._changes[fieldName] = dp.id;
} else if (field.type === 'one2many' || field.type === 'many2many') {
defs.push(this._processX2ManyCommands(record, fieldName, values[fieldName], options));
} else {
record._changes[fieldName] = this._parseServerValue(field, values[fieldName]);
}
}
return Promise.all(defs);
},
/**
* Onchange RPCs may return values for fields that are not in the current
* view. Those fields might even be unknown when the onchange returns (e.g.
* in x2manys, we only know the fields that are used in the inner view, but
* not those used in the potential form view opened in a dialog when a sub-
* record is clicked). When this happens, we can't infer their type, so the
* given value can't be processed. It is instead stored in the '_rawChanges'
* key of the record, without any processing. Later on, if this record is
* displayed in another view (e.g. the user clicked on it in the x2many
* list, and the record opens in a dialog), those changes that were left
* behind must be applied. This function applies changes stored in
* '_rawChanges' for a given viewType.
*
* @param {string} recordID local resource id of a record
* @param {string} viewType the current viewType
* @returns {Promise<string>} resolves to the id of the record
*/
applyRawChanges: function (recordID, viewType) {
var record = this.localData[recordID];
return this._applyOnChange(record._rawChanges, record, viewType).then(function () {
return record.id;
});
},
/**
* Returns true if a record can be abandoned.
*
* Case for not abandoning the record:
*
* 1. flagged as 'no abandon' (i.e. during a `default_get`, including any
* `onchange` from a `default_get`)
* 2. registered in a list on addition
*
* 2.1. registered as non-new addition
* 2.2. registered as new additon on update
*
* 3. record is not new
*
* Otherwise, the record can be abandoned.
*
* This is useful when discarding changes on this record, as it means that
* we must keep the record even if some fields are invalids (e.g. required
* field is empty).
*
* @param {string} id id for a local resource
* @returns {boolean}
*/
canBeAbandoned: function (id) {
// 1. no drop if flagged
if (this.localData[id]._noAbandon) {
return false;
}
// 2. no drop in a list on "ADD in some cases
var record = this.localData[id];
var parent = this.localData[record.parentID];
if (parent) {
var entry = _.findWhere(parent._savePoint, {operation: 'ADD', id: id});
if (entry) {
// 2.1. no drop on non-new addition in list
if (!entry.isNew) {
return false;
}
// 2.2. no drop on new addition on "UPDATE"
var lastEntry = _.last(parent._savePoint);
if (lastEntry.operation === 'UPDATE' && lastEntry.id === id) {
return false;
}
}
}
// 3. drop new records
return this.isNew(id);
},
/**
* Delete a list of records, then, if the records have a parent, reload it.
*
* @todo we should remove the deleted records from the localData
* @todo why can't we infer modelName? Because of grouped datapoint
* --> res_id doesn't correspond to the model and we don't have the
* information about the related model
*
* @param {string[]} recordIds list of local resources ids. They should all
* be of type 'record', be of the same model and have the same parent.
* @param {string} modelName mode name used to unlink the records
* @returns {Promise}
*/
deleteRecords: function (recordIds, modelName) {
var self = this;
var records = _.map(recordIds, function (id) { return self.localData[id]; });
var context = _.extend(records[0].getContext(), session.user_context);
return this._rpc({
model: modelName,
method: 'unlink',
args: [_.pluck(records, 'res_id')],
context: context,
})
.then(function () {
_.each(records, function (record) {
var parent = record.parentID && self.localData[record.parentID];
if (parent && parent.type === 'list') {
parent.data = _.without(parent.data, record.id);
delete self.localData[record.id];
} else {
record.res_ids.splice(record.offset, 1);
record.offset = Math.min(record.offset, record.res_ids.length - 1);
record.res_id = record.res_ids[record.offset];
record.count--;
}
});
// optionally clear the DataManager's cache
self._invalidateCache(records[0]);
});
},
/**
* Discard all changes in a local resource. Basically, it removes
* everything that was stored in a _changes key.
*
* @param {string} id local resource id
* @param {Object} [options]
* @param {boolean} [options.rollback=false] if true, the changes will
* be reset to the last _savePoint, otherwise, they are reset to null
*/
discardChanges: function (id, options) {
options = options || {};
var element = this.localData[id];
var isNew = this.isNew(id);
var rollback = 'rollback' in options ? options.rollback : isNew;
var initialOffset = element.offset;
element._domains = {};
this._visitChildren(element, function (elem) {
if (rollback && elem._savePoint) {
if (elem._savePoint instanceof Array) {
elem._changes = elem._savePoint.slice(0);
} else {
elem._changes = _.extend({}, elem._savePoint);
}
elem._isDirty = !isNew;
} else {
elem._changes = null;
elem._isDirty = false;
}
elem.offset = 0;
if (elem.tempLimitIncrement) {
elem.limit -= elem.tempLimitIncrement;
delete elem.tempLimitIncrement;
}
});
element.offset = initialOffset;
},
/**
* Duplicate a record (by calling the 'copy' route)
*
* @param {string} recordID id for a local resource
* @returns {Promise<string>} resolves to the id of duplicate record
*/
duplicateRecord: function (recordID) {
var self = this;
var record = this.localData[recordID];
var context = this._getContext(record);
return this._rpc({
model: record.model,
method: 'copy',
args: [record.data.id],
context: context,
})
.then(function (res_id) {
var index = record.res_ids.indexOf(record.res_id);
record.res_ids.splice(index + 1, 0, res_id);
return self.load({
fieldsInfo: record.fieldsInfo,
fields: record.fields,
modelName: record.model,
res_id: res_id,
res_ids: record.res_ids.slice(0),
viewType: record.viewType,
context: context,
});
});
},
/**
* For list resources, this freezes the current records order.
*
* @param {string} listID a valid element ID of type list
*/
freezeOrder: function (listID) {
var list = this.localData[listID];
if (list.type === 'record') {
return;
}
list = this._applyX2ManyOperations(list);
this._sortList(list);
this.localData[listID].orderedResIDs = list.res_ids;
},
/**
* The get method first argument is the handle returned by the load method.
* It is optional (the handle can be undefined). In some case, it makes
* sense to use the handle as a key, for example the BasicModel holds the
* data for various records, each with its local ID.
*
* synchronous method, it assumes that the resource has already been loaded.
*
* @param {string} id local id for the resource
* @param {any} options
* @param {boolean} [options.env=false] if true, will only return res_id
* (if record) or res_ids (if list)
* @param {boolean} [options.raw=false] if true, will not follow relations
* @returns {Object}
*/
get: function (id, options) {
var self = this;
options = options || {};
if (!(id in this.localData)) {
return null;
}
var element = this.localData[id];
if (options.env) {
var env = {
ids: element.res_ids ? element.res_ids.slice(0) : [],
};
if (element.type === 'record') {
env.currentId = this.isNew(element.id) ? undefined : element.res_id;
}
return env;
}
if (element.type === 'record') {
var data = _.extend({}, element.data, element._changes);
var relDataPoint;
for (var fieldName in data) {
var field = element.fields[fieldName];
if (data[fieldName] === null) {
data[fieldName] = false;
}
if (!field) {
continue;
}
// get relational datapoint
if (field.type === 'many2one') {
if (options.raw) {
relDataPoint = this.localData[data[fieldName]];
data[fieldName] = relDataPoint ? relDataPoint.res_id : false;
} else {
data[fieldName] = this.get(data[fieldName]) || false;
}
} else if (field.type === 'reference') {
if (options.raw) {
relDataPoint = this.localData[data[fieldName]];
data[fieldName] = relDataPoint ?
relDataPoint.model + ',' + relDataPoint.res_id :
false;
} else {
data[fieldName] = this.get(data[fieldName]) || false;
}
} else if (field.type === 'one2many' || field.type === 'many2many') {
if (options.raw) {
relDataPoint = this.localData[data[fieldName]];
relDataPoint = this._applyX2ManyOperations(relDataPoint);
data[fieldName] = relDataPoint.res_ids;
} else {
data[fieldName] = this.get(data[fieldName]) || [];
}
}
}
var record = {
context: _.extend({}, element.context),
count: element.count,
data: data,
domain: element.domain.slice(0),
evalModifiers: element.evalModifiers,
fields: element.fields,
fieldsInfo: element.fieldsInfo,
getContext: element.getContext,
getDomain: element.getDomain,
getFieldNames: element.getFieldNames,
id: element.id,
isDirty: element.isDirty,
limit: element.limit,
model: element.model,
offset: element.offset,
ref: element.ref,
res_ids: element.res_ids.slice(0),
specialData: _.extend({}, element.specialData),
type: 'record',
viewType: element.viewType,
};
if (!this.isNew(element.id)) {
record.res_id = element.res_id;
}
var evalContext;
Object.defineProperty(record, 'evalContext', {
get: function () {
evalContext = evalContext || self._getEvalContext(element);
return evalContext;
},
});
return record;
}
// apply potential changes (only for x2many lists)
element = this._applyX2ManyOperations(element);
this._sortList(element);
if (!element.orderedResIDs && element._changes) {
_.each(element._changes, function (change) {
if (change.operation === 'ADD' && change.isNew) {
element.data = _.without(element.data, change.id);
if (change.position === 'top') {
element.data.unshift(change.id);
} else {
element.data.push(change.id);
}
}
});
}
var list = {
aggregateValues: _.extend({}, element.aggregateValues),
context: _.extend({}, element.context),
count: element.count,
data: _.map(element.data, function (elemID) {
return self.get(elemID, options);
}),
domain: element.domain.slice(0),
fields: element.fields,
getContext: element.getContext,
getDomain: element.getDomain,
getFieldNames: element.getFieldNames,
groupedBy: element.groupedBy,
groupsCount: element.groupsCount,
groupsLimit: element.groupsLimit,
groupsOffset: element.groupsOffset,
id: element.id,
isDirty: element.isDirty,
isOpen: element.isOpen,
limit: element.limit,
model: element.model,
offset: element.offset,
orderedBy: element.orderedBy,
res_id: element.res_id,
res_ids: element.res_ids.slice(0),
type: 'list',
value: element.value,
viewType: element.viewType,
};
if (element.fieldsInfo) {
list.fieldsInfo = element.fieldsInfo;
}
return list;
},
/**
* Returns the current display_name for the record.
*
* @param {string} id the localID for a valid record element
* @returns {string}
*/
getName: function (id) {
var record = this.localData[id];
if (record._changes && 'display_name' in record._changes) {
return record._changes.display_name;
}
if ('display_name' in record.data) {
return record.data.display_name;
}
return _t("New");
},
/**
* Returns true if a record is dirty. A record is considered dirty if it has
* some unsaved changes, marked by the _isDirty property on the record or
* one of its subrecords.
*
* @param {string} id - the local resource id
* @returns {boolean}
*/
isDirty: function (id) {
var isDirty = false;
this._visitChildren(this.localData[id], function (r) {
if (r._isDirty) {
isDirty = true;
}
});
return isDirty;
},
/**
* Check if a localData is new, meaning if it is in the process of being
* created and no actual record exists in db. Note: if the localData is not
* of the "record" type, then it is always considered as not new.
*
* Note: A virtual id is a character string composed of an integer and has
* a dash and other information.
* E.g: in calendar, the recursive event have virtual id linked to a real id
* virtual event id "23-20170418020000" is linked to the event id 23
*
* @param {string} id id for a local resource
* @returns {boolean}
*/
isNew: function (id) {
var data = this.localData[id];
if (data.type !== "record") {
return false;
}
var res_id = data.res_id;
if (typeof res_id === 'number') {
return false;
} else if (typeof res_id === 'string' && /^[0-9]+-/.test(res_id)) {
return false;
}
return true;
},
/**
* Main entry point, the goal of this method is to fetch and process all
* data (following relations if necessary) for a given record/list.
*
* @todo document all params
*
* @param {any} params
* @param {Object} [params.fieldsInfo={}] contains the fieldInfo of each field
* @param {Object} params.fields contains the description of each field
* @param {string} [params.type] 'record' or 'list'
* @param {string} [params.recordID] an ID for an existing resource.
* @returns {Promise<string>} resolves to a local id, or handle
*/
load: function (params) {
params.type = params.type || (params.res_id !== undefined ? 'record' : 'list');
// FIXME: the following seems only to be used by the basic_model_tests
// so it should probably be removed and the tests should be adapted
params.viewType = params.viewType || 'default';
if (!params.fieldsInfo) {
var fieldsInfo = {};
for (var fieldName in params.fieldNames) {
fieldsInfo[params.fieldNames[fieldName]] = {};
}
params.fieldsInfo = {};
params.fieldsInfo[params.viewType] = fieldsInfo;
}
if (params.type === 'record' && params.res_id === undefined) {
params.allowWarning = true;
return this._makeDefaultRecord(params.modelName, params);
}
var dataPoint = this._makeDataPoint(params);
return this._load(dataPoint).then(function () {
return dataPoint.id;
});
},
/**
* This helper method is designed to help developpers that want to use a
* field widget outside of a view. In that case, we want a way to create
* data without actually performing a fetch.
*
* @param {string} model name of the model
* @param {Object[]} fields a description of field properties
* @param {Object} [fieldInfo] various field info that we want to set
* @returns {Promise<string>} the local id for the created resource
*/
makeRecord: function (model, fields, fieldInfo) {
var self = this;
var defs = [];
var record_fields = {};
_.each(fields, function (field) {
record_fields[field.name] = _.pick(field, 'type', 'relation', 'domain');
});
fieldInfo = fieldInfo || {};
var fieldsInfo = {};
fieldsInfo.default = {};
_.each(fields, function (field) {
fieldsInfo.default[field.name] = fieldInfo[field.name] || {};
});
var record = this._makeDataPoint({
modelName: model,
fields: record_fields,
fieldsInfo: fieldsInfo,
viewType: 'default',
});
_.each(fields, function (field) {
var dataPoint;
if (field.type === 'many2one') {
if (field.value) {
var id = _.isArray(field.value) ? field.value[0] : field.value;
var display_name = _.isArray(field.value) ? field.value[1] : undefined;
dataPoint = self._makeDataPoint({
modelName: field.relation,
data: {
id: id,
display_name: display_name,
},
parentID: record.id,
});
record.data[field.name] = dataPoint.id;
if (display_name === undefined) {
defs.push(self._fetchNameGet(dataPoint));
}
}
} else if (field.type === 'one2many' || field.type === 'many2many') {
var relatedFieldsInfo = {};
relatedFieldsInfo.default = {};
_.each(field.fields, function (field) {
relatedFieldsInfo.default[field.name] = {};
});
var dpParams = {
fieldsInfo: relatedFieldsInfo,
modelName: field.relation,
parentID: record.id,
static: true,
type: 'list',
viewType: 'default',
};
var needLoad = false;
// As value, you could either pass:
// - a list of ids related to the record
// - a list of object
// We only need to load the datapoint in the first case.
if (field.value && field.value.length) {
if (_.isObject(field.value[0])) {
dpParams.res_ids = _.pluck(field.value, 'id');
dataPoint = self._makeDataPoint(dpParams);
_.each(field.value, function (data) {
var recordDP = self._makeDataPoint({
data: data,
modelName: field.relation,
parentID: dataPoint.id,
type: 'record',
});
dataPoint.data.push(recordDP.id);
dataPoint._cache[recordDP.res_id] = recordDP.id;
});
} else {
dpParams.res_ids = field.value;
dataPoint = self._makeDataPoint(dpParams);
needLoad = true;
}
} else {
dpParams.res_ids = [];
dataPoint = self._makeDataPoint(dpParams);
}
if (needLoad) {
defs.push(self._load(dataPoint));
}
record.data[field.name] = dataPoint.id;
} else if (field.value) {
record.data[field.name] = field.value;
}
});
return Promise.all(defs).then(function () {
return record.id;
});
},
/**
* This is an extremely important method. All changes in any field go
* through this method. It will then apply them in the local state, check
* if onchanges needs to be applied, actually do them if necessary, then
* resolves with the list of changed fields.
*
* @param {string} record_id
* @param {Object} changes a map field => new value
* @param {Object} [options] will be transferred to the applyChange method
* @see _applyChange
* @returns {Promise<string[]>} list of changed fields
*/
notifyChanges: function (record_id, changes, options) {
return this.mutex.exec(this._applyChange.bind(this, record_id, changes, options));
},
/**
* Reload all data for a given resource. At any time there is at most one
* reload operation active.
*
* @param {string} id local id for a resource
* @param {Object} [options]
* @param {boolean} [options.keepChanges=false] if true, doesn't discard the
* changes on the record before reloading it
* @returns {Promise<string>} resolves to the id of the resource
*/
reload: function (id, options) {
return this.mutex.exec(this._reload.bind(this, id, options));
},
/**
* In some case, we may need to remove an element from a list, without going
* through the notifyChanges machinery. The motivation for this is when the
* user click on 'Add a line' in a field one2many with a required field,
* then clicks somewhere else. The new line need to be discarded, but we
* don't want to trigger a real notifyChanges (no need for that, and also,
* we don't want to rerender the UI).
*
* @param {string} elementID some valid element id. It is necessary that the
* corresponding element has a parent.
*/
removeLine: function (elementID) {
var record = this.localData[elementID];
var parent = this.localData[record.parentID];
if (parent.static) {
// x2Many case: the new record has been stored in _changes, as a
// command so we remove the command(s) related to that record
parent._changes = _.filter(parent._changes, function (change) {
if (change.id === elementID &&
change.operation === 'ADD' && // For now, only an ADD command increases limits
parent.tempLimitIncrement) {
// The record will be deleted from the _changes.
// So we won't be passing into the logic of _applyX2ManyOperations anymore
// implying that we have to cancel out the effects of an ADD command here
parent.tempLimitIncrement--;
parent.limit--;
}
return change.id !== elementID;
});
} else {
// main list view case: the new record is in data
parent.data = _.without(parent.data, elementID);
parent.count--;
}
},
/**
* Resequences records.
*
* @param {string} modelName the resIDs model
* @param {Array<integer>} resIDs the new sequence of ids
* @param {string} parentID the localID of the parent
* @param {object} [options]
* @param {integer} [options.offset]
* @param {string} [options.field] the field name used as sequence
* @returns {Promise<string>} resolves to the local id of the parent
*/
resequence: function (modelName, resIDs, parentID, options) {
options = options || {};
if ((resIDs.length <= 1)) {
return Promise.resolve(parentID); // there is nothing to sort
}
var self = this;
var data = this.localData[parentID];
var params = {
model: modelName,
ids: resIDs,
};
if (options.offset) {
params.offset = options.offset;
}
if (options.field) {
params.field = options.field;
}
return this._rpc({
route: '/web/dataset/resequence',
params: params,
})
.then(function (wasResequenced) {
if (!wasResequenced) {
// the field on which the resequence was triggered does not
// exist, so no resequence happened server-side
return Promise.resolve();
}
var field = params.field ? params.field : 'sequence';
return self._rpc({
model: modelName,
method: 'read',
args: [resIDs, [field]],
}).then(function (records) {
if (data.data.length) {
var dataType = self.localData[data.data[0]].type;
if (dataType === 'record') {
_.each(data.data, function (dataPoint) {
var recordData = self.localData[dataPoint].data;
var inRecords = _.findWhere(records, {id: recordData.id});
if (inRecords) {
recordData[field] = inRecords[field];
}
});
data.data = _.sortBy(data.data, function (d) {
return self.localData[d].data[field];
});
}
if (dataType === 'list') {
data.data = _.sortBy(data.data, function (d) {
return _.indexOf(resIDs, self.localData[d].res_id)
});
}
}
data.res_ids = [];
_.each(data.data, function (d) {
var dataPoint = self.localData[d];
if (dataPoint.type === 'record') {
data.res_ids.push(dataPoint.res_id);
} else {
data.res_ids = data.res_ids.concat(dataPoint.res_ids);
}
});
self._updateParentResIDs(data);
return parentID;
})
});