summaryrefslogtreecommitdiff
path: root/addons/web/static/src/js
diff options
context:
space:
mode:
Diffstat (limited to 'addons/web/static/src/js')
-rw-r--r--addons/web/static/src/js/boot.js2
-rw-r--r--addons/web/static/src/js/chrome.js7
-rw-r--r--addons/web/static/src/js/corelib.js299
-rw-r--r--addons/web/static/src/js/data.js19
-rw-r--r--addons/web/static/src/js/pyeval.js774
-rw-r--r--addons/web/static/src/js/search.js51
-rw-r--r--addons/web/static/src/js/testing.js6
-rw-r--r--addons/web/static/src/js/view_form.js40
-rw-r--r--addons/web/static/src/js/view_tree.js10
-rw-r--r--addons/web/static/src/js/views.js103
10 files changed, 909 insertions, 402 deletions
diff --git a/addons/web/static/src/js/boot.js b/addons/web/static/src/js/boot.js
index 631a7f8c6f5..5d50841d78d 100644
--- a/addons/web/static/src/js/boot.js
+++ b/addons/web/static/src/js/boot.js
@@ -53,7 +53,7 @@
* OpenERP Web web module split
*---------------------------------------------------------*/
openerp.web = function(session) {
- var files = ["corelib","coresetup","dates","formats","chrome","data","views","search","list","form","list_editable","web_mobile","view_tree","data_export","data_import"];
+ var files = ["pyeval", "corelib","coresetup","dates","formats","chrome","data","views","search","list","form","list_editable","web_mobile","view_tree","data_export","data_import"];
for(var i=0; i<files.length; i++) {
if(openerp.web[files[i]]) {
openerp.web[files[i]](session);
diff --git a/addons/web/static/src/js/chrome.js b/addons/web/static/src/js/chrome.js
index 91cca8468d1..6bdda1a721e 100644
--- a/addons/web/static/src/js/chrome.js
+++ b/addons/web/static/src/js/chrome.js
@@ -1264,11 +1264,12 @@ instance.web.WebClient = instance.web.Client.extend({
var self = this;
return this.rpc("/web/action/load", { action_id: options.action_id })
.then(function (result) {
- var action = result;
if (options.needaction) {
- action.context.search_default_message_unread = true;
+ result.context = new instance.web.CompoundContext(
+ result.context,
+ {search_default_message_unread: true});
}
- return $.when(self.action_manager.do_action(action, {
+ return $.when(self.action_manager.do_action(result, {
clear_breadcrumbs: true,
action_menu_id: self.menu.current_menu,
})).fail(function() {
diff --git a/addons/web/static/src/js/corelib.js b/addons/web/static/src/js/corelib.js
index 0a6f4ed3a29..55984162a55 100644
--- a/addons/web/static/src/js/corelib.js
+++ b/addons/web/static/src/js/corelib.js
@@ -948,296 +948,6 @@ instance.web.JsonRPC = instance.web.Class.extend(instance.web.PropertiesMixin, {
this.server = this.origin; // keep chs happy
this.rpc_function = (this.origin == window_origin) ? this.rpc_json : this.rpc_jsonp;
},
- test_eval_get_context: function () {
- var asJS = function (arg) {
- if (arg instanceof py.object) {
- return arg.toJSON();
- }
- return arg;
- };
-
- var datetime = new py.object();
- datetime.datetime = new py.type(function datetime() {
- throw new Error('datetime.datetime not implemented');
- });
- var date = datetime.date = new py.type(function date(y, m, d) {
- if (y instanceof Array) {
- d = y[2];
- m = y[1];
- y = y[0];
- }
- this.year = asJS(y);
- this.month = asJS(m);
- this.day = asJS(d);
- }, py.object, {
- strftime: function (args) {
- var f = asJS(args[0]), self = this;
- return new py.str(f.replace(/%([A-Za-z])/g, function (m, c) {
- switch (c) {
- case 'Y': return self.year;
- case 'm': return _.str.sprintf('%02d', self.month);
- case 'd': return _.str.sprintf('%02d', self.day);
- }
- throw new Error('ValueError: No known conversion for ' + m);
- }));
- }
- });
- date.__getattribute__ = function (name) {
- if (name === 'today') {
- return date.today;
- }
- throw new Error("AttributeError: object 'date' has no attribute '" + name +"'");
- };
- date.today = new py.def(function () {
- var d = new Date();
- return new date(d.getFullYear(), d.getMonth() + 1, d.getDate());
- });
- datetime.time = new py.type(function time() {
- throw new Error('datetime.time not implemented');
- });
-
- var time = new py.object();
- time.strftime = new py.def(function (args) {
- return date.today.__call__().strftime(args);
- });
-
- var relativedelta = new py.type(function relativedelta(args, kwargs) {
- if (!_.isEmpty(args)) {
- throw new Error('Extraction of relative deltas from existing datetimes not supported');
- }
- this.ops = kwargs;
- }, py.object, {
- __add__: function (other) {
- if (!(other instanceof datetime.date)) {
- return py.NotImplemented;
- }
- // TODO: test this whole mess
- var year = asJS(this.ops.year) || asJS(other.year);
- if (asJS(this.ops.years)) {
- year += asJS(this.ops.years);
- }
-
- var month = asJS(this.ops.month) || asJS(other.month);
- if (asJS(this.ops.months)) {
- month += asJS(this.ops.months);
- // FIXME: no divmod in JS?
- while (month < 1) {
- year -= 1;
- month += 12;
- }
- while (month > 12) {
- year += 1;
- month -= 12;
- }
- }
-
- var lastMonthDay = new Date(year, month, 0).getDate();
- var day = asJS(this.ops.day) || asJS(other.day);
- if (day > lastMonthDay) { day = lastMonthDay; }
- var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);
- if (days_offset) {
- day = new Date(year, month-1, day + days_offset).getDate();
- }
- // TODO: leapdays?
- // TODO: hours, minutes, seconds? Not used in XML domains
- // TODO: weekday?
- return new datetime.date(year, month, day);
- },
- __radd__: function (other) {
- return this.__add__(other);
- },
-
- __sub__: function (other) {
- if (!(other instanceof datetime.date)) {
- return py.NotImplemented;
- }
- // TODO: test this whole mess
- var year = asJS(this.ops.year) || asJS(other.year);
- if (asJS(this.ops.years)) {
- year -= asJS(this.ops.years);
- }
-
- var month = asJS(this.ops.month) || asJS(other.month);
- if (asJS(this.ops.months)) {
- month -= asJS(this.ops.months);
- // FIXME: no divmod in JS?
- while (month < 1) {
- year -= 1;
- month += 12;
- }
- while (month > 12) {
- year += 1;
- month -= 12;
- }
- }
-
- var lastMonthDay = new Date(year, month, 0).getDate();
- var day = asJS(this.ops.day) || asJS(other.day);
- if (day > lastMonthDay) { day = lastMonthDay; }
- var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);
- if (days_offset) {
- day = new Date(year, month-1, day - days_offset).getDate();
- }
- // TODO: leapdays?
- // TODO: hours, minutes, seconds? Not used in XML domains
- // TODO: weekday?
- return new datetime.date(year, month, day);
- },
- __rsub__: function (other) {
- return this.__sub__(other);
- }
- });
-
- return {
- uid: new py.float(this.uid),
- datetime: datetime,
- time: time,
- relativedelta: relativedelta,
- current_date: date.today.__call__().strftime(['%Y-%m-%d'])
- };
- },
- /**
- * FIXME: Huge testing hack, especially the evaluation context, rewrite + test for real before switching
- */
- test_eval: function (source, expected) {
- var match_template = '<ul>' +
- '<li>Source: %(source)s</li>' +
- '<li>Local: %(local)s</li>' +
- '<li>Remote: %(remote)s</li>' +
- '</ul>',
- fail_template = '<ul>' +
- '<li>Error: %(error)s</li>' +
- '<li>Source: %(source)s</li>' +
- '</ul>';
- try {
- // see Session.eval_context in Python
- var ctx = this.test_eval_contexts(
- ([this.context] || []).concat(source.contexts));
- if (!_.isEqual(ctx, expected.context)) {
- instance.webclient.notification.warn('Context mismatch, report to xmo',
- _.str.sprintf(match_template, {
- source: JSON.stringify(source.contexts),
- local: JSON.stringify(ctx),
- remote: JSON.stringify(expected.context)
- }), true);
- }
- } catch (e) {
- instance.webclient.notification.warn('Context fail, report to xmo',
- _.str.sprintf(fail_template, {
- error: e.message,
- source: JSON.stringify(source.contexts)
- }), true);
- }
-
- try {
- var dom = this.test_eval_domains(source.domains, this.test_eval_get_context());
- if (!_.isEqual(dom, expected.domain)) {
- instance.webclient.notification.warn('Domains mismatch, report to xmo',
- _.str.sprintf(match_template, {
- source: JSON.stringify(source.domains),
- local: JSON.stringify(dom),
- remote: JSON.stringify(expected.domain)
- }), true);
- }
- } catch (e) {
- instance.webclient.notification.warn('Domain fail, report to xmo',
- _.str.sprintf(fail_template, {
- error: e.message,
- source: JSON.stringify(source.domains)
- }), true);
- }
-
- try {
- var groups = this.test_eval_groupby(source.group_by_seq);
- if (!_.isEqual(groups, expected.group_by)) {
- instance.webclient.notification.warn('GroupBy mismatch, report to xmo',
- _.str.sprintf(match_template, {
- source: JSON.stringify(source.group_by_seq),
- local: JSON.stringify(groups),
- remote: JSON.stringify(expected.group_by)
- }), true);
- }
- } catch (e) {
- instance.webclient.notification.warn('GroupBy fail, report to xmo',
- _.str.sprintf(fail_template, {
- error: e.message,
- source: JSON.stringify(source.group_by_seq)
- }), true);
- }
- },
- test_eval_contexts: function (contexts, evaluation_context) {
- evaluation_context = evaluation_context || {};
- var self = this;
- return _(contexts).reduce(function (result_context, ctx) {
- // __eval_context evaluations can lead to some of `contexts`'s
- // values being null, skip them as well as empty contexts
- if (_.isEmpty(ctx)) { return result_context; }
- var evaluated = ctx;
- switch(ctx.__ref) {
- case 'context':
- evaluated = py.eval(ctx.__debug, evaluation_context);
- break;
- case 'compound_context':
- var eval_context = self.test_eval_contexts([ctx.__eval_context]);
- evaluated = self.test_eval_contexts(
- ctx.__contexts, _.extend({}, evaluation_context, eval_context));
- break;
- }
- // add newly evaluated context to evaluation context for following
- // siblings
- _.extend(evaluation_context, evaluated);
- return _.extend(result_context, evaluated);
- }, _.extend({}, this.user_context));
- },
- test_eval_domains: function (domains, evaluation_context) {
- var result_domain = [], self = this;
- _(domains).each(function (dom) {
- switch(dom.__ref) {
- case 'domain':
- result_domain.push.apply(
- result_domain, py.eval(dom.__debug, evaluation_context));
- break;
- case 'compound_domain':
- var eval_context = self.test_eval_contexts([dom.__eval_context]);
- result_domain.push.apply(
- result_domain, self.test_eval_domains(
- dom.__domains, _.extend(
- {}, evaluation_context, eval_context)));
- break;
- default:
- result_domain.push.apply(
- result_domain, dom);
- }
- });
- return result_domain;
- },
- test_eval_groupby: function (contexts) {
- var result_group = [], self = this;
- _(contexts).each(function (ctx) {
- var group;
- switch(ctx.__ref) {
- case 'context':
- group = py.eval(ctx.__debug).group_by;
- break;
- case 'compound_context':
- group = self.test_eval_contexts(
- ctx.__contexts, ctx.__eval_context).group_by;
- break;
- default:
- group = ctx.group_by
- }
- if (!group) { return; }
- if (typeof group === 'string') {
- result_group.push(group);
- } else if (group instanceof Array) {
- result_group.push.apply(result_group, group);
- } else {
- throw new Error('Got invalid groupby {{'
- + JSON.stringify(group) + '}}');
- }
- });
- return result_group;
- },
/**
* Executes an RPC call, registering the provided callbacks.
*
@@ -1271,22 +981,19 @@ instance.web.JsonRPC = instance.web.Class.extend(instance.web.PropertiesMixin, {
var deferred = $.Deferred();
if (! options.shadow)
this.trigger('request', url, payload);
- var request = this.rpc_function(url, payload).done(
+
+ this.rpc_function(url, payload).then(
function (response, textStatus, jqXHR) {
if (! options.shadow)
self.trigger('response', response);
if (!response.error) {
- if (url.url === '/web/session/eval_domain_and_context') {
- self.test_eval(params, response.result);
- }
deferred.resolve(response["result"], textStatus, jqXHR);
} else if (response.error.data.type === "session_invalid") {
self.uid = false;
} else {
deferred.reject(response.error, $.Event());
}
- }
- ).fail(
+ },
function(jqXHR, textStatus, errorThrown) {
if (! options.shadow)
self.trigger('response_failed', jqXHR);
diff --git a/addons/web/static/src/js/data.js b/addons/web/static/src/js/data.js
index 524a88bdc48..bbff633c687 100644
--- a/addons/web/static/src/js/data.js
+++ b/addons/web/static/src/js/data.js
@@ -61,8 +61,10 @@ instance.web.Query = instance.web.Class.extend({
return instance.session.rpc('/web/dataset/search_read', {
model: this._model.name,
fields: this._fields || false,
- domain: this._model.domain(this._filter),
- context: this._model.context(this._context),
+ domain: instance.web.pyeval.eval('domains',
+ [this._model.domain(this._filter)]),
+ context: instance.web.pyeval.eval('contexts',
+ [this._model.context(this._context)]),
offset: this._offset,
limit: this._limit,
sort: instance.web.serialize_sort(this._order_by)
@@ -121,9 +123,8 @@ instance.web.Query = instance.web.Class.extend({
var self = this;
- // FIXME: when pyeval is merged
- var ctx = instance.session.test_eval_contexts(
- [this._model.context(this._context)]);
+ var ctx = instance.web.pyeval.eval(
+ 'context', this._model.context(this._context));
return this._model.call('read_group', {
groupby: grouping,
fields: _.uniq(grouping.concat(this._fields || [])),
@@ -289,6 +290,7 @@ instance.web.Model = instance.web.Class.extend({
kwargs = args;
args = [];
}
+ instance.web.pyeval.ensure_evaluated(args, kwargs);
var debug = instance.session.debug ? '/'+this.name+':'+method : '';
return instance.session.rpc('/web/dataset/call_kw' + debug, {
model: this.name,
@@ -301,7 +303,7 @@ instance.web.Model = instance.web.Class.extend({
* Fetches a Query instance bound to this model, for searching
*
* @param {Array<String>} [fields] fields to ultimately fetch during the search
- * @returns {openerp.web.Query}
+ * @returns {instance.web.Query}
*/
query: function (fields) {
return new instance.web.Query(this, fields);
@@ -349,9 +351,11 @@ instance.web.Model = instance.web.Class.extend({
* FIXME: remove when evaluator integrated
*/
call_button: function (method, args) {
+ instance.web.pyeval.ensure_evaluated(args, {});
return instance.session.rpc('/web/dataset/call_button', {
model: this.name,
method: method,
+ // Should not be necessary anymore. Integrate remote in this?
domain_id: null,
context_id: args.length - 1,
args: args || []
@@ -606,7 +610,8 @@ instance.web.DataSet = instance.web.Class.extend(instance.web.PropertiesMixin,
return instance.session.rpc('/web/dataset/resequence', {
model: this.model,
ids: ids,
- context: this.get_context(options.context),
+ context: instance.web.pyeval.eval(
+ 'context', this.get_context(options.context)),
}).then(function (results) {
return results;
});
diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js
new file mode 100644
index 00000000000..265449f9f64
--- /dev/null
+++ b/addons/web/static/src/js/pyeval.js
@@ -0,0 +1,774 @@
+/*
+ * py.js helpers and setup
+ */
+openerp.web.pyeval = function (instance) {
+ instance.web.pyeval = {};
+
+ var obj = function () {};
+ obj.prototype = py.object;
+ var asJS = function (arg) {
+ if (arg instanceof obj) {
+ return arg.toJSON();
+ }
+ return arg;
+ };
+
+ var datetime = py.PY_call(py.object);
+
+ /**
+ * computes (Math.floor(a/b), a%b and passes that to the callback.
+ *
+ * returns the callback's result
+ */
+ var divmod = function (a, b, fn) {
+ var mod = a%b;
+ // in python, sign(a % b) === sign(b). Not in JS. If wrong side, add a
+ // round of b
+ if (mod > 0 && b < 0 || mod < 0 && b > 0) {
+ mod += b;
+ }
+ return fn(Math.floor(a/b), mod);
+ };
+ /**
+ * Passes the fractional and integer parts of x to the callback, returns
+ * the callback's result
+ */
+ var modf = function (x, fn) {
+ var mod = x%1;
+ if (mod < 0) {
+ mod += 1;
+ }
+ return fn(mod, Math.floor(x));
+ };
+ var zero = py.float.fromJSON(0);
+
+ // Port from pypy/lib_pypy/datetime.py
+ var DAYS_IN_MONTH = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+ var DAYS_BEFORE_MONTH = [null];
+ var dbm = 0;
+ for (var i=1; i<DAYS_IN_MONTH.length; ++i) {
+ DAYS_BEFORE_MONTH.push(dbm);
+ dbm += DAYS_IN_MONTH[i];
+ }
+ var is_leap = function (year) {
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+ };
+ var days_before_year = function (year) {
+ var y = year - 1;
+ return y*365 + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400);
+ };
+ var days_in_month = function (year, month) {
+ if (month === 2 && is_leap(year)) {
+ return 29;
+ }
+ return DAYS_IN_MONTH[month];
+ };
+ var days_before_month = function (year, month) {
+ var post_leap_feb = month > 2 && is_leap(year);
+ return DAYS_BEFORE_MONTH[month]
+ + (post_leap_feb ? 1 : 0);
+ };
+ var ymd2ord = function (year, month, day) {
+ var dim = days_in_month(year, month);
+ if (!(1 <= day && day <= dim)) {
+ throw new Error("ValueError: day must be in 1.." + dim);
+ }
+ return days_before_year(year)
+ + days_before_month(year, month)
+ + day;
+ };
+ var DI400Y = days_before_year(401);
+ var DI100Y = days_before_year(101);
+ var DI4Y = days_before_year(5);
+ var assert = function (bool) {
+ if (!bool) {
+ throw new Error("AssertionError");
+ }
+ };
+ var ord2ymd = function (n) {
+ --n;
+ var n400, n100, n4, n1, n0;
+ divmod(n, DI400Y, function (_n400, n) {
+ n400 = _n400;
+ divmod(n, DI100Y, function (_n100, n) {
+ n100 = _n100;
+ divmod(n, DI4Y, function (_n4, n) {
+ n4 = _n4;
+ divmod(n, 365, function (_n1, n) {
+ n1 = _n1;
+ n0 = n;
+ })
+ });
+ });
+ });
+
+ n = n0;
+ var year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1;
+ if (n1 == 4 || n100 == 100) {
+ assert(n0 === 0);
+ return {
+ year: year - 1,
+ month: 12,
+ day: 31
+ };
+ }
+
+ var leapyear = n1 === 3 && (n4 !== 24 || n100 == 3);
+ assert(leapyear == is_leap(year));
+ var month = (n + 50) >> 5;
+ var preceding = DAYS_BEFORE_MONTH[month] + ((month > 2 && leapyear) ? 1 : 0);
+ if (preceding > n) {
+ --month;
+ preceding -= DAYS_IN_MONTH[month] + ((month === 2 && leapyear) ? 1 : 0);
+ }
+ n -= preceding;
+ return {
+ year: year,
+ month: month,
+ day: n+1
+ };
+ };
+
+ /**
+ * Converts the stuff passed in into a valid date, applying overflows as needed
+ */
+ var tmxxx = function (year, month, day, hour, minute, second, microsecond) {
+ hour = hour || 0; minute = minute || 0; second = second || 0;
+ microsecond = microsecond || 0;
+
+ if (microsecond < 0 || microsecond > 999999) {
+ divmod(microsecond, 1000000, function (carry, ms) {
+ microsecond = ms;
+ second += carry
+ });
+ }
+ if (second < 0 || second > 59) {
+ divmod(second, 60, function (carry, s) {
+ second = s;
+ minute += carry;
+ });
+ }
+ if (minute < 0 || minute > 59) {
+ divmod(minute, 60, function (carry, m) {
+ minute = m;
+ hour += carry;
+ })
+ }
+ if (hour < 0 || hour > 23) {
+ divmod(hour, 24, function (carry, h) {
+ hour = h;
+ day += carry;
+ })
+ }
+ // That was easy. Now it gets muddy: the proper range for day
+ // can't be determined without knowing the correct month and year,
+ // but if day is, e.g., plus or minus a million, the current month
+ // and year values make no sense (and may also be out of bounds
+ // themselves).
+ // Saying 12 months == 1 year should be non-controversial.
+ if (month < 1 || month > 12) {
+ divmod(month-1, 12, function (carry, m) {
+ month = m + 1;
+ year += carry;
+ })
+ }
+ // Now only day can be out of bounds (year may also be out of bounds
+ // for a datetime object, but we don't care about that here).
+ // If day is out of bounds, what to do is arguable, but at least the
+ // method here is principled and explainable.
+ var dim = days_in_month(year, month);
+ if (day < 1 || day > dim) {
+ // Move day-1 days from the first of the month. First try to
+ // get off cheap if we're only one day out of range (adjustments
+ // for timezone alone can't be worse than that).
+ if (day === 0) {
+ --month;
+ if (month > 0) {
+ day = days_in_month(year, month);
+ } else {
+ --year; month=12; day=31;
+ }
+ } else if (day == dim + 1) {
+ ++month;
+ day = 1;
+ if (month > 12) {
+ month = 1;
+ ++year;
+ }
+ } else {
+ var r = ord2ymd(ymd2ord(year, month, 1) + (day - 1));
+ year = r.year;
+ month = r.month;
+ day = r.day;
+ }
+ }
+ return {
+ year: year,
+ month: month,
+ day: day,
+ hour: hour,
+ minute: minute,
+ second: second,
+ microsecond: microsecond
+ };
+ };
+ datetime.timedelta = py.type('timedelta', null, {
+ __init__: function () {
+ var args = py.PY_parseArgs(arguments, [
+ ['days', zero], ['seconds', zero], ['microseconds', zero],
+ ['milliseconds', zero], ['minutes', zero], ['hours', zero],
+ ['weeks', zero]
+ ]);
+
+ var d = 0, s = 0, m = 0;
+ var days = args.days.toJSON() + args.weeks.toJSON() * 7;
+ var seconds = args.seconds.toJSON()
+ + args.minutes.toJSON() * 60
+ + args.hours.toJSON() * 3600;
+ var microseconds = args.microseconds.toJSON()
+ + args.milliseconds.toJSON() * 1000;
+
+ // Get rid of all fractions, and normalize s and us.
+ // Take a deep breath <wink>.
+ var daysecondsfrac = modf(days, function (dayfrac, days) {
+ d = days;
+ if (dayfrac) {
+ return modf(dayfrac * 24 * 3600, function (dsf, dsw) {
+ s = dsw;
+ return dsf;
+ });
+ }
+ return 0;
+ });
+
+ var secondsfrac = modf(seconds, function (sf, s) {
+ seconds = s;
+ return sf + daysecondsfrac;
+ });
+ divmod(seconds, 24*3600, function (days, seconds) {
+ d += days;
+ s += seconds
+ });
+ // seconds isn't referenced again before redefinition
+
+ microseconds += secondsfrac * 1e6;
+ divmod(microseconds, 1000000, function (seconds, microseconds) {
+ divmod(seconds, 24*3600, function (days, seconds) {
+ d += days;
+ s += seconds;
+ m += Math.round(microseconds);
+ });
+ });
+
+ // Carrying still possible here?
+
+ this.days = d;
+ this.seconds = s;
+ this.microseconds = m;
+ },
+ __str__: function () {
+ var hh, mm, ss;
+ divmod(this.seconds, 60, function (m, s) {
+ divmod(m, 60, function (h, m) {
+ hh = h;
+ mm = m;
+ ss = s;
+ });
+ });
+ var s = _.str.sprintf("%d:%02d:%02d", hh, mm, ss);
+ if (this.days) {
+ s = _.str.sprintf("%d day%s, %s",
+ this.days,
+ (this.days != 1 && this.days != -1) ? 's' : '',
+ s);
+ }
+ if (this.microseconds) {
+ s = _.str.sprintf("%s.%06d", s, this.microseconds);
+ }
+ return py.str.fromJSON(s);
+ },
+ __eq__: function (other) {
+ if (!py.PY_isInstance(other, datetime.timedelta)) {
+ return py.False;
+ }
+ return (this.days === other.days
+ && this.seconds === other.seconds
+ && this.microseconds === other.microseconds)
+ ? py.True : py.False;
+ },
+ __add__: function (other) {
+ if (!py.PY_isInstance(other, datetime.timedelta)) {
+ return py.NotImplemented;
+ }
+ return py.PY_call(datetime.timedelta, [
+ py.float.fromJSON(this.days + other.days),
+ py.float.fromJSON(this.seconds + other.seconds),
+ py.float.fromJSON(this.microseconds + other.microseconds)
+ ]);
+ },
+ __radd__: function (other) { return this.__add__(other); },
+ __sub__: function (other) {
+ if (!py.PY_isInstance(other, datetime.timedelta)) {
+ return py.NotImplemented;
+ }
+ return py.PY_call(datetime.timedelta, [
+ py.float.fromJSON(this.days - other.days),
+ py.float.fromJSON(this.seconds - other.seconds),
+ py.float.fromJSON(this.microseconds - other.microseconds)
+ ]);
+ },
+ __rsub__: function (other) {
+ if (!py.PY_isInstance(other, datetime.timedelta)) {
+ return py.NotImplemented;
+ }
+ return this.__neg__().__add__(other);
+ },
+ __neg__: function () {
+ return py.PY_call(datetime.timedelta, [
+ py.float.fromJSON(-this.days),
+ py.float.fromJSON(-this.seconds),
+ py.float.fromJSON(-this.microseconds)
+ ]);
+ },
+ __pos__: function () { return this; },
+ __mul__: function (other) {
+ if (!py.PY_isInstance(other, py.float)) {
+ return py.NotImplemented;
+ }
+ var n = other.toJSON();
+ return py.PY_call(datetime.timedelta, [
+ py.float.fromJSON(this.days * n),
+ py.float.fromJSON(this.seconds * n),
+ py.float.fromJSON(this.microseconds * n)
+ ]);
+ },
+ __rmul__: function (other) { return this.__mul__(other); },
+ __div__: function (other) {
+ if (!py.PY_isInstance(other, py.float)) {
+ return py.NotImplemented;
+ }
+ var usec = ((this.days * 24 * 3600) + this.seconds) * 1000000
+ + this.microseconds;
+ return py.PY_call(
+ datetime.timedelta, [
+ zero, zero, py.float.fromJSON(usec / other.toJSON())]);
+ },
+ __floordiv__: function (other) { return this.__div__(other); },
+ total_seconds: function () {
+ return py.float.fromJSON(
+ this.days * 86400
+ + this.seconds
+ + this.microseconds / 1000000)
+ },
+ __nonzero__: function () {
+ return (!!this.days || !!this.seconds || !!this.microseconds)
+ ? py.True
+ : py.False;
+ }
+ });
+ datetime.datetime = py.type('datetime', null, {
+ __init__: function () {
+ var zero = py.float.fromJSON(0);
+ var args = py.PY_parseArgs(arguments, [
+ 'year', 'month', 'day',
+ ['hour', zero], ['minute', zero], ['second', zero],
+ ['microsecond', zero], ['tzinfo', py.None]
+ ]);
+ for(var key in args) {
+ if (!args.hasOwnProperty(key)) { continue; }
+ this[key] = asJS(args[key]);
+ }
+ },
+ strftime: function () {
+ var self = this;
+ var args = py.PY_parseArgs(arguments, 'format');
+ return py.str.fromJSON(args.format.toJSON()
+ .replace(/%([A-Za-z])/g, function (m, c) {
+ switch (c) {
+ case 'Y': return self.year;
+ case 'm': return _.str.sprintf('%02d', self.month);
+ case 'd': return _.str.sprintf('%02d', self.day);
+ case 'H': return _.str.sprintf('%02d', self.hour);
+ case 'M': return _.str.sprintf('%02d', self.minute);
+ case 'S': return _.str.sprintf('%02d', self.second);
+ }
+ throw new Error('ValueError: No known conversion for ' + m);
+ }));
+ },
+ now: py.classmethod.fromJSON(function () {
+ var d = new Date();
+ return py.PY_call(datetime.datetime,
+ [d.getFullYear(), d.getMonth() + 1, d.getDate(),
+ d.getHours(), d.getMinutes(), d.getSeconds(),
+ d.getMilliseconds() * 1000]);
+ }),
+ today: py.classmethod.fromJSON(function () {
+ var d = new Date();
+ return py.PY_call(datetime.datetime,
+ [d.getFullYear(), d.getMonth() + 1, d.getDate()]);
+ }),
+ combine: py.classmethod.fromJSON(function () {
+ var args = py.PY_parseArgs(arguments, 'date time');
+ return py.PY_call(datetime.datetime, [
+ py.PY_getAttr(args.date, 'year'),
+ py.PY_getAttr(args.date, 'month'),
+ py.PY_getAttr(args.date, 'day'),
+ py.PY_getAttr(args.time, 'hour'),
+ py.PY_getAttr(args.time, 'minute'),
+ py.PY_getAttr(args.time, 'second')
+ ]);
+ })
+ });
+ datetime.date = py.type('date', null, {
+ __init__: function () {
+ var args = py.PY_parseArgs(arguments, 'year month day');
+ this.year = asJS(args.year);
+ this.month = asJS(args.month);
+ this.day = asJS(args.day);
+ },
+ strftime: function () {
+ var self = this;
+ var args = py.PY_parseArgs(arguments, 'format');
+ return py.str.fromJSON(args.format.toJSON()
+ .replace(/%([A-Za-z])/g, function (m, c) {
+ switch (c) {
+ case 'Y': return self.year;
+ case 'm': return _.str.sprintf('%02d', self.month);
+ case 'd': return _.str.sprintf('%02d', self.day);
+ }
+ throw new Error('ValueError: No known conversion for ' + m);
+ }));
+ },
+ today: py.classmethod.fromJSON(function () {
+ var d = new Date();
+ return py.PY_call(
+ datetime.date, [d.getFullYear(), d.getMonth() + 1, d.getDate()]);
+ }),
+ __eq__: function (other) {
+ return (this.year === other.year
+ && this.month === other.month
+ && this.day === other.day)
+ ? py.True : py.False;
+ },
+ __add__: function (other) {
+ if (!py.PY_isInstance(other, datetime.timedelta)) {
+ return py.NotImplemented;
+ }
+ var s = tmxxx(this.year, this.month, this.day + other.days);
+ return datetime.date.fromJSON(s.year, s.month, s.day);
+ },
+ __radd__: function (other) { return this.__add__(other); },
+ __sub__: function (other) {
+ if (py.PY_isInstance(other, datetime.timedelta)) {
+ return this.__add__(other.__neg__());
+ }
+ if (py.PY_isInstance(other, datetime.date)) {
+ // FIXME: getattr and sub API methods
+ return py.PY_call(datetime.timedelta, [
+ py.PY_subtract(
+ py.PY_call(py.PY_getAttr(this, 'toordinal')),
+ py.PY_call(py.PY_getAttr(other, 'toordinal')))
+ ]);
+ }
+ return py.NotImplemented;
+ },
+ toordinal: function () {
+ return py.float.fromJSON(ymd2ord(this.year, this.month, this.day));
+ },
+ fromJSON: function (year, month, day) {
+ return py.PY_call(datetime.date, [year, month, day])
+ }
+ });
+ datetime.time = py.type('time', null, {
+ __init__: function () {
+ var zero = py.float.fromJSON(0);
+ var args = py.PY_parseArgs(arguments, [
+ ['hour', zero], ['minute', zero], ['second', zero], ['microsecond', zero],
+ ['tzinfo', py.None]
+ ]);
+
+ for(var k in args) {
+ if (!args.hasOwnProperty(k)) { continue; }
+ this[k] = asJS(args[k]);
+ }
+ }
+ });
+ var time = py.PY_call(py.object);
+ time.strftime = py.PY_def.fromJSON(function () {
+ var args = py.PY_parseArgs(arguments, 'format');
+ var dt_class = py.PY_getAttr(datetime, 'datetime');
+ var d = py.PY_call(py.PY_getAttr(dt_class, 'now'));
+ return py.PY_call(py.PY_getAttr(d, 'strftime'), [args.format]);
+ });
+
+ var relativedelta = py.type('relativedelta', null, {
+ __init__: function () {
+ this.ops = py.PY_parseArgs(arguments,
+ '* year month day hour minute second microsecond '
+ + 'years months weeks days hours minutes secondes microseconds '
+ + 'weekday leakdays yearday nlyearday');
+ },
+ __add__: function (other) {
+ if (!py.PY_isInstance(other, datetime.date)) {
+ return py.NotImplemented;
+ }
+ // TODO: test this whole mess
+ var year = asJS(this.ops.year) || asJS(other.year);
+ if (asJS(this.ops.years)) {
+ year += asJS(this.ops.years);
+ }
+
+ var month = asJS(this.ops.month) || asJS(other.month);
+ if (asJS(this.ops.months)) {
+ month += asJS(this.ops.months);
+ // FIXME: no divmod in JS?
+ while (month < 1) {
+ year -= 1;
+ month += 12;
+ }
+ while (month > 12) {
+ year += 1;
+ month -= 12;
+ }
+ }
+
+ var lastMonthDay = new Date(year, month, 0).getDate();
+ var day = asJS(this.ops.day) || asJS(other.day);
+ if (day > lastMonthDay) { day = lastMonthDay; }
+ var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);
+ if (days_offset) {
+ day = new Date(year, month-1, day + days_offset).getDate();
+ }
+ // TODO: leapdays?
+ // TODO: hours, minutes, seconds? Not used in XML domains
+ // TODO: weekday?
+ // FIXME: use date.replace
+ return py.PY_call(datetime.date, [
+ py.float.fromJSON(year),
+ py.float.fromJSON(month),
+ py.float.fromJSON(day)
+ ]);
+ },
+ __radd__: function (other) {
+ return this.__add__(other);
+ },
+
+ __sub__: function (other) {
+ if (!py.PY_isInstance(other, datetime.date)) {
+ return py.NotImplemented;
+ }
+ // TODO: test this whole mess
+ var year = asJS(this.ops.year) || asJS(other.year);
+ if (asJS(this.ops.years)) {
+ year -= asJS(this.ops.years);
+ }
+
+ var month = asJS(this.ops.month) || asJS(other.month);
+ if (asJS(this.ops.months)) {
+ month -= asJS(this.ops.months);
+ // FIXME: no divmod in JS?
+ while (month < 1) {
+ year -= 1;
+ month += 12;
+ }
+ while (month > 12) {
+ year += 1;
+ month -= 12;
+ }
+ }
+
+ var lastMonthDay = new Date(year, month, 0).getDate();
+ var day = asJS(this.ops.day) || asJS(other.day);
+ if (day > lastMonthDay) { day = lastMonthDay; }
+ var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);
+ if (days_offset) {
+ day = new Date(year, month-1, day - days_offset).getDate();
+ }
+ // TODO: leapdays?
+ // TODO: hours, minutes, seconds? Not used in XML domains
+ // TODO: weekday?
+ return py.PY_call(datetime.date, [
+ py.float.fromJSON(year),
+ py.float.fromJSON(month),
+ py.float.fromJSON(day)
+ ]);
+ },
+ __rsub__: function (other) {
+ return this.__sub__(other);
+ }
+ });
+
+ var eval_contexts = function (contexts, evaluation_context) {
+ evaluation_context = evaluation_context || {};
+ return _(contexts).reduce(function (result_context, ctx) {
+ // __eval_context evaluations can lead to some of `contexts`'s
+ // values being null, skip them as well as empty contexts
+ if (_.isEmpty(ctx)) { return result_context; }
+ if (_.isString(ctx)) {
+ // wrap raw strings in context
+ ctx = { __ref: 'context', __debug: ctx };
+ }
+ var evaluated = ctx;
+ switch(ctx.__ref) {
+ case 'context':
+ evaluation_context.context = py.dict.fromJSON(evaluation_context);
+ evaluated = py.eval(ctx.__debug, evaluation_context);
+ break;
+ case 'compound_context':
+ var eval_context = eval_contexts([ctx.__eval_context]);
+ evaluated = eval_contexts(
+ ctx.__contexts, _.extend({}, evaluation_context, eval_context));
+ break;
+ }
+ // add newly evaluated context to evaluation context for following
+ // siblings
+ _.extend(evaluation_context, evaluated);
+ return _.extend(result_context, evaluated);
+ }, _.extend({}, instance.session.user_context));
+ };
+ var eval_domains = function (domains, evaluation_context) {
+ var result_domain = [];
+ _(domains).each(function (domain) {
+ if (_.isString(domain)) {
+ // wrap raw strings in domain
+ domain = { __ref: 'domain', __debug: domain };
+ }
+ switch(domain.__ref) {
+ case 'domain':
+ evaluation_context.context = py.dict.fromJSON(evaluation_context);
+ result_domain.push.apply(
+ result_domain, py.eval(domain.__debug, evaluation_context));
+ break;
+ case 'compound_domain':
+ var eval_context = eval_contexts([domain.__eval_context]);
+ result_domain.push.apply(
+ result_domain, eval_domains(
+ domain.__domains, _.extend(
+ {}, evaluation_context, eval_context)));
+ break;
+ default:
+ result_domain.push.apply(result_domain, domain);
+ }
+ });
+ return result_domain;
+ };
+ var eval_groupbys = function (contexts, evaluation_context) {
+ var result_group = [];
+ _(contexts).each(function (ctx) {
+ if (_.isString(ctx)) {
+ // wrap raw strings in context
+ ctx = { __ref: 'context', __debug: ctx };
+ }
+ var group;
+ var evaluated = ctx;
+ switch(ctx.__ref) {
+ case 'context':
+ evaluation_context.context = py.dict.fromJSON(evaluation_context);
+ evaluated = py.eval(ctx.__debug, evaluation_context);
+ break;
+ case 'compound_context':
+ var eval_context = eval_contexts([ctx.__eval_context]);
+ evaluated = eval_contexts(
+ ctx.__contexts, _.extend({}, evaluation_context, eval_context));
+ break;
+ }
+ group = evaluated.group_by;
+ if (!group) { return; }
+ if (typeof group === 'string') {
+ result_group.push(group);
+ } else if (group instanceof Array) {
+ result_group.push.apply(result_group, group);
+ } else {
+ throw new Error('Got invalid groupby {{'
+ + JSON.stringify(group) + '}}');
+ }
+ _.extend(evaluation_context, evaluated);
+ });
+ return result_group;
+ };
+
+ instance.web.pyeval.context = function () {
+ return {
+ uid: py.float.fromJSON(instance.session.uid),
+ datetime: datetime,
+ time: time,
+ relativedelta: relativedelta,
+ current_date: py.PY_call(
+ time.strftime, [py.str.fromJSON('%Y-%m-%d')]),
+ };
+ };
+
+ /**
+ * @param {String} type "domains", "contexts" or "groupbys"
+ * @param {Array} object domains or contexts to evaluate
+ * @param {Object} [context] evaluation context
+ */
+ instance.web.pyeval.eval = function (type, object, context) {
+ context = _.extend(instance.web.pyeval.context(), context || {});
+ context['context'] = py.dict.fromJSON(context);
+
+ //noinspection FallthroughInSwitchStatementJS
+ switch(type) {
+ case 'context': object = [object];
+ case 'contexts': return eval_contexts(object, context);
+ case 'domain': object = [object];
+ case 'domains': return eval_domains(object, context);
+ case 'groupbys': return eval_groupbys(object, context);
+ }
+ throw new Error("Unknow evaluation type " + type)
+ };
+
+ var eval_arg = function (arg) {
+ if (typeof arg !== 'object' || !arg.__ref) { return arg; }
+ switch(arg.__ref) {
+ case 'domain': case 'compound_domain':
+ return instance.web.pyeval.eval('domains', [arg]);
+ case 'context': case 'compound_context':
+ return instance.web.pyeval.eval('contexts', [arg]);
+ default:
+ throw new Error(instance.web._t("Unknown nonliteral type " + arg.__ref));
+ }
+ };
+ /**
+ * If args or kwargs are unevaluated contexts or domains (compound or not),
+ * evaluated them in-place.
+ *
+ * Potentially mutates both parameters.
+ *
+ * @param args
+ * @param kwargs
+ */
+ instance.web.pyeval.ensure_evaluated = function (args, kwargs) {
+ for (var i=0; i<args.length; ++i) {
+ args[i] = eval_arg(args[i]);
+ }
+ for (var k in kwargs) {
+ if (!kwargs.hasOwnProperty(k)) { continue; }
+ kwargs[k] = eval_arg(kwargs[k]);
+ }
+ };
+ instance.web.pyeval.eval_domains_and_contexts = function (source) {
+ return new $.Deferred(function (d) {setTimeout(function () {
+ try {
+ var contexts = ([instance.session.user_context] || []).concat(source.contexts);
+ // see Session.eval_context in Python
+ d.resolve({
+ context: instance.web.pyeval.eval('contexts', contexts),
+ domain: instance.web.pyeval.eval('domains', source.domains),
+ group_by: instance.web.pyeval.eval('groupbys', source.group_by_seq || [])
+ });
+ } catch (e) {
+ d.resolve({ error: {
+ code: 400,
+ message: instance.web._t("Evaluation Error"),
+ data: {
+ type: 'local_exception',
+ debug: _.str.sprintf(
+ instance.web._t("Local evaluation failure\n%s\n\n%s"),
+ e.message, JSON.stringify(source))
+ }
+ }});
+ }
+ }, 0); });
+ }
+};
diff --git a/addons/web/static/src/js/search.js b/addons/web/static/src/js/search.js
index 88d45793173..5b59c7d6912 100644
--- a/addons/web/static/src/js/search.js
+++ b/addons/web/static/src/js/search.js
@@ -341,17 +341,19 @@ instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.Sea
if (this.headless) {
this.ready.resolve();
} else {
- var load_view = this.rpc("/web/searchview/load", {
+ var load_view = this.rpc("/web/view/load", {
model: this.model,
view_id: this.view_id,
- context: this.dataset.get_context() });
-
- $.when(load_view)
- .then(function(r) {
- self.search_view_loaded(r)
- }, function () {
- self.ready.reject.apply(null, arguments);
- });
+ view_type: 'search',
+ context: instance.web.pyeval.eval(
+ 'context', this.dataset.get_context())
+ });
+
+ $.when(load_view).then(function (r) {
+ return self.search_view_loaded(r)
+ }).fail(function () {
+ self.ready.reject.apply(null, arguments);
+ });
}
instance.web.bus.on('click', this, function(ev) {
@@ -615,16 +617,16 @@ instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.Sea
search_view_loaded: function(data) {
var self = this;
- this.fields_view = data.fields_view;
- if (data.fields_view.type !== 'search' ||
- data.fields_view.arch.tag !== 'search') {
+ this.fields_view = data;
+ if (data.type !== 'search' ||
+ data.arch.tag !== 'search') {
throw new Error(_.str.sprintf(
"Got non-search view after asking for a search view: type %s, arch root %s",
- data.fields_view.type, data.fields_view.arch.tag));
+ data.type, data.arch.tag));
}
this.make_widgets(
- data.fields_view['arch'].children,
- data.fields_view.fields);
+ data['arch'].children,
+ data.fields);
this.add_common_inputs();
@@ -632,6 +634,7 @@ instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.Sea
var drawer_started = $.when.apply(
null, _(this.select_for_drawer()).invoke(
'appendTo', this.$('.oe_searchview_drawer')));
+
// load defaults
var defaults_fetched = $.when.apply(null, _(this.inputs).invoke(
@@ -1506,16 +1509,10 @@ instance.web.search.CustomFilters = instance.web.search.Input.extend({
this.$el.on('click', 'h4', function () {
self.$el.toggleClass('oe_opened');
});
- // FIXME: local eval of domain and context to get rid of special endpoint
- return this.rpc('/web/searchview/get_filters', {
- model: this.view.model
- })
+ return this.model.call('get_filters', [this.view.model])
.then(this.proxy('set_filters'))
- .then(function () {
- self.is_ready.resolve(null);
- }, function () {
- self.is_ready.reject();
- });
+ .done(function () { self.is_ready.resolve(); })
+ .fail(function () { self.is_ready.reject.apply(self.is_ready, arguments); });
},
/**
* Special implementation delaying defaults until CustomFilters is loaded
@@ -1614,7 +1611,7 @@ instance.web.search.CustomFilters = instance.web.search.Input.extend({
var set_as_default = this.$('#oe_searchview_custom_default').prop('checked');
var search = this.view.build_search_data();
- this.rpc('/web/session/eval_domain_and_context', {
+ instance.web.pyeval.eval_domains_and_contexts({
domains: search.domains,
contexts: search.contexts,
group_by_seq: search.groupbys || []
@@ -1708,10 +1705,10 @@ instance.web.search.Advanced = instance.web.search.Input.extend({
});
return $.when(
this._super(),
- this.rpc("/web/searchview/fields_get", {model: this.view.model}).done(function(data) {
+ new instance.web.Model(this.view.model).call('fields_get').done(function(data) {
self.fields = _.extend({
id: { string: 'ID', type: 'id' }
- }, data.fields);
+ }, data);
})).done(function () {
self.append_proposition();
});
diff --git a/addons/web/static/src/js/testing.js b/addons/web/static/src/js/testing.js
index bf39f543734..5aeeeb4de78 100644
--- a/addons/web/static/src/js/testing.js
+++ b/addons/web/static/src/js/testing.js
@@ -2,7 +2,8 @@
openerp.testing = {};
(function (testing) {
var dependencies = {
- corelib: [],
+ pyeval: [],
+ corelib: ['pyeval'],
coresetup: ['corelib'],
data: ['corelib', 'coresetup'],
dates: [],
@@ -270,6 +271,9 @@ openerp.testing = {};
openerp.web[module](instance);
});
}
+ if (instance.session) {
+ instance.session.uid = 42;
+ }
if (_.isNumber(opts.asserts)) {
expect(opts.asserts);
}
diff --git a/addons/web/static/src/js/view_form.js b/addons/web/static/src/js/view_form.js
index 06c1a3d989b..b4f59499b9b 100644
--- a/addons/web/static/src/js/view_form.js
+++ b/addons/web/static/src/js/view_form.js
@@ -436,26 +436,26 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM
var method = call[1];
if (!_.str.trim(call[2])) {
- return {method: method, args: [], context_index: null}
+ return {method: method, args: []}
}
var argument_replacement = {
'False': function () {return false;},
'True': function () {return true;},
'None': function () {return null;},
- 'context': function (i) {
- context_index = i;
- var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
- return ctx;
+ 'context': function () {
+ return new instance.web.CompoundContext(
+ self.dataset.get_context(),
+ widget.build_context() ? widget.build_context() : {});
}
};
- var parent_fields = null, context_index = null;
+ var parent_fields = null;
var args = _.map(call[2].split(','), function (a, i) {
var field = _.str.trim(a);
// literal constant or context
if (field in argument_replacement) {
- return argument_replacement[field](i);
+ return argument_replacement[field]();
}
// literal number
if (/^-?\d+(\.\d+)?$/.test(field)) {
@@ -490,8 +490,7 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM
return {
method: method,
- args: args,
- context_index: context_index
+ args: args
};
},
do_onchange: function(widget, processed) {
@@ -510,18 +509,15 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM
var on_change = widget.node.attrs.on_change;
if (on_change) {
var change_spec = self.parse_on_change(on_change, widget);
- def = self.rpc('/web/dataset/onchange', {
- model: self.dataset.model,
- method: change_spec.method,
- args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
- context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
- });
+ var id = [self.datarecord.id == null ? [] : [self.datarecord.id]];
+ def = new instance.web.Model(self.dataset.model).call(
+ change_spec.method, id.concat(change_spec.args));
} else {
def = $.when({});
}
return def.then(function(response) {
if (widget.field['change_default']) {
- var fieldname = widget.name
+ var fieldname = widget.name;
var value_;
if (response.value && (fieldname in response.value)) {
// Use value from onchange if onchange executed
@@ -533,11 +529,9 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM
var condition = fieldname + '=' + value_;
if (value_) {
- return self.rpc('/web/dataset/call', {
- model: 'ir.values',
- method: 'get_defaults',
- args: [self.model, condition]
- }).then(function (results) {
+ return new instance.web.Model('ir.values').call(
+ 'get_defaults', [self.model, condition]
+ ).then(function (results) {
if (!results.length) {
return response;
}
@@ -4591,7 +4585,7 @@ instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend
var self = this;
this.init_dataset();
if (this.options.initial_view == "search") {
- self.rpc('/web/session/eval_domain_and_context', {
+ instance.web.pyeval.eval_domains_and_contexts({
domains: [],
contexts: [this.context]
}).done(function (results) {
@@ -4664,7 +4658,7 @@ instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend
},
do_search: function(domains, contexts, groupbys) {
var self = this;
- this.rpc('/web/session/eval_domain_and_context', {
+ instance.web.pyeval.eval_domains_and_contexts({
domains: domains || [],
contexts: contexts || [],
group_by_seq: groupbys || []
diff --git a/addons/web/static/src/js/view_tree.js b/addons/web/static/src/js/view_tree.js
index 8265be77ba1..4d08da385fd 100644
--- a/addons/web/static/src/js/view_tree.js
+++ b/addons/web/static/src/js/view_tree.js
@@ -44,7 +44,8 @@ instance.web.TreeView = instance.web.View.extend(/** @lends instance.web.TreeVie
view_id: this.view_id,
view_type: "tree",
toolbar: this.view_manager ? !!this.view_manager.sidebar : false,
- context: this.dataset.get_context()
+ context: instance.web.pyeval.eval(
+ 'context', this.dataset.get_context())
}).done(this.on_loaded);
},
/**
@@ -227,8 +228,9 @@ instance.web.TreeView = instance.web.View.extend(/** @lends instance.web.TreeVie
return this.rpc('/web/treeview/action', {
id: id,
model: this.dataset.model,
- context: new instance.web.CompoundContext(
- this.dataset.get_context(), local_context)
+ context: instance.web.pyeval.eval(
+ 'context', new instance.web.CompoundContext(
+ this.dataset.get_context(), local_context))
}).then(function (actions) {
if (!actions.length) { return; }
var action = actions[0][2];
@@ -236,7 +238,7 @@ instance.web.TreeView = instance.web.View.extend(/** @lends instance.web.TreeVie
if (action.context) {
c.add(action.context);
}
- return self.rpc('/web/session/eval_domain_and_context', {
+ return instance.web.pyeval.eval_domains_and_contexts({
contexts: [c], domains: []
}).then(function (res) {
action.context = res.context;
diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js
index 600a0b065c1..d7dcd590218 100644
--- a/addons/web/static/src/js/views.js
+++ b/addons/web/static/src/js/views.js
@@ -256,7 +256,9 @@ instance.web.ActionManager = instance.web.Widget.extend({
on_close: function() {},
action_menu_id: null,
});
- if (_.isString(action) && instance.web.client_actions.contains(action)) {
+ if (action === false) {
+ action = { type: 'ir.actions.act_window_close' };
+ } else if (_.isString(action) && instance.web.client_actions.contains(action)) {
var action_client = { type: "ir.actions.client", tag: action, params: {} };
return this.do_action(action_client, options);
} else if (_.isNumber(action) || _.isString(action)) {
@@ -265,6 +267,17 @@ instance.web.ActionManager = instance.web.Widget.extend({
return self.do_action(result, options);
});
}
+
+ // Ensure context & domain are evaluated and can be manipulated/used
+ if (action.context) {
+ action.context = instance.web.pyeval.eval(
+ 'context', action.context);
+ }
+ if (action.domain) {
+ action.domain = instance.web.pyeval.eval(
+ 'domain', action.domain);
+ }
+
if (!action.type) {
console.error("No type for action", action);
return $.Deferred().reject();
@@ -382,6 +395,7 @@ instance.web.ActionManager = instance.web.Widget.extend({
options.on_close();
}
this.dialog_stop();
+ return $.when();
},
ir_actions_server: function (action, options) {
var self = this;
@@ -395,29 +409,36 @@ instance.web.ActionManager = instance.web.Widget.extend({
ir_actions_report_xml: function(action, options) {
var self = this;
instance.web.blockUI();
- self.rpc("/web/session/eval_domain_and_context", {
+ return instance.web.pyeval.eval_domains_and_contexts({
contexts: [action.context],
domains: []
- }).done(function(res) {
+ }).then(function(res) {
action = _.clone(action);
action.context = res.context;
var c = instance.webclient.crashmanager;
- self.session.get_file({
- url: '/web/report',
- data: {action: JSON.stringify(action)},
- complete: instance.web.unblockUI,
- success: function(){
- if (!self.dialog) {
- options.on_close();
+ return $.Deferred(function (d) {
+ self.session.get_file({
+ url: '/web/report',
+ data: {action: JSON.stringify(action)},
+ complete: instance.web.unblockUI,
+ success: function(){
+ if (!self.dialog) {
+ options.on_close();
+ }
+ self.dialog_stop();
+ d.resolve();
+ },
+ error: function () {
+ c.rpc_error.apply(c, arguments);
+ d.reject();
}
- self.dialog_stop();
- },
- error: c.rpc_error.bind(c)
- })
+ })
+ });
});
},
ir_actions_act_url: function (action) {
window.open(action.url, action.target === 'self' ? '_self' : '_blank');
+ return $.when();
},
});
@@ -666,7 +687,7 @@ instance.web.ViewManager = instance.web.Widget.extend({
var self = this,
controller = this.views[this.active_view].controller,
action_context = this.action.context || {};
- this.rpc('/web/session/eval_domain_and_context', {
+ instance.web.pyeval.eval_domains_and_contexts({
domains: [this.action.domain || []].concat(domains || []),
contexts: [action_context].concat(contexts || []),
group_by_seq: groupbys || []
@@ -880,7 +901,11 @@ instance.web.ViewManagerAction = instance.web.ViewManager.extend({
nested: true,
}
};
- this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI });
+ this.session.get_file({
+ url: '/web/report',
+ data: {action: JSON.stringify(action)},
+ complete: instance.web.unblockUI
+ });
}
break;
default:
@@ -1069,14 +1094,17 @@ instance.web.Sidebar = instance.web.Widget.extend({
active_id: ids[0],
active_ids: ids,
active_model: self.getParent().dataset.model
- };
+ };
+ var c = instance.web.pyeval.eval('context',
+ new instance.web.CompoundContext(
+ sidebar_eval_context, active_ids_context));
self.rpc("/web/action/load", {
action_id: item.action.id,
- context: active_ids_context,
- eval_context: new instance.web.CompoundContext(sidebar_eval_context, active_ids_context),
+ context: c
}).done(function(result) {
- console.log(result.context);
- result.context = new instance.web.CompoundContext(result.context || {}, active_ids_context);
+ result.context = new instance.web.CompoundContext(
+ result.context || {}, active_ids_context)
+ .set_eval_context(c);
result.flags = result.flags || {};
result.flags.new_window = true;
self.do_action(result, {
@@ -1137,7 +1165,6 @@ instance.web.Sidebar = instance.web.Widget.extend({
}
},
on_attachment_delete: function(e) {
- var self = this;
e.preventDefault();
e.stopPropagation();
var self = this;
@@ -1182,7 +1209,8 @@ instance.web.View = instance.web.Widget.extend({
"view_id": this.view_id,
"view_type": this.view_type,
toolbar: !!this.options.$sidebar,
- context: this.dataset.get_context(context)
+ context: instance.web.pyeval.eval(
+ 'context', this.dataset.get_context(context))
});
}
return view_loaded.then(function(r) {
@@ -1226,8 +1254,7 @@ instance.web.View = instance.web.Widget.extend({
};
var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
- var handler = function (r) {
- var action = r;
+ var handler = function (action) {
if (action && action.constructor == Object) {
var ncontext = new instance.web.CompoundContext(context);
if (record_id) {
@@ -1238,18 +1265,10 @@ instance.web.View = instance.web.Widget.extend({
});
}
ncontext.add(action.context || {});
- return self.rpc('/web/session/eval_domain_and_context', {
- contexts: [ncontext],
- domains: []
- }).then(function (results) {
- action.context = results.context;
- /* niv: previously we were overriding once more with action_data.context,
- * I assumed this was not a correct behavior and removed it
- */
- return self.do_action(action, {
- on_close: result_handler,
- });
- }, null);
+ action.context = ncontext;
+ return self.do_action(action, {
+ on_close: result_handler,
+ });
} else {
self.do_action({"type":"ir.actions.act_window_close"});
return result_handler();
@@ -1271,11 +1290,15 @@ instance.web.View = instance.web.Widget.extend({
}
}
args.push(context);
- return dataset.call_button(action_data.name, args).done(handler);
+ return dataset.call_button(action_data.name, args).then(handler);
} else if (action_data.type=="action") {
- return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).done(handler);
+ return this.rpc('/web/action/load', {
+ action_id: action_data.name,
+ context: instance.web.pyeval.eval('context', context),
+ do_not_eval: true
+ }).then(handler);
} else {
- return dataset.exec_workflow(record_id, action_data.name).done(handler);
+ return dataset.exec_workflow(record_id, action_data.name).then(handler);
}
},
/**