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.Widget.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.Widget
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
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.Widget.extend( /** @lends openerp.web.DataSet# */{
237 identifier_prefix: "dataset",
239 * DateaManagement interface between views and the collection of selected
240 * OpenERP records (represents the view's state?)
242 * @constructs openerp.web.DataSet
243 * @extends openerp.web.Widget
245 * @param {String} model the OpenERP model this dataset will manage
247 init: function(parent, model, context) {
250 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 }, callback, error_callback);
438 * Calls a button method, usually returning some sort of action
440 * @param {String} method
441 * @param {Array} [args]
442 * @param {Function} callback
443 * @param {Function} error_callback
444 * @returns {$.Deferred}
446 call_button: function (method, args, callback, error_callback) {
447 return this.rpc('/web/dataset/call_button', {
451 context_id: args.length - 1,
453 }, callback, error_callback);
456 * Fetches the "readable name" for records, based on intrinsic rules
459 * @param {Function} callback
460 * @returns {$.Deferred}
462 name_get: function(ids, callback) {
463 return this.call_and_eval('name_get', [ids, this.get_context()], null, 1, callback);
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}
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],
483 name_create: function(name, callback) {
484 return this.call_and_eval('name_create', [name, this.get_context()], null, 1, callback);
486 exec_workflow: function (id, signal, callback) {
487 return this.rpc('/web/dataset/exec_workflow', {
493 get_context: function(request_context) {
494 if (request_context) {
495 return new openerp.web.CompoundContext(this.context, request_context);
500 openerp.web.DataSetStatic = openerp.web.DataSet.extend({
501 init: function(parent, model, context, ids) {
502 this._super(parent, model, context);
504 this.ids = ids || [];
506 read_slice: function (fields, options) {
507 // TODO remove fields from options
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);
515 set_ids: function (ids) {
517 if (ids.length === 0) {
519 } else if (this.index >= ids.length - 1) {
520 this.index = ids.length - 1;
523 unlink: function(ids) {
525 return $.Deferred().resolve({result: true});
527 on_unlink: function(ids) {
528 this.set_ids(_.without.apply(null, [this.ids].concat(ids)));
531 openerp.web.DataSetSearch = openerp.web.DataSet.extend(/** @lends openerp.web.DataSetSearch */{
533 * @constructs openerp.web.DataSetSearch
534 * @extends openerp.web.DataSet
536 * @param {Object} parent
537 * @param {String} model
538 * @param {Object} context
539 * @param {Array} domain
541 init: function(parent, model, context, domain) {
542 this._super(parent, model, context);
543 this.domain = domain || [];
546 // subset records[offset:offset+limit]
551 * Read a slice of the records represented by this DataSet, based on its
552 * domain and context.
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}
562 read_slice: function (fields, options) {
564 var options = options || {};
565 var offset = options.offset || 0;
566 return this.rpc('/web/dataset/search_read', {
568 fields: fields || false,
569 domain: this.get_domain(options.domain),
570 context: this.get_context(options.context),
573 limit: options.limit || false
574 }).pipe(function (result) {
575 self.ids = result.ids;
576 self.offset = offset;
577 return result.records;
580 get_domain: function (other_domain) {
582 return new openerp.web.CompoundDomain(this.domain, other_domain);
587 * Reads or changes sort criteria on the dataset.
589 * If not provided with any argument, serializes the sort criteria to
590 * an SQL-like form usable by OpenERP's ORM.
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.
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}
599 sort: function (field, force_reverse) {
601 return openerp.web.serialize_sort(this._sort);
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)));
608 this._sort.unshift((reverse ? '-' : '') + field);
611 unlink: function(ids, callback, error_callback) {
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);
624 openerp.web.BufferedDataSet = openerp.web.DataSetStatic.extend({
625 virtual_id_prefix: "one2many_v_id_",
628 this._super.apply(this, arguments);
630 this.last_default_get = {};
632 default_get: function(fields, options) {
633 return this._super(fields, options).then(this.on_default_get);
635 on_default_get: function(res) {
636 this.last_default_get = res;
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);
644 var prom = $.Deferred().then(callback);
645 prom.resolve({result: cached.id});
646 return prom.promise();
648 write: function (id, data, options, callback) {
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;});
654 for (var k in data) {
655 if (record.values[k] === undefined || record.values[k] !== data[k]) {
660 $.extend(record.values, data);
663 record = {id: id, values: data};
664 self.to_write.push(record);
666 var cached = _.detect(this.cache, function(x) {return x.id === id;});
668 cached = {id: id, values: {}};
669 this.cache.push(cached);
671 $.extend(cached.values, record.values);
674 var to_return = $.Deferred().then(callback);
675 to_return.resolve({result: true});
676 return to_return.promise();
678 unlink: function(ids, callback, error_callback) {
680 _.each(ids, function(id) {
681 if (! _.detect(self.to_create, function(x) { return x.id === id; })) {
682 self.to_delete.push({id: id})
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)));
690 return $.async_when({result: true}).then(callback);
692 reset_ids: function(ids) {
698 this.delete_all = false;
700 on_change: function() {},
701 read_ids: function (ids, fields, options) {
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;});
708 _.each(fields, function(x) {if (cached.values[x] === undefined)
709 cached.values[x] = created.defaults[x] || false;});
711 if (!cached || !_.all(fields, function(x) {return cached.values[x] !== undefined}))
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});
720 if (self.debug_mode) {
721 if (_.include(records, undefined)) {
722 throw "Record not correctly loaded";
725 completion.resolve(records);
727 if(to_get.length > 0) {
728 var rpc_promise = this._super(to_get, fields, options).then(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;});
733 self.cache.push({id: id, values: record});
735 // I assume cache value is prioritary
736 _.defaults(cached.values, record);
741 $.when(rpc_promise).fail(function() {completion.reject();});
745 return completion.promise();
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);
758 return this._super(method, args, callback, error_callback);
761 openerp.web.BufferedDataSet.virtual_id_regex = /^one2many_v_id_.*$/;
763 openerp.web.ProxyDataSet = openerp.web.DataSetSearch.extend({
765 this._super.apply(this, arguments);
766 this.create_function = null;
767 this.write_function = null;
768 this.read_function = null;
770 read_ids: function () {
771 if (this.read_function) {
772 return this.read_function.apply(null, arguments);
774 return this._super.apply(this, arguments);
777 default_get: function(fields, options) {
778 return this._super(fields, options).then(this.on_default_get);
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);
786 console.warn("trying to create a record using default proxy dataset behavior");
787 return $.async_when({"result": undefined}).then(callback);
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);
796 console.warn("trying to write a record using default proxy dataset behavior");
797 return $.async_when({"result": true}).then(callback);
800 on_write: function(id, data) {},
801 unlink: function(ids, callback, error_callback) {
803 console.warn("trying to unlink a record using default proxy dataset behavior");
804 return $.async_when({"result": true}).then(callback);
806 on_unlink: function(ids) {}
809 openerp.web.Model = openerp.web.CallbackEnabled.extend({
810 init: function(model_name) {
812 this.model_name = model_name;
815 var c = openerp.connection;
816 return c.rpc.apply(c, arguments);
819 * deprecated because it does not allow to specify kwargs, directly use call() instead
821 get_func: function(method_name) {
824 return self.call(method_name, _.toArray(arguments), {});
827 call: function (method, args, kwargs) {
828 return this.rpc('/web/dataset/call_kw', {
829 model: this.model_name,
837 openerp.web.CompoundContext = openerp.web.Class.extend({
839 this.__ref = "compound_context";
840 this.__contexts = [];
841 this.__eval_context = null;
843 _.each(arguments, function(x) {
847 add: function (context) {
848 this.__contexts.push(context);
851 set_eval_context: function (eval_context) {
852 this.__eval_context = eval_context;
855 get_eval_context: function () {
856 return this.__eval_context;
860 openerp.web.CompoundDomain = openerp.web.Class.extend({
862 this.__ref = "compound_domain";
864 this.__eval_context = null;
866 _.each(arguments, function(x) {
870 add: function(domain) {
871 this.__domains.push(domain);
874 set_eval_context: function(eval_context) {
875 this.__eval_context = eval_context;
878 get_eval_context: function() {
879 return this.__eval_context;
884 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: