2 openerp.web.data = function(openerp) {
5 * Serializes the sort criterion array of a dataset into a form which can be
6 * consumed by OpenERP's RPC APIs.
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
11 openerp.web.serialize_sort = function (criterion) {
12 return _.map(criterion,
14 if (criteria[0] === '-') {
15 return criteria.slice(1) + ' DESC';
17 return criteria + ' ASC';
21 openerp.web.DataGroup = openerp.web.OldWidget.extend( /** @lends openerp.web.DataGroup# */{
23 * Management interface between views and grouped collections of OpenERP
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.
32 * @constructs openerp.web.DataGroup
33 * @extends openerp.web.OldWidget
35 * @param {openerp.web.OldWidget} 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
42 init: function(parent, model, domain, context, group_by, level) {
43 this._super(parent, null);
45 if (group_by.length || context['group_by_no_leaf']) {
46 return new openerp.web.ContainerDataGroup( this, model, domain, context, group_by, level);
48 return new openerp.web.GrouplessDataGroup( this, model, domain, context, level);
53 this.context = context;
56 this.level = level || 0;
60 openerp.web.ContainerDataGroup = openerp.web.DataGroup.extend( /** @lends openerp.web.ContainerDataGroup# */ {
63 * @constructs openerp.web.ContainerDataGroup
64 * @extends openerp.web.DataGroup
73 init: function (parent, model, domain, context, group_by, level) {
74 this._super(parent, model, domain, context, null, level);
76 this.group_by = group_by;
79 * The format returned by ``read_group`` is absolutely dreadful:
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
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
91 * This function slightly improves the grouping records by:
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
98 * Context and domain keys remain as-is, they should not be used externally
99 * but in case they're needed...
101 * @param {Object} group ``read_group`` record
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: []},
113 _(fixed_group).each(function (value, key) {
114 if (key.indexOf('__') === 0
115 || key === field_name
116 || key === field_name + '_count') {
119 aggregates[key] = value || 0;
122 var group_size = fixed_group[field_name + '_count'] || fixed_group.__count || 0;
123 var leaf_group = fixed_group.__context.group_by.length === 0;
125 __context: fixed_group.__context,
126 __domain: fixed_group.__domain,
128 grouped_on: field_name,
129 // if terminal group (or no group) and group_by_no_leaf => use group.__count
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']),
135 aggregates: aggregates
138 fetch: function (fields) {
140 var d = new $.Deferred();
143 this.rpc('/web/group/read', {
145 context: this.context,
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]);
156 d.rejectWith.apply(d, [self, arguments]);
161 * The items of a list have the following properties:
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
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.
174 * the value which led to this group (this is the value all contained
175 * records have for the current ``grouped_on`` field name).
177 * a mapping of other aggregation fields provided by ``read_group``
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
183 list: function (fields, ifGroups, ifRecords) {
185 this.fetch(fields).then(function (group_records) {
186 ifGroups(_(group_records).map(function (group) {
187 var child_context = _.extend({}, self.context, group.__context);
189 new openerp.web.DataGroup(
190 self, self.model, group.__domain,
191 child_context, child_context.group_by,
193 group, {sort: self.sort});
198 openerp.web.GrouplessDataGroup = openerp.web.DataGroup.extend( /** @lends openerp.web.GrouplessDataGroup# */ {
201 * @constructs openerp.web.GrouplessDataGroup
202 * @extends openerp.web.DataGroup
210 init: function (parent, model, domain, context, level) {
211 this._super(parent, model, domain, context, null, level);
213 list: function (fields, ifGroups, ifRecords) {
215 new openerp.web.DataSetSearch(this, this.model),
216 {domain: this.domain, context: this.context, _sort: this.sort}));
219 openerp.web.StaticDataGroup = openerp.web.GrouplessDataGroup.extend( /** @lends openerp.web.StaticDataGroup# */ {
221 * A specialization of groupless data groups, relying on a single static
222 * dataset as its records provider.
224 * @constructs openerp.web.StaticDataGroup
225 * @extends openerp.web.GrouplessDataGroup
226 * @param {openep.web.DataSetStatic} dataset a static dataset backing the groups
228 init: function (dataset) {
229 this.dataset = dataset;
231 list: function (fields, ifGroups, ifRecords) {
232 ifRecords(this.dataset);
236 openerp.web.DataSet = openerp.web.OldWidget.extend( /** @lends openerp.web.DataSet# */{
238 * DateaManagement interface between views and the collection of selected
239 * OpenERP records (represents the view's state?)
241 * @constructs openerp.web.DataSet
242 * @extends openerp.web.OldWidget
244 * @param {String} model the OpenERP model this dataset will manage
246 init: function(parent, model, context) {
249 this.context = context || {};
253 previous: function () {
255 if (!this.ids.length) {
257 } else if (this.index < 0) {
258 this.index = this.ids.length - 1;
264 if (!this.ids.length) {
266 } else if (this.index >= this.ids.length) {
271 select_id: function(id) {
272 var idx = this.get_id_index(id);
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]) {
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}
298 read_ids: function (ids, fields, options) {
299 var options = options || {};
300 return this.rpc('/web/dataset/get', {
304 context: this.get_context(options.context)
308 * Read a slice of the records represented by this DataSet, based on its
309 * domain and context.
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}
317 read_slice: function (fields, options) {
321 * Reads the current dataset record (from its index)
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}
327 read_index: function (fields, options) {
328 var def = $.Deferred();
329 if (_.isEmpty(this.ids)) {
332 fields = fields || false;
333 this.read_ids([this.ids[this.index]], fields, options).then(function(records) {
334 def.resolve(records[0]);
336 def.reject.apply(def, arguments);
339 return def.promise();
342 * Reads default values for the current model
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}
348 default_get: function(fields, options) {
349 var options = options || {};
350 return this.rpc('/web/dataset/default_get', {
353 context: this.get_context(options.context)
357 * Creates a new record in db
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}
364 create: function(data, callback, error_callback) {
365 return this.rpc('/web/dataset/create', {
368 context: this.get_context()
369 }, callback, error_callback);
372 * Saves the provided data in an existing db record
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}
380 write: function (id, data, options, callback, error_callback) {
381 options = options || {};
382 return this.rpc('/web/dataset/save', {
386 context: this.get_context(options.context)
387 }, callback, error_callback);
390 * Deletes an existing record from the database
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
396 unlink: function(ids, callback, error_callback) {
398 return this.call_and_eval("unlink", [ids, this.get_context()], null, 1,
399 callback, error_callback);
402 * Calls an arbitrary RPC method
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}
410 call: function (method, args, callback, error_callback) {
411 return this.rpc('/web/dataset/call', {
415 }, callback, error_callback);
418 * Calls an arbitrary method, with more crazy
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}
428 call_and_eval: function (method, args, domain_index, context_index, callback, error_callback) {
429 return this.rpc('/web/dataset/call', {
432 domain_id: domain_index == undefined ? null : domain_index,
433 context_id: context_index == undefined ? null : context_index,
435 // FIXME: API which does not suck for aborting requests in-flight
437 }, callback, error_callback);
440 * Calls a button method, usually returning some sort of action
442 * @param {String} method
443 * @param {Array} [args]
444 * @param {Function} callback
445 * @param {Function} error_callback
446 * @returns {$.Deferred}
448 call_button: function (method, args, callback, error_callback) {
449 return this.rpc('/web/dataset/call_button', {
453 context_id: args.length - 1,
455 }, callback, error_callback);
458 * Fetches the "readable name" for records, based on intrinsic rules
461 * @param {Function} callback
462 * @returns {$.Deferred}
464 name_get: function(ids, callback) {
465 return this.call_and_eval('name_get', [ids, this.get_context()], null, 1, callback);
469 * @param {String} name name to perform a search for/on
470 * @param {Array} [domain=[]] filters for the objects returned, OpenERP domain
471 * @param {String} [operator='ilike'] matching operator to use with the provided name value
472 * @param {Number} [limit=100] maximum number of matches to return
473 * @param {Function} callback function to call with name_search result
474 * @returns {$.Deferred}
476 name_search: function (name, domain, operator, limit, callback) {
477 return this.call_and_eval('name_search',
478 [name || '', domain || false, operator || 'ilike', this.get_context(), limit || 100],
485 name_create: function(name, callback) {
486 return this.call_and_eval('name_create', [name, this.get_context()], null, 1, callback);
488 exec_workflow: function (id, signal, callback) {
489 return this.rpc('/web/dataset/exec_workflow', {
495 get_context: function(request_context) {
496 if (request_context) {
497 return new openerp.web.CompoundContext(this.context, request_context);
502 * Reads or changes sort criteria on the dataset.
504 * If not provided with any argument, serializes the sort criteria to
505 * an SQL-like form usable by OpenERP's ORM.
507 * If given a field, will set that field as first sorting criteria or,
508 * if the field is already the first sorting criteria, will reverse it.
510 * @param {String} [field] field to sort on, reverses it (toggle from ASC to DESC) if already the main sort criteria
511 * @param {Boolean} [force_reverse=false] forces inserting the field as DESC
512 * @returns {String|undefined}
514 sort: function (field, force_reverse) {
516 return openerp.web.serialize_sort(this._sort);
518 var reverse = force_reverse || (this._sort[0] === field);
519 this._sort.splice.apply(
520 this._sort, [0, this._sort.length].concat(
521 _.without(this._sort, field, '-' + field)));
523 this._sort.unshift((reverse ? '-' : '') + field);
527 return this.ids.length;
529 alter_ids: function(n_ids) {
533 openerp.web.DataSetStatic = openerp.web.DataSet.extend({
534 init: function(parent, model, context, ids) {
535 this._super(parent, model, context);
537 this.ids = ids || [];
539 read_slice: function (fields, options) {
540 options = options || {};
541 fields = fields || {};
542 var offset = options.offset || 0,
543 limit = options.limit || false;
544 var end_pos = limit && limit !== -1 ? offset + limit : this.ids.length;
545 return this.read_ids(this.ids.slice(offset, end_pos), fields);
547 set_ids: function (ids) {
549 if (ids.length === 0) {
551 } else if (this.index >= ids.length - 1) {
552 this.index = ids.length - 1;
555 unlink: function(ids) {
557 return $.Deferred().resolve({result: true});
559 on_unlink: function(ids) {
560 this.set_ids(_.without.apply(null, [this.ids].concat(ids)));
563 openerp.web.DataSetSearch = openerp.web.DataSet.extend(/** @lends openerp.web.DataSetSearch */{
565 * @constructs openerp.web.DataSetSearch
566 * @extends openerp.web.DataSet
568 * @param {Object} parent
569 * @param {String} model
570 * @param {Object} context
571 * @param {Array} domain
573 init: function(parent, model, context, domain) {
574 this._super(parent, model, context);
575 this.domain = domain || [];
578 // subset records[offset:offset+limit]
583 * Read a slice of the records represented by this DataSet, based on its
584 * domain and context.
586 * @params {Object} options
587 * @param {Array} [options.fields] fields to read and return, by default all fields are returned
588 * @param {Object} [options.context] context data to add to the request payload, on top of the DataSet's own context
589 * @param {Array} [options.domain] domain data to add to the request payload, ANDed with the dataset's domain
590 * @param {Number} [options.offset=0] The index from which selected records should be returned
591 * @param {Number} [options.limit=null] The maximum number of records to return
592 * @returns {$.Deferred}
594 read_slice: function (fields, options) {
595 options = options || {};
597 var offset = options.offset || 0;
598 return this.rpc('/web/dataset/search_read', {
600 fields: fields || false,
601 domain: this.get_domain(options.domain),
602 context: this.get_context(options.context),
605 limit: options.limit || false
606 }).pipe(function (result) {
607 self.ids = result.ids;
608 self.offset = offset;
609 self._length = result.length;
610 return result.records;
613 get_domain: function (other_domain) {
615 return new openerp.web.CompoundDomain(this.domain, other_domain);
619 unlink: function(ids, callback, error_callback) {
621 return this._super(ids, function(result) {
622 self.ids = _.without.apply(_, [self.ids].concat(ids));
623 if (this.index !== null) {
624 self.index = self.index <= self.ids.length - 1 ?
625 self.index : (self.ids.length > 0 ? self.ids.length -1 : 0);
632 if (this._length !== undefined) {
635 return this._super();
638 openerp.web.BufferedDataSet = openerp.web.DataSetStatic.extend({
639 virtual_id_prefix: "one2many_v_id_",
642 this._super.apply(this, arguments);
644 this.last_default_get = {};
646 default_get: function(fields, options) {
647 return this._super(fields, options).then(this.on_default_get);
649 on_default_get: function(res) {
650 this.last_default_get = res;
652 create: function(data, callback, error_callback) {
653 var cached = {id:_.uniqueId(this.virtual_id_prefix), values: data,
654 defaults: this.last_default_get};
655 this.to_create.push(_.extend(_.clone(cached), {values: _.clone(cached.values)}));
656 this.cache.push(cached);
657 var prom = $.Deferred().then(callback);
658 prom.resolve({result: cached.id});
659 return prom.promise();
661 write: function (id, data, options, callback) {
663 var record = _.detect(this.to_create, function(x) {return x.id === id;});
664 record = record || _.detect(this.to_write, function(x) {return x.id === id;});
667 for (var k in data) {
668 if (record.values[k] === undefined || record.values[k] !== data[k]) {
673 $.extend(record.values, data);
676 record = {id: id, values: data};
677 self.to_write.push(record);
679 var cached = _.detect(this.cache, function(x) {return x.id === id;});
681 cached = {id: id, values: {}};
682 this.cache.push(cached);
684 $.extend(cached.values, record.values);
687 var to_return = $.Deferred().then(callback);
688 to_return.resolve({result: true});
689 return to_return.promise();
691 unlink: function(ids, callback, error_callback) {
693 _.each(ids, function(id) {
694 if (! _.detect(self.to_create, function(x) { return x.id === id; })) {
695 self.to_delete.push({id: id})
698 this.to_create = _.reject(this.to_create, function(x) { return _.include(ids, x.id);});
699 this.to_write = _.reject(this.to_write, function(x) { return _.include(ids, x.id);});
700 this.cache = _.reject(this.cache, function(x) { return _.include(ids, x.id);});
701 this.set_ids(_.without.apply(_, [this.ids].concat(ids)));
703 return $.async_when({result: true}).then(callback);
705 reset_ids: function(ids) {
711 this.delete_all = false;
713 on_change: function() {},
714 read_ids: function (ids, fields, options) {
717 _.each(ids, function(id) {
718 var cached = _.detect(self.cache, function(x) {return x.id === id;});
719 var created = _.detect(self.to_create, function(x) {return x.id === id;});
721 _.each(fields, function(x) {if (cached.values[x] === undefined)
722 cached.values[x] = created.defaults[x] || false;});
724 if (!cached || !_.all(fields, function(x) {return cached.values[x] !== undefined}))
728 var completion = $.Deferred();
729 var return_records = function() {
730 var records = _.map(ids, function(id) {
731 return _.extend({}, _.detect(self.cache, function(c) {return c.id === id;}).values, {"id": id});
733 if (self.debug_mode) {
734 if (_.include(records, undefined)) {
735 throw "Record not correctly loaded";
738 var sort_fields = self._sort,
739 compare = function (v1, v2) {
740 return (v1 < v2) ? -1
744 records.sort(function (a, b) {
745 return _.reduce(sort_fields, function (acc, field) {
746 if (acc) { return acc; }
749 if (field[0] === '-') {
751 field = field.slice(1);
753 return sign * compare(a[field], b[field]);
756 completion.resolve(records);
758 if(to_get.length > 0) {
759 var rpc_promise = this._super(to_get, fields, options).then(function(records) {
760 _.each(records, function(record, index) {
761 var id = to_get[index];
762 var cached = _.detect(self.cache, function(x) {return x.id === id;});
764 self.cache.push({id: id, values: record});
766 // I assume cache value is prioritary
767 _.defaults(cached.values, record);
772 $.when(rpc_promise).fail(function() {completion.reject();});
776 return completion.promise();
778 call_button: function (method, args, callback, error_callback) {
779 var id = args[0][0], index;
780 for(var i=0, len=this.cache.length; i<len; ++i) {
781 var record = this.cache[i];
782 // if record we call the button upon is in the cache
783 if (record.id === id) {
784 // evict it so it gets reloaded from server
785 this.cache.splice(i, 1);
789 return this._super(method, args, callback, error_callback);
791 alter_ids: function(n_ids) {
796 openerp.web.BufferedDataSet.virtual_id_regex = /^one2many_v_id_.*$/;
798 openerp.web.ProxyDataSet = openerp.web.DataSetSearch.extend({
800 this._super.apply(this, arguments);
801 this.create_function = null;
802 this.write_function = null;
803 this.read_function = null;
805 read_ids: function () {
806 if (this.read_function) {
807 return this.read_function.apply(null, arguments);
809 return this._super.apply(this, arguments);
812 default_get: function(fields, options) {
813 return this._super(fields, options).then(this.on_default_get);
815 on_default_get: function(result) {},
816 create: function(data, callback, error_callback) {
817 this.on_create(data);
818 if (this.create_function) {
819 return this.create_function(data, callback, error_callback);
821 console.warn("trying to create a record using default proxy dataset behavior");
822 return $.async_when({"result": undefined}).then(callback);
825 on_create: function(data) {},
826 write: function (id, data, options, callback) {
827 this.on_write(id, data);
828 if (this.write_function) {
829 return this.write_function(id, data, options, callback);
831 console.warn("trying to write a record using default proxy dataset behavior");
832 return $.async_when({"result": true}).then(callback);
835 on_write: function(id, data) {},
836 unlink: function(ids, callback, error_callback) {
838 console.warn("trying to unlink a record using default proxy dataset behavior");
839 return $.async_when({"result": true}).then(callback);
841 on_unlink: function(ids) {}
844 openerp.web.Model = openerp.web.CallbackEnabled.extend({
845 init: function(model_name) {
847 this.model_name = model_name;
850 var c = openerp.connection;
851 return c.rpc.apply(c, arguments);
854 * deprecated because it does not allow to specify kwargs, directly use call() instead
856 get_func: function(method_name) {
859 return self.call(method_name, _.toArray(arguments), {});
862 call: function (method, args, kwargs) {
863 return this.rpc('/web/dataset/call_kw', {
864 model: this.model_name,
872 openerp.web.CompoundContext = openerp.web.Class.extend({
874 this.__ref = "compound_context";
875 this.__contexts = [];
876 this.__eval_context = null;
878 _.each(arguments, function(x) {
882 add: function (context) {
883 this.__contexts.push(context);
886 set_eval_context: function (eval_context) {
887 this.__eval_context = eval_context;
890 get_eval_context: function () {
891 return this.__eval_context;
895 openerp.web.CompoundDomain = openerp.web.Class.extend({
897 this.__ref = "compound_domain";
899 this.__eval_context = null;
901 _.each(arguments, function(x) {
905 add: function(domain) {
906 this.__domains.push(domain);
909 set_eval_context: function(eval_context) {
910 this.__eval_context = eval_context;
913 get_eval_context: function() {
914 return this.__eval_context;
919 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: