[IMP] More dataset refactoring
[odoo/odoo.git] / addons / web / static / src / js / data.js
1
2 openerp.web.data = function(openerp) {
3
4 /**
5  * Serializes the sort criterion array of a dataset into a form which can be
6  * consumed by OpenERP's RPC APIs.
7  *
8  * @param {Array} criterion array of fields, from first to last criteria, prefixed with '-' for reverse sorting
9  * @returns {String} SQL-like sorting string (``ORDER BY``) clause
10  */
11 openerp.web.serialize_sort = function (criterion) {
12     return _.map(criterion,
13         function (criteria) {
14             if (criteria[0] === '-') {
15                 return criteria.slice(1) + ' DESC';
16             }
17             return criteria + ' ASC';
18         }).join(', ');
19 };
20
21 openerp.web.DataGroup =  openerp.web.Widget.extend( /** @lends openerp.web.DataGroup# */{
22     /**
23      * Management interface between views and grouped collections of OpenERP
24      * records.
25      *
26      * The root DataGroup is instantiated with the relevant information
27      * (a session, a model, a domain, a context and a group_by sequence), the
28      * domain and context may be empty. It is then interacted with via
29      * :js:func:`~openerp.web.DataGroup.list`, which is used to read the
30      * content of the current grouping level.
31      *
32      * @constructs openerp.web.DataGroup
33      * @extends openerp.web.Widget
34      *
35      * @param {openerp.web.Widget} parent widget
36      * @param {String} model name of the model managed by this DataGroup
37      * @param {Array} domain search domain for this DataGroup
38      * @param {Object} context context of the DataGroup's searches
39      * @param {Array} group_by sequence of fields by which to group
40      * @param {Number} [level=0] nesting level of the group
41      */
42     init: function(parent, model, domain, context, group_by, level) {
43         this._super(parent, null);
44         if (group_by) {
45             if (group_by.length || context['group_by_no_leaf']) {
46                 return new openerp.web.ContainerDataGroup( this, model, domain, context, group_by, level);
47             } else {
48                 return new openerp.web.GrouplessDataGroup( this, model, domain, context, level);
49             }
50         }
51
52         this.model = model;
53         this.context = context;
54         this.domain = domain;
55
56         this.level = level || 0;
57     },
58     cls: 'DataGroup'
59 });
60 openerp.web.ContainerDataGroup = openerp.web.DataGroup.extend( /** @lends openerp.web.ContainerDataGroup# */ {
61     /**
62      *
63      * @constructs openerp.web.ContainerDataGroup
64      * @extends openerp.web.DataGroup
65      *
66      * @param session
67      * @param model
68      * @param domain
69      * @param context
70      * @param group_by
71      * @param level
72      */
73     init: function (parent, model, domain, context, group_by, level) {
74         this._super(parent, model, domain, context, null, level);
75
76         this.group_by = group_by;
77     },
78     /**
79      * The format returned by ``read_group`` is absolutely dreadful:
80      *
81      * * A ``__context`` key provides future grouping levels
82      * * A ``__domain`` key provides the domain for the next search
83      * * The current grouping value is provided through the name of the
84      *   current grouping name e.g. if currently grouping on ``user_id``, then
85      *   the ``user_id`` value for this group will be provided through the
86      *   ``user_id`` key.
87      * * Similarly, the number of items in the group (not necessarily direct)
88      *   is provided via ``${current_field}_count``
89      * * Other aggregate fields are just dumped there
90      *
91      * This function slightly improves the grouping records by:
92      *
93      * * Adding a ``grouped_on`` property providing the current grouping field
94      * * Adding a ``value`` and a ``length`` properties which replace the
95      *   ``$current_field`` and ``${current_field}_count`` ones
96      * * Moving aggregate values into an ``aggregates`` property object
97      *
98      * Context and domain keys remain as-is, they should not be used externally
99      * but in case they're needed...
100      *
101      * @param {Object} group ``read_group`` record
102      */
103     transform_group: function (group) {
104         var field_name = this.group_by[0];
105         // In cases where group_by_no_leaf and no group_by, the result of
106         // read_group has aggregate fields but no __context or __domain.
107         // Create default (empty) values for those so that things don't break
108         var fixed_group = _.extend(
109                 {__context: {group_by: []}, __domain: []},
110                 group);
111
112         var aggregates = {};
113         _(fixed_group).each(function (value, key) {
114             if (key.indexOf('__') === 0
115                     || key === field_name
116                     || key === field_name + '_count') {
117                 return;
118             }
119             aggregates[key] = value || 0;
120         });
121
122         var group_size = fixed_group[field_name + '_count'] || fixed_group.__count || 0;
123         var leaf_group = fixed_group.__context.group_by.length === 0;
124         return {
125             __context: fixed_group.__context,
126             __domain: fixed_group.__domain,
127
128             grouped_on: field_name,
129             // if terminal group (or no group) and group_by_no_leaf => use group.__count
130             length: group_size,
131             value: fixed_group[field_name],
132             // A group is openable if it's not a leaf in group_by_no_leaf mode
133             openable: !(leaf_group && this.context['group_by_no_leaf']),
134
135             aggregates: aggregates
136         };
137     },
138     fetch: function (fields) {
139         // internal method
140         var d = new $.Deferred();
141         var self = this;
142
143         this.rpc('/web/group/read', {
144             model: this.model,
145             context: this.context,
146             domain: this.domain,
147             fields: _.uniq(this.group_by.concat(fields)),
148             group_by_fields: this.group_by,
149             sort: openerp.web.serialize_sort(this.sort)
150         }, function () { }).then(function (response) {
151             var data_groups = _(response).map(
152                     _.bind(self.transform_group, self));
153             self.groups = data_groups;
154             d.resolveWith(self, [data_groups]);
155         }, function () {
156             d.rejectWith.apply(d, [self, arguments]);
157         });
158         return d.promise();
159     },
160     /**
161      * The items of a list have the following properties:
162      *
163      * ``length``
164      *     the number of records contained in the group (and all of its
165      *     sub-groups). This does *not* provide the size of the "next level"
166      *     of the group, unless the group is terminal (no more groups within
167      *     it).
168      * ``grouped_on``
169      *     the name of the field this level was grouped on, this is mostly
170      *     used for display purposes, in order to know the name of the current
171      *     level of grouping. The ``grouped_on`` should be the same for all
172      *     objects of the list.
173      * ``value``
174      *     the value which led to this group (this is the value all contained
175      *     records have for the current ``grouped_on`` field name).
176      * ``aggregates``
177      *     a mapping of other aggregation fields provided by ``read_group``
178      *
179      * @param {Array} fields the list of fields to aggregate in each group, can be empty
180      * @param {Function} ifGroups function executed if any group is found (DataGroup.group_by is non-null and non-empty), called with a (potentially empty) list of groups as parameters.
181      * @param {Function} ifRecords function executed if there is no grouping left to perform, called with a DataSet instance as parameter
182      */
183     list: function (fields, ifGroups, ifRecords) {
184         var self = this;
185         this.fetch(fields).then(function (group_records) {
186             ifGroups(_(group_records).map(function (group) {
187                 var child_context = _.extend({}, self.context, group.__context);
188                 return _.extend(
189                     new openerp.web.DataGroup(
190                         self, self.model, group.__domain,
191                         child_context, child_context.group_by,
192                         self.level + 1),
193                     group, {sort: self.sort});
194             }));
195         });
196     }
197 });
198 openerp.web.GrouplessDataGroup = openerp.web.DataGroup.extend( /** @lends openerp.web.GrouplessDataGroup# */ {
199     /**
200      *
201      * @constructs openerp.web.GrouplessDataGroup
202      * @extends openerp.web.DataGroup
203      *
204      * @param session
205      * @param model
206      * @param domain
207      * @param context
208      * @param level
209      */
210     init: function (parent, model, domain, context, level) {
211         this._super(parent, model, domain, context, null, level);
212     },
213     list: function (fields, ifGroups, ifRecords) {
214         ifRecords(_.extend(
215             new openerp.web.DataSetSearch(this, this.model),
216             {domain: this.domain, context: this.context, _sort: this.sort}));
217     }
218 });
219 openerp.web.StaticDataGroup = openerp.web.GrouplessDataGroup.extend( /** @lends openerp.web.StaticDataGroup# */ {
220     /**
221      * A specialization of groupless data groups, relying on a single static
222      * dataset as its records provider.
223      *
224      * @constructs openerp.web.StaticDataGroup
225      * @extends openerp.web.GrouplessDataGroup
226      * @param {openep.web.DataSetStatic} dataset a static dataset backing the groups
227      */
228     init: function (dataset) {
229         this.dataset = dataset;
230     },
231     list: function (fields, ifGroups, ifRecords) {
232         ifRecords(this.dataset);
233     }
234 });
235
236 openerp.web.DataSet =  openerp.web.Widget.extend( /** @lends openerp.web.DataSet# */{
237     identifier_prefix: "dataset",
238     /**
239      * DateaManagement interface between views and the collection of selected
240      * OpenERP records (represents the view's state?)
241      *
242      * @constructs openerp.web.DataSet
243      * @extends openerp.web.Widget
244      *
245      * @param {String} model the OpenERP model this dataset will manage
246      */
247     init: function(parent, model, context) {
248         this._super(parent);
249         this.model = model;
250         this.context = context || {};
251         this.index = null;
252     },
253     previous: function () {
254         this.index -= 1;
255         if (!this.ids.length) {
256             this.index = null;
257         } else if (this.index < 0) {
258             this.index = this.ids.length - 1;
259         }
260         return this;
261     },
262     next: function () {
263         this.index += 1;
264         if (!this.ids.length) {
265             this.index = null;
266         } else if (this.index >= this.ids.length) {
267             this.index = 0;
268         }
269         return this;
270     },
271     select_id: function(id) {
272         var idx = this.get_id_index(id);
273         if (idx === null) {
274             return false;
275         } else {
276             this.index = idx;
277             return true;
278         }
279     },
280     get_id_index: function(id) {
281         for (var i=0, ii=this.ids.length; i<ii; i++) {
282             // Here we use type coercion because of the mess potentially caused by
283             // OpenERP ids fetched from the DOM as string. (eg: dhtmlxcalendar)
284             // OpenERP ids can be non-numeric too ! (eg: recursive events in calendar)
285             if (id == this.ids[i]) {
286                 return i;
287             }
288         }
289         return null;
290     },
291     /**
292      * Read records.
293      *
294      * @param {Array} ids identifiers of the records to read
295      * @param {Array} fields fields to read and return, by default all fields are returned
296      * @returns {$.Deferred}
297      */
298     read_ids: function (ids, fields, options) {
299         var options = options || {};
300         return this.rpc('/web/dataset/get', {
301             model: this.model,
302             ids: ids,
303             fields: fields,
304             context: this.get_context(options.context)
305         });
306     },
307     /**
308      * Read a slice of the records represented by this DataSet, based on its
309      * domain and context.
310      *
311      * @param {Array} [fields] fields to read and return, by default all fields are returned
312      * @params {Object} options
313      * @param {Number} [options.offset=0] The index from which selected records should be returned
314      * @param {Number} [options.limit=null] The maximum number of records to return
315      * @returns {$.Deferred}
316      */
317     read_slice: function (fields, options) {
318         return null;
319     },
320     /**
321      * Reads the current dataset record (from its index)
322      *
323      * @params {Array} [fields] fields to read and return, by default all fields are returned
324      * @param {Object} [options.context] context data to add to the request payload, on top of the DataSet's own context
325      * @returns {$.Deferred}
326      */
327     read_index: function (fields, options) {
328         var def = $.Deferred();
329         if (_.isEmpty(this.ids)) {
330             def.reject();
331         } else {
332             fields = fields || false;
333             this.read_ids([this.ids[this.index]], fields, options).then(function(records) {
334                 def.resolve(records[0]);
335             }, function() {
336                 def.reject.apply(def, arguments);
337             });
338         }
339         return def.promise();
340     },
341     /**
342      * Reads default values for the current model
343      *
344      * @param {Array} [fields] fields to get default values for, by default all defaults are read
345      * @param {Object} [options.context] context data to add to the request payload, on top of the DataSet's own context
346      * @returns {$.Deferred}
347      */
348     default_get: function(fields, options) {
349         var options = options || {};
350         return this.rpc('/web/dataset/default_get', {
351             model: this.model,
352             fields: fields,
353             context: this.get_context(options.context)
354         });
355     },
356     /**
357      * Creates a new record in db
358      *
359      * @param {Object} data field values to set on the new record
360      * @param {Function} callback function called with operation result
361      * @param {Function} error_callback function called in case of creation error
362      * @returns {$.Deferred}
363      */
364     create: function(data, callback, error_callback) {
365         return this.rpc('/web/dataset/create', {
366             model: this.model,
367             data: data,
368             context: this.get_context()
369         }, callback, error_callback);
370     },
371     /**
372      * Saves the provided data in an existing db record
373      *
374      * @param {Number|String} id identifier for the record to alter
375      * @param {Object} data field values to write into the record
376      * @param {Function} callback function called with operation result
377      * @param {Function} error_callback function called in case of write error
378      * @returns {$.Deferred}
379      */
380     write: function (id, data, options, callback, error_callback) {
381         options = options || {};
382         return this.rpc('/web/dataset/save', {
383             model: this.model,
384             id: id,
385             data: data,
386             context: this.get_context(options.context)
387         }, callback, error_callback);
388     },
389     /**
390      * Deletes an existing record from the database
391      *
392      * @param {Number|String} ids identifier of the record to delete
393      * @param {Function} callback function called with operation result
394      * @param {Function} error_callback function called in case of deletion error
395      */
396     unlink: function(ids, callback, error_callback) {
397         var self = this;
398         return this.call_and_eval("unlink", [ids, this.get_context()], null, 1,
399             callback, error_callback);
400     },
401     /**
402      * Calls an arbitrary RPC method
403      *
404      * @param {String} method name of the method (on the current model) to call
405      * @param {Array} [args] arguments to pass to the method
406      * @param {Function} callback
407      * @param {Function} error_callback
408      * @returns {$.Deferred}
409      */
410     call: function (method, args, callback, error_callback) {
411         return this.rpc('/web/dataset/call', {
412             model: this.model,
413             method: method,
414             args: args || []
415         }, callback, error_callback);
416     },
417     /**
418      * Calls an arbitrary method, with more crazy
419      *
420      * @param {String} method
421      * @param {Array} [args]
422      * @param {Number} [domain_index] index of a domain to evaluate in the args array
423      * @param {Number} [context_index] index of a context to evaluate in the args array
424      * @param {Function} callback
425      * @param {Function }error_callback
426      * @returns {$.Deferred}
427      */
428     call_and_eval: function (method, args, domain_index, context_index, callback, error_callback) {
429         return this.rpc('/web/dataset/call', {
430             model: this.model,
431             method: method,
432             domain_id: domain_index == undefined ? null : domain_index,
433             context_id: context_index == undefined ? null : context_index,
434             args: args || []
435         }, callback, error_callback);
436     },
437     /**
438      * Calls a button method, usually returning some sort of action
439      *
440      * @param {String} method
441      * @param {Array} [args]
442      * @param {Function} callback
443      * @param {Function} error_callback
444      * @returns {$.Deferred}
445      */
446     call_button: function (method, args, callback, error_callback) {
447         return this.rpc('/web/dataset/call_button', {
448             model: this.model,
449             method: method,
450             domain_id: null,
451             context_id: args.length - 1,
452             args: args || []
453         }, callback, error_callback);
454     },
455     /**
456      * Fetches the "readable name" for records, based on intrinsic rules
457      *
458      * @param {Array} ids
459      * @param {Function} callback
460      * @returns {$.Deferred}
461      */
462     name_get: function(ids, callback) {
463         return this.call_and_eval('name_get', [ids, this.get_context()], null, 1, callback);
464     },
465     /**
466      * 
467      * @param {String} name name to perform a search for/on
468      * @param {Array} [domain=[]] filters for the objects returned, OpenERP domain
469      * @param {String} [operator='ilike'] matching operator to use with the provided name value
470      * @param {Number} [limit=100] maximum number of matches to return
471      * @param {Function} callback function to call with name_search result
472      * @returns {$.Deferred}
473      */
474     name_search: function (name, domain, operator, limit, callback) {
475         return this.call_and_eval('name_search',
476             [name || '', domain || false, operator || 'ilike', this.get_context(), limit || 100],
477             1, 3, callback);
478     },
479     /**
480      * @param name
481      * @param callback
482      */
483     name_create: function(name, callback) {
484         return this.call_and_eval('name_create', [name, this.get_context()], null, 1, callback);
485     },
486     exec_workflow: function (id, signal, callback) {
487         return this.rpc('/web/dataset/exec_workflow', {
488             model: this.model,
489             id: id,
490             signal: signal
491         }, callback);
492     },
493     get_context: function(request_context) {
494         if (request_context) {
495             return new openerp.web.CompoundContext(this.context, request_context);
496         }
497         return this.context;
498     }
499 });
500 openerp.web.DataSetStatic =  openerp.web.DataSet.extend({
501     init: function(parent, model, context, ids) {
502         this._super(parent, model, context);
503         // all local records
504         this.ids = ids || [];
505     },
506     read_slice: function (fields, options) {
507         // TODO remove fields from options
508         var self = this,
509             offset = options.offset || 0,
510             limit = options.limit || false,
511             fields = fields || false;
512         var end_pos = limit && limit !== -1 ? offset + limit : this.ids.length;
513         return this.read_ids(this.ids.slice(offset, end_pos), fields);
514     },
515     set_ids: function (ids) {
516         this.ids = ids;
517         if (ids.length === 0) {
518             this.index = null;
519         } else if (this.index >= ids.length - 1) {
520             this.index = ids.length - 1;
521         }
522     },
523     unlink: function(ids) {
524         this.on_unlink(ids);
525         return $.Deferred().resolve({result: true});
526     },
527     on_unlink: function(ids) {
528         this.set_ids(_.without.apply(null, [this.ids].concat(ids)));
529     }
530 });
531 openerp.web.DataSetSearch =  openerp.web.DataSet.extend(/** @lends openerp.web.DataSetSearch */{
532     /**
533      * @constructs openerp.web.DataSetSearch
534      * @extends openerp.web.DataSet
535      *
536      * @param {Object} parent
537      * @param {String} model
538      * @param {Object} context
539      * @param {Array} domain
540      */
541     init: function(parent, model, context, domain) {
542         this._super(parent, model, context);
543         this.domain = domain || [];
544         this._sort = [];
545         this.offset = 0;
546         // subset records[offset:offset+limit]
547         // is it necessary ?
548         this.ids = [];
549     },
550     /**
551      * Read a slice of the records represented by this DataSet, based on its
552      * domain and context.
553      *
554      * @params {Object} options
555      * @param {Array} [options.fields] fields to read and return, by default all fields are returned
556      * @param {Object} [options.context] context data to add to the request payload, on top of the DataSet's own context
557      * @param {Array} [options.domain] domain data to add to the request payload, ANDed with the dataset's domain
558      * @param {Number} [options.offset=0] The index from which selected records should be returned
559      * @param {Number} [options.limit=null] The maximum number of records to return
560      * @returns {$.Deferred}
561      */
562     read_slice: function (fields, options) {
563         var self = this;
564         var options = options || {};
565         var offset = options.offset || 0;
566         return this.rpc('/web/dataset/search_read', {
567             model: this.model,
568             fields: fields || false,
569             domain: this.get_domain(options.domain),
570             context: this.get_context(options.context),
571             sort: this.sort(),
572             offset: offset,
573             limit: options.limit || false
574         }).pipe(function (result) {
575             self.ids = result.ids;
576             self.offset = offset;
577             return result.records;
578         });
579     },
580     get_domain: function (other_domain) {
581         if (other_domain) {
582             return new openerp.web.CompoundDomain(this.domain, other_domain);
583         }
584         return this.domain;
585     },
586     /**
587      * Reads or changes sort criteria on the dataset.
588      *
589      * If not provided with any argument, serializes the sort criteria to
590      * an SQL-like form usable by OpenERP's ORM.
591      *
592      * If given a field, will set that field as first sorting criteria or,
593      * if the field is already the first sorting criteria, will reverse it.
594      *
595      * @param {String} [field] field to sort on, reverses it (toggle from ASC to DESC) if already the main sort criteria
596      * @param {Boolean} [force_reverse=false] forces inserting the field as DESC
597      * @returns {String|undefined}
598      */
599     sort: function (field, force_reverse) {
600         if (!field) {
601             return openerp.web.serialize_sort(this._sort);
602         }
603         var reverse = force_reverse || (this._sort[0] === field);
604         this._sort.splice.apply(
605             this._sort, [0, this._sort.length].concat(
606                 _.without(this._sort, field, '-' + field)));
607
608         this._sort.unshift((reverse ? '-' : '') + field);
609         return undefined;
610     },
611     unlink: function(ids, callback, error_callback) {
612         var self = this;
613         return this._super(ids, function(result) {
614             self.ids = _.without.apply(_, [self.ids].concat(ids));
615             if (this.index !== null) {
616                 self.index = self.index <= self.ids.length - 1 ?
617                     self.index : (self.ids.length > 0 ? self.ids.length -1 : 0);
618             }
619             if (callback)
620                 callback(result);
621         }, error_callback);
622     }
623 });
624 openerp.web.BufferedDataSet = openerp.web.DataSetStatic.extend({
625     virtual_id_prefix: "one2many_v_id_",
626     debug_mode: true,
627     init: function() {
628         this._super.apply(this, arguments);
629         this.reset_ids([]);
630         this.last_default_get = {};
631     },
632     default_get: function(fields, callback) {
633         return this._super(fields).then(this.on_default_get).then(callback);
634     },
635     on_default_get: function(res) {
636         this.last_default_get = res;
637     },
638     create: function(data, callback, error_callback) {
639         var cached = {id:_.uniqueId(this.virtual_id_prefix), values: data,
640             defaults: this.last_default_get};
641         this.to_create.push(_.extend(_.clone(cached), {values: _.clone(cached.values)}));
642         this.cache.push(cached);
643         this.on_change();
644         var prom = $.Deferred().then(callback);
645         prom.resolve({result: cached.id});
646         return prom.promise();
647     },
648     write: function (id, data, options, callback) {
649         var self = this;
650         var record = _.detect(this.to_create, function(x) {return x.id === id;});
651         record = record || _.detect(this.to_write, function(x) {return x.id === id;});
652         var dirty = false;
653         if (record) {
654             for (var k in data) {
655                 if (record.values[k] === undefined || record.values[k] !== data[k]) {
656                     dirty = true;
657                     break;
658                 }
659             }
660             $.extend(record.values, data);
661         } else {
662             dirty = true;
663             record = {id: id, values: data};
664             self.to_write.push(record);
665         }
666         var cached = _.detect(this.cache, function(x) {return x.id === id;});
667         if (!cached) {
668             cached = {id: id, values: {}};
669             this.cache.push(cached);
670         }
671         $.extend(cached.values, record.values);
672         if (dirty)
673             this.on_change();
674         var to_return = $.Deferred().then(callback);
675         to_return.resolve({result: true});
676         return to_return.promise();
677     },
678     unlink: function(ids, callback, error_callback) {
679         var self = this;
680         _.each(ids, function(id) {
681             if (! _.detect(self.to_create, function(x) { return x.id === id; })) {
682                 self.to_delete.push({id: id})
683             }
684         });
685         this.to_create = _.reject(this.to_create, function(x) { return _.include(ids, x.id);});
686         this.to_write = _.reject(this.to_write, function(x) { return _.include(ids, x.id);});
687         this.cache = _.reject(this.cache, function(x) { return _.include(ids, x.id);});
688         this.set_ids(_.without.apply(_, [this.ids].concat(ids)));
689         this.on_change();
690         return $.async_when({result: true}).then(callback);
691     },
692     reset_ids: function(ids) {
693         this.set_ids(ids);
694         this.to_delete = [];
695         this.to_create = [];
696         this.to_write = [];
697         this.cache = [];
698         this.delete_all = false;
699     },
700     on_change: function() {},
701     read_ids: function (ids, fields) {
702         var self = this;
703         var to_get = [];
704         _.each(ids, function(id) {
705             var cached = _.detect(self.cache, function(x) {return x.id === id;});
706             var created = _.detect(self.to_create, function(x) {return x.id === id;});
707             if (created) {
708                 _.each(fields, function(x) {if (cached.values[x] === undefined)
709                     cached.values[x] = created.defaults[x] || false;});
710             } else {
711                 if (!cached || !_.all(fields, function(x) {return cached.values[x] !== undefined}))
712                     to_get.push(id);
713             }
714         });
715         var completion = $.Deferred();
716         var return_records = function() {
717             var records = _.map(ids, function(id) {
718                 return _.extend({}, _.detect(self.cache, function(c) {return c.id === id;}).values, {"id": id});
719             });
720             if (self.debug_mode) {
721                 if (_.include(records, undefined)) {
722                     throw "Record not correctly loaded";
723                 }
724             }
725             completion.resolve(records);
726         };
727         if(to_get.length > 0) {
728             var rpc_promise = this._super(to_get, fields, function(records) {
729                 _.each(records, function(record, index) {
730                     var id = to_get[index];
731                     var cached = _.detect(self.cache, function(x) {return x.id === id;});
732                     if (!cached) {
733                         self.cache.push({id: id, values: record});
734                     } else {
735                         // I assume cache value is prioritary
736                         _.defaults(cached.values, record);
737                     }
738                 });
739                 return_records();
740             });
741             $.when(rpc_promise).fail(function() {completion.reject();});
742         } else {
743             return_records();
744         }
745         return completion.promise();
746     },
747     call_button: function (method, args, callback, error_callback) {
748         var id = args[0][0], index;
749         for(var i=0, len=this.cache.length; i<len; ++i) {
750             var record = this.cache[i];
751             // if record we call the button upon is in the cache
752             if (record.id === id) {
753                 // evict it so it gets reloaded from server
754                 this.cache.splice(i, 1);
755                 break;
756             }
757         }
758         return this._super(method, args, callback, error_callback);
759     }
760 });
761 openerp.web.BufferedDataSet.virtual_id_regex = /^one2many_v_id_.*$/;
762
763 openerp.web.ProxyDataSet = openerp.web.DataSetSearch.extend({
764     init: function() {
765         this._super.apply(this, arguments);
766         this.create_function = null;
767         this.write_function = null;
768         this.read_function = null;
769     },
770     read_ids: function () {
771         if (this.read_function) {
772             return this.read_function.apply(null, arguments);
773         } else {
774             return this._super.apply(this, arguments);
775         }
776     },
777     default_get: function(fields, callback) {
778         return this._super(fields, callback).then(this.on_default_get);
779     },
780     on_default_get: function(result) {},
781     create: function(data, callback, error_callback) {
782         this.on_create(data);
783         if (this.create_function) {
784             return this.create_function(data, callback, error_callback);
785         } else {
786             console.warn("trying to create a record using default proxy dataset behavior");
787             return $.async_when({"result": undefined}).then(callback);
788         }
789     },
790     on_create: function(data) {},
791     write: function (id, data, options, callback) {
792         this.on_write(id, data);
793         if (this.write_function) {
794             return this.write_function(id, data, options, callback);
795         } else {
796             console.warn("trying to write a record using default proxy dataset behavior");
797             return $.async_when({"result": true}).then(callback);
798         }
799     },
800     on_write: function(id, data) {},
801     unlink: function(ids, callback, error_callback) {
802         this.on_unlink(ids);
803         console.warn("trying to unlink a record using default proxy dataset behavior");
804         return $.async_when({"result": true}).then(callback);
805     },
806     on_unlink: function(ids) {}
807 });
808
809 openerp.web.Model = openerp.web.CallbackEnabled.extend({
810     init: function(model_name) {
811         this._super();
812         this.model_name = model_name;
813     },
814     rpc: function() {
815         var c = openerp.connection;
816         return c.rpc.apply(c, arguments);
817     },
818     /*
819      * deprecated because it does not allow to specify kwargs, directly use call() instead
820      */
821     get_func: function(method_name) {
822         var self = this;
823         return function() {
824             return self.call(method_name, _.toArray(arguments), {});
825         };
826     },
827     call: function (method, args, kwargs) {
828         return this.rpc('/web/dataset/call_kw', {
829             model: this.model_name,
830             method: method,
831             args: args,
832             kwargs: kwargs,
833         });
834     },
835 });
836
837 openerp.web.CompoundContext = openerp.web.Class.extend({
838     init: function () {
839         this.__ref = "compound_context";
840         this.__contexts = [];
841         this.__eval_context = null;
842         var self = this;
843         _.each(arguments, function(x) {
844             self.add(x);
845         });
846     },
847     add: function (context) {
848         this.__contexts.push(context);
849         return this;
850     },
851     set_eval_context: function (eval_context) {
852         this.__eval_context = eval_context;
853         return this;
854     },
855     get_eval_context: function () {
856         return this.__eval_context;
857     }
858 });
859
860 openerp.web.CompoundDomain = openerp.web.Class.extend({
861     init: function () {
862         this.__ref = "compound_domain";
863         this.__domains = [];
864         this.__eval_context = null;
865         var self = this;
866         _.each(arguments, function(x) {
867             self.add(x);
868         });
869     },
870     add: function(domain) {
871         this.__domains.push(domain);
872         return this;
873     },
874     set_eval_context: function(eval_context) {
875         this.__eval_context = eval_context;
876         return this;
877     },
878     get_eval_context: function() {
879         return this.__eval_context;
880     }
881 });
882 };
883
884 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: