[IMP] mark a bunch of dialog stuff as exportable (mostly buttons, but also dialog...
[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.index < 0) {
256             this.index = this.ids.length - 1;
257         }
258         return this;
259     },
260     next: function () {
261         this.index += 1;
262         if (this.index >= this.ids.length) {
263             this.index = 0;
264         }
265         return this;
266     },
267     select_id: function(id) {
268         var idx = this.get_id_index(id);
269         if (idx === null) {
270             return false;
271         } else {
272             this.index = idx;
273             return true;
274         }
275     },
276     get_id_index: function(id) {
277         for (var i=0, ii=this.ids.length; i<ii; i++) {
278             // Here we use type coercion because of the mess potentially caused by
279             // OpenERP ids fetched from the DOM as string. (eg: dhtmlxcalendar)
280             // OpenERP ids can be non-numeric too ! (eg: recursive events in calendar)
281             if (id == this.ids[i]) {
282                 return i;
283             }
284         }
285         return null;
286     },
287     /**
288      * Read records.
289      *
290      * @param {Array} ids identifiers of the records to read
291      * @param {Array} fields fields to read and return, by default all fields are returned
292      * @param {Function} callback function called with read result
293      * @returns {$.Deferred}
294      */
295     read_ids: function (ids, fields, callback) {
296         return this.rpc('/web/dataset/get', {
297             model: this.model,
298             ids: ids,
299             fields: fields,
300             context: this.get_context()
301         }, callback);
302     },
303     /**
304      * Read a slice of the records represented by this DataSet, based on its
305      * domain and context.
306      *
307      * @param {Array} [fields] fields to read and return, by default all fields are returned
308      * @params {Object} options
309      * @param {Number} [options.offset=0] The index from which selected records should be returned
310      * @param {Number} [options.limit=null] The maximum number of records to return
311      * @param {Function} callback function called with read_slice result
312      * @returns {$.Deferred}
313      */
314     read_slice: function (fields, options, callback) { 
315         return null; 
316     },
317     /**
318      * Reads the current dataset record (from its index)
319      *
320      * @params {Array} [fields] fields to read and return, by default all fields are returned
321      * @params {Function} callback function called with read_index result
322      * @returns {$.Deferred}
323      */
324     read_index: function (fields, callback) {
325         var def = $.Deferred().then(callback);
326         if (_.isEmpty(this.ids)) {
327             def.reject();
328         } else {
329             fields = fields || false;
330             this.read_ids([this.ids[this.index]], fields).then(function(records) {
331                 def.resolve(records[0]);
332             }, function() {
333                 def.reject.apply(def, arguments);
334             });
335         }
336         return def.promise();
337     },
338     /**
339      * Reads default values for the current model
340      *
341      * @param {Array} [fields] fields to get default values for, by default all defaults are read
342      * @param {Function} callback function called with default_get result
343      * @returns {$.Deferred}
344      */
345     default_get: function(fields, callback) {
346         return this.rpc('/web/dataset/default_get', {
347             model: this.model,
348             fields: fields,
349             context: this.get_context()
350         }, callback);
351     },
352     /**
353      * Creates a new record in db
354      *
355      * @param {Object} data field values to set on the new record
356      * @param {Function} callback function called with operation result
357      * @param {Function} error_callback function called in case of creation error
358      * @returns {$.Deferred}
359      */
360     create: function(data, callback, error_callback) {
361         return this.rpc('/web/dataset/create', {
362             model: this.model,
363             data: data,
364             context: this.get_context()
365         }, callback, error_callback);
366     },
367     /**
368      * Saves the provided data in an existing db record
369      *
370      * @param {Number|String} id identifier for the record to alter
371      * @param {Object} data field values to write into the record
372      * @param {Function} callback function called with operation result
373      * @param {Function} error_callback function called in case of write error
374      * @returns {$.Deferred}
375      */
376     write: function (id, data, options, callback, error_callback) {
377         options = options || {};
378         return this.rpc('/web/dataset/save', {
379             model: this.model,
380             id: id,
381             data: data,
382             context: this.get_context(options.context)
383         }, callback, error_callback);
384     },
385     /**
386      * Deletes an existing record from the database
387      *
388      * @param {Number|String} ids identifier of the record to delete
389      * @param {Function} callback function called with operation result
390      * @param {Function} error_callback function called in case of deletion error
391      */
392     unlink: function(ids, callback, error_callback) {
393         var self = this;
394         return this.call_and_eval("unlink", [ids, this.get_context()], null, 1,
395             callback, error_callback);
396     },
397     /**
398      * Calls an arbitrary RPC method
399      *
400      * @param {String} method name of the method (on the current model) to call
401      * @param {Array} [args] arguments to pass to the method
402      * @param {Function} callback
403      * @param {Function} error_callback
404      * @returns {$.Deferred}
405      */
406     call: function (method, args, callback, error_callback) {
407         return this.rpc('/web/dataset/call', {
408             model: this.model,
409             method: method,
410             args: args || []
411         }, callback, error_callback);
412     },
413     /**
414      * Calls an arbitrary method, with more crazy
415      *
416      * @param {String} method
417      * @param {Array} [args]
418      * @param {Number} [domain_index] index of a domain to evaluate in the args array
419      * @param {Number} [context_index] index of a context to evaluate in the args array
420      * @param {Function} callback
421      * @param {Function }error_callback
422      * @returns {$.Deferred}
423      */
424     call_and_eval: function (method, args, domain_index, context_index, callback, error_callback) {
425         return this.rpc('/web/dataset/call', {
426             model: this.model,
427             method: method,
428             domain_id: domain_index == undefined ? null : domain_index,
429             context_id: context_index == undefined ? null : context_index,
430             args: args || []
431         }, callback, error_callback);
432     },
433     /**
434      * Calls a button method, usually returning some sort of action
435      *
436      * @param {String} method
437      * @param {Array} [args]
438      * @param {Function} callback
439      * @param {Function} error_callback
440      * @returns {$.Deferred}
441      */
442     call_button: function (method, args, callback, error_callback) {
443         return this.rpc('/web/dataset/call_button', {
444             model: this.model,
445             method: method,
446             domain_id: null,
447             context_id: args.length - 1,
448             args: args || []
449         }, callback, error_callback);
450     },
451     /**
452      * Fetches the "readable name" for records, based on intrinsic rules
453      *
454      * @param {Array} ids
455      * @param {Function} callback
456      * @returns {$.Deferred}
457      */
458     name_get: function(ids, callback) {
459         return this.call_and_eval('name_get', [ids, this.get_context()], null, 1, callback);
460     },
461     /**
462      * 
463      * @param {String} name name to perform a search for/on
464      * @param {Array} [domain=[]] filters for the objects returned, OpenERP domain
465      * @param {String} [operator='ilike'] matching operator to use with the provided name value
466      * @param {Number} [limit=100] maximum number of matches to return
467      * @param {Function} callback function to call with name_search result
468      * @returns {$.Deferred}
469      */
470     name_search: function (name, domain, operator, limit, callback) {
471         return this.call_and_eval('name_search',
472             [name || '', domain || false, operator || 'ilike', this.get_context(), limit || 100],
473             1, 3, callback);
474     },
475     /**
476      * @param name
477      * @param callback
478      */
479     name_create: function(name, callback) {
480         return this.call_and_eval('name_create', [name, this.get_context()], null, 1, callback);
481     },
482     exec_workflow: function (id, signal, callback) {
483         return this.rpc('/web/dataset/exec_workflow', {
484             model: this.model,
485             id: id,
486             signal: signal
487         }, callback);
488     },
489     get_context: function(request_context) {
490         if (request_context) {
491             return new openerp.web.CompoundContext(this.context, request_context);
492         }
493         return this.context;
494     }
495 });
496 openerp.web.DataSetStatic =  openerp.web.DataSet.extend({
497     init: function(parent, model, context, ids) {
498         this._super(parent, model, context);
499         // all local records
500         this.ids = ids || [];
501     },
502     read_slice: function (fields, options, callback) {
503         // TODO remove fields from options
504         var self = this,
505             offset = options.offset || 0,
506             limit = options.limit || false,
507             fields = fields || false;
508         var end_pos = limit && limit !== -1 ? offset + limit : this.ids.length;
509         return this.read_ids(this.ids.slice(offset, end_pos), fields, callback);
510     },
511     set_ids: function (ids) {
512         this.ids = ids;
513         if (this.index !== null) {
514             this.index = this.index <= this.ids.length - 1 ?
515                 this.index : (this.ids.length > 0 ? this.length - 1 : 0);
516         }
517     },
518     unlink: function(ids) {
519         this.on_unlink(ids);
520         return $.Deferred().resolve({result: true});
521     },
522     on_unlink: function(ids) {
523         this.set_ids(_.without.apply(null, [this.ids].concat(ids)));
524     }
525 });
526 openerp.web.DataSetSearch =  openerp.web.DataSet.extend(/** @lends openerp.web.DataSetSearch */{
527     /**
528      * @constructs openerp.web.DataSetSearch
529      * @extends openerp.web.DataSet
530      *
531      * @param {Object} parent
532      * @param {String} model
533      * @param {Object} context
534      * @param {Array} domain
535      */
536     init: function(parent, model, context, domain) {
537         this._super(parent, model, context);
538         this.domain = domain || [];
539         this._sort = [];
540         this.offset = 0;
541         // subset records[offset:offset+limit]
542         // is it necessary ?
543         this.ids = [];
544     },
545     /**
546      * Read a slice of the records represented by this DataSet, based on its
547      * domain and context.
548      *
549      * @params {Object} options
550      * @param {Array} [options.fields] fields to read and return, by default all fields are returned
551      * @param {Object} [options.context] context data to add to the request payload, on top of the DataSet's own context
552      * @param {Array} [options.domain] domain data to add to the request payload, ANDed with the dataset's domain
553      * @param {Number} [options.offset=0] The index from which selected records should be returned
554      * @param {Number} [options.limit=null] The maximum number of records to return
555      * @param {Function} callback function called with read_slice result
556      * @returns {$.Deferred}
557      */
558     read_slice: function (fields, options, callback) {
559         var self = this;
560         var options = options || {};
561         var offset = options.offset || 0;
562         return this.rpc('/web/dataset/search_read', {
563             model: this.model,
564             fields: fields || false,
565             domain: this.get_domain(options.domain),
566             context: this.get_context(options.context),
567             sort: this.sort(),
568             offset: offset,
569             limit: options.limit || false
570         }).pipe(function (result) {
571             self.ids = result.ids;
572             self.offset = offset;
573             return result.records;
574         }).then(callback);
575     },
576     get_domain: function (other_domain) {
577         if (other_domain) {
578             return new openerp.web.CompoundDomain(this.domain, other_domain);
579         }
580         return this.domain;
581     },
582     /**
583      * Reads or changes sort criteria on the dataset.
584      *
585      * If not provided with any argument, serializes the sort criteria to
586      * an SQL-like form usable by OpenERP's ORM.
587      *
588      * If given a field, will set that field as first sorting criteria or,
589      * if the field is already the first sorting criteria, will reverse it.
590      *
591      * @param {String} [field] field to sort on, reverses it (toggle from ASC to DESC) if already the main sort criteria
592      * @param {Boolean} [force_reverse=false] forces inserting the field as DESC
593      * @returns {String|undefined}
594      */
595     sort: function (field, force_reverse) {
596         if (!field) {
597             return openerp.web.serialize_sort(this._sort);
598         }
599         var reverse = force_reverse || (this._sort[0] === field);
600         this._sort.splice.apply(
601             this._sort, [0, this._sort.length].concat(
602                 _.without(this._sort, field, '-' + field)));
603
604         this._sort.unshift((reverse ? '-' : '') + field);
605         return undefined;
606     },
607     unlink: function(ids, callback, error_callback) {
608         var self = this;
609         return this._super(ids, function(result) {
610             self.ids = _.without.apply(_, [self.ids].concat(ids));
611             if (this.index !== null) {
612                 self.index = self.index <= self.ids.length - 1 ?
613                     self.index : (self.ids.length > 0 ? self.ids.length -1 : 0);
614             }
615             if (callback)
616                 callback(result);
617         }, error_callback);
618     }
619 });
620 openerp.web.BufferedDataSet = openerp.web.DataSetStatic.extend({
621     virtual_id_prefix: "one2many_v_id_",
622     debug_mode: true,
623     init: function() {
624         this._super.apply(this, arguments);
625         this.reset_ids([]);
626         this.last_default_get = {};
627     },
628     default_get: function(fields, callback) {
629         return this._super(fields).then(this.on_default_get).then(callback);
630     },
631     on_default_get: function(res) {
632         this.last_default_get = res;
633     },
634     create: function(data, callback, error_callback) {
635         var cached = {id:_.uniqueId(this.virtual_id_prefix), values: data,
636             defaults: this.last_default_get};
637         this.to_create.push(_.extend(_.clone(cached), {values: _.clone(cached.values)}));
638         this.cache.push(cached);
639         this.on_change();
640         var prom = $.Deferred().then(callback);
641         prom.resolve({result: cached.id});
642         return prom.promise();
643     },
644     write: function (id, data, options, callback) {
645         var self = this;
646         var record = _.detect(this.to_create, function(x) {return x.id === id;});
647         record = record || _.detect(this.to_write, function(x) {return x.id === id;});
648         var dirty = false;
649         if (record) {
650             for (var k in data) {
651                 if (record.values[k] === undefined || record.values[k] !== data[k]) {
652                     dirty = true;
653                     break;
654                 }
655             }
656             $.extend(record.values, data);
657         } else {
658             dirty = true;
659             record = {id: id, values: data};
660             self.to_write.push(record);
661         }
662         var cached = _.detect(this.cache, function(x) {return x.id === id;});
663         if (!cached) {
664             cached = {id: id, values: {}};
665             this.cache.push(cached);
666         }
667         $.extend(cached.values, record.values);
668         if (dirty)
669             this.on_change();
670         var to_return = $.Deferred().then(callback);
671         to_return.resolve({result: true});
672         return to_return.promise();
673     },
674     unlink: function(ids, callback, error_callback) {
675         var self = this;
676         _.each(ids, function(id) {
677             if (! _.detect(self.to_create, function(x) { return x.id === id; })) {
678                 self.to_delete.push({id: id})
679             }
680         });
681         this.to_create = _.reject(this.to_create, function(x) { return _.include(ids, x.id);});
682         this.to_write = _.reject(this.to_write, function(x) { return _.include(ids, x.id);});
683         this.cache = _.reject(this.cache, function(x) { return _.include(ids, x.id);});
684         this.set_ids(_.without.apply(_, [this.ids].concat(ids)));
685         this.on_change();
686         var to_return = $.Deferred().then(callback);
687         setTimeout(function () {to_return.resolve({result: true});}, 0);
688         return to_return.promise();
689     },
690     reset_ids: function(ids) {
691         this.set_ids(ids);
692         this.to_delete = [];
693         this.to_create = [];
694         this.to_write = [];
695         this.cache = [];
696         this.delete_all = false;
697     },
698     on_change: function() {},
699     read_ids: function (ids, fields, callback) {
700         var self = this;
701         var to_get = [];
702         _.each(ids, function(id) {
703             var cached = _.detect(self.cache, function(x) {return x.id === id;});
704             var created = _.detect(self.to_create, function(x) {return x.id === id;});
705             if (created) {
706                 _.each(fields, function(x) {if (cached.values[x] === undefined)
707                     cached.values[x] = created.defaults[x] || false;});
708             } else {
709                 if (!cached || !_.all(fields, function(x) {return cached.values[x] !== undefined}))
710                     to_get.push(id);
711             }
712         });
713         var completion = $.Deferred().then(callback);
714         var return_records = function() {
715             var records = _.map(ids, function(id) {
716                 return _.extend({}, _.detect(self.cache, function(c) {return c.id === id;}).values, {"id": id});
717             });
718             if (self.debug_mode) {
719                 if (_.include(records, undefined)) {
720                     throw "Record not correctly loaded";
721                 }
722             }
723             completion.resolve(records);
724         };
725         if(to_get.length > 0) {
726             var rpc_promise = this._super(to_get, fields, function(records) {
727                 _.each(records, function(record, index) {
728                     var id = to_get[index];
729                     var cached = _.detect(self.cache, function(x) {return x.id === id;});
730                     if (!cached) {
731                         self.cache.push({id: id, values: record});
732                     } else {
733                         // I assume cache value is prioritary
734                         _.defaults(cached.values, record);
735                     }
736                 });
737                 return_records();
738             });
739             $.when(rpc_promise).fail(function() {completion.reject();});
740         } else {
741             return_records();
742         }
743         return completion.promise();
744     },
745     call_button: function (method, args, callback, error_callback) {
746         var id = args[0][0], index;
747         for(var i=0, len=this.cache.length; i<len; ++i) {
748             var record = this.cache[i];
749             // if record we call the button upon is in the cache
750             if (record.id === id) {
751                 // evict it so it gets reloaded from server
752                 this.cache.splice(i, 1);
753                 break;
754             }
755         }
756         return this._super(method, args, callback, error_callback);
757     }
758 });
759 openerp.web.BufferedDataSet.virtual_id_regex = /^one2many_v_id_.*$/;
760
761 openerp.web.ProxyDataSet = openerp.web.DataSetSearch.extend({
762     init: function() {
763         this._super.apply(this, arguments);
764         this.create_function = null;
765         this.write_function = null;
766         this.read_function = null;
767     },
768     read_ids: function () {
769         if (this.read_function) {
770             return this.read_function.apply(null, arguments);
771         } else {
772             return this._super.apply(this, arguments);
773         }
774     },
775     default_get: function(fields, callback) {
776         return this._super(fields, callback).then(this.on_default_get);
777     },
778     on_default_get: function(result) {},
779     create: function(data, callback, error_callback) {
780         this.on_create(data);
781         if (this.create_function) {
782             return this.create_function(data, callback, error_callback);
783         } else {
784             console.warn("trying to create a record using default proxy dataset behavior");
785             var to_return = $.Deferred().then(callback);
786             setTimeout(function () {to_return.resolve({"result": undefined});}, 0);
787             return to_return.promise();
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             var to_return = $.Deferred().then(callback);
798             setTimeout(function () {to_return.resolve({"result": true});}, 0);
799             return to_return.promise();
800         }
801     },
802     on_write: function(id, data) {},
803     unlink: function(ids, callback, error_callback) {
804         this.on_unlink(ids);
805         console.warn("trying to unlink a record using default proxy dataset behavior");
806         var to_return = $.Deferred().then(callback);
807         setTimeout(function () {to_return.resolve({"result": true});}, 0);
808         return to_return.promise();
809     },
810     on_unlink: function(ids) {}
811 });
812
813 openerp.web.Model = openerp.web.CallbackEnabled.extend({
814     init: function(model_name) {
815         this._super();
816         this.model_name = model_name;
817     },
818     rpc: function() {
819         var c = openerp.connection;
820         return c.rpc.apply(c, arguments);
821     },
822     get_func: function(method_name) {
823         var self = this;
824         return function() {
825             if (method_name == "search_read")
826                 return self._search_read.apply(self, arguments);
827             return self._call(method_name, _.toArray(arguments));
828         };
829     },
830     _call: function (method, args) {
831         return this.rpc('/web/dataset/call', {
832             model: this.model_name,
833             method: method,
834             args: args
835         }).pipe(function(result) {
836             if (method == "read" && result instanceof Array && result.length > 0 && result[0]["id"]) {
837                 var index = {};
838                 _.each(_.range(result.length), function(i) {
839                     index[result[i]["id"]] = result[i];
840                 });
841                 result = _.map(args[0], function(x) {return index[x];});
842             }
843             return result;
844         });
845     },
846     _search_read: function(domain, fields, offset, limit, order, context) {
847         return this.rpc('/web/dataset/search_read', {
848             model: this.model_name,
849             fields: fields,
850             offset: offset,
851             limit: limit,
852             domain: domain,
853             sort: order,
854             context: context
855         }).pipe(function(result) {
856             return result.records;
857         });
858     }
859 });
860
861 openerp.web.CompoundContext = openerp.web.Class.extend({
862     init: function () {
863         this.__ref = "compound_context";
864         this.__contexts = [];
865         this.__eval_context = null;
866         var self = this;
867         _.each(arguments, function(x) {
868             self.add(x);
869         });
870     },
871     add: function (context) {
872         this.__contexts.push(context);
873         return this;
874     },
875     set_eval_context: function (eval_context) {
876         this.__eval_context = eval_context;
877         return this;
878     },
879     get_eval_context: function () {
880         return this.__eval_context;
881     }
882 });
883
884 openerp.web.CompoundDomain = openerp.web.Class.extend({
885     init: function () {
886         this.__ref = "compound_domain";
887         this.__domains = [];
888         this.__eval_context = null;
889         var self = this;
890         _.each(arguments, function(x) {
891             self.add(x);
892         });
893     },
894     add: function(domain) {
895         this.__domains.push(domain);
896         return this;
897     },
898     set_eval_context: function(eval_context) {
899         this.__eval_context = eval_context;
900         return this;
901     },
902     get_eval_context: function() {
903         return this.__eval_context;
904     }
905 });
906 };
907
908 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: