[MERGE] forward port branch saas-16 up to 4ac347735d

This commit is contained in:
Christophe Simonis
2017-08-28 14:49:11 +02:00
40 changed files with 909 additions and 103 deletions
@@ -201,7 +201,10 @@ var StatementAction = Widget.extend(ControlPanelMixin, {
_.each(self.model.lines, function (line, _handle) {
if (line.mode !== 'inactive' && _handle !== handle) {
self.model.changeMode(_handle, 'inactive');
self._getWidget(_handle).update(line);
var widget = self._getWidget(_handle);
if (widget) {
widget.update(line);
}
}
});
}
@@ -1005,7 +1005,6 @@ QUnit.module('account', {
clientAction.destroy();
});
QUnit.test('Reconciliation pager', function (assert) {
assert.expect(6);
@@ -1219,9 +1218,11 @@ QUnit.module('account', {
assert.strictEqual(clientAction.$('.o_reconciliation_line').length, 10, "should display 10 lines");
assert.strictEqual(clientAction.$('.js_load_more:visible').length, 1, "should display the load more button");
clientAction.$('.accounting_view:has(.o_reconcile:visible) thead .cell_action').click();
clientAction.$('.o_reconcile:visible').click();
assert.strictEqual(clientAction.$('.o_reconcile:visible').length, 0, "should remove the reconciled line");
assert.strictEqual(clientAction.$('.o_reconciliation_line').length, 10, "should load one line to complete the 10");
clientAction.$('thead .cell_action:eq(1)').click();
clientAction.$('.js_load_more').click();
assert.strictEqual(clientAction.$('.o_reconciliation_line').length, 11, "should load the last record");
assert.strictEqual(clientAction.$('.js_load_more:visible').length, 0, "should hide the load more button");
@@ -77,13 +77,7 @@ var BarcodeEvents = core.Class.extend(mixins.PropertiesMixin, {
'bubbles': old_event.bubbles,
'cancelable': old_event.cancelable,
};
try {
new_event = new Event("keypress", params);
} catch(error) {
// For IE >= 9, use new CustomEvent(), instead of new Event()
new_event = new CustomEvent("keypress", params);
}
new_event = $.Event('keypress', params);
new_event.viewArg = old_event.viewArg;
new_event.ctrl = old_event.ctrl;
new_event.alt = old_event.alt;
@@ -96,7 +90,7 @@ var BarcodeEvents = core.Class.extend(mixins.PropertiesMixin, {
new_event.which = old_event.which;
new_event.dispatched_by_barcode_reader = true;
old_event.target.dispatchEvent(new_event);
$(old_event.target).trigger(new_event);
}
}
},
@@ -173,17 +167,17 @@ var BarcodeEvents = core.Class.extend(mixins.PropertiesMixin, {
},
start: function(prevent_key_repeat){
document.body.addEventListener('keypress', this.__handler, true);
$('body').bind("keypress", this.__handler);
if (prevent_key_repeat === true) {
document.body.addEventListener('keydown', this.__keydown_handler, true);
document.body.addEventListener('keyup', this.__keyup_handler, true);
$('body').bind("keydown", this.__keydown_handler);
$('body').bind('keyup', this.__keyup_handler);
}
},
stop: function(){
document.body.removeEventListener('keypress', this.__handler, true);
document.body.removeEventListener('keydown', this.__keydown_handler, true);
document.body.removeEventListener('keyup', this.__keyup_handler, true);
$('body').unbind("keypress", this.__handler);
$('body').unbind("keydown", this.__keydown_handler);
$('body').unbind('keyup', this.__keyup_handler);
},
});
+5 -19
View File
@@ -8,12 +8,12 @@ var fieldRegistry = require('web.field_registry');
// Field in which the user can both type normally and scan barcodes
var FieldFloatScannable = basicFields.FieldFloat.extend({
events: {
events: _.extend({}, basicFields.FieldFloat.prototype.events, {
// The barcode_events component intercepts keypresses and releases them when it
// appears they are not part of a barcode. But since released keypresses don't
// trigger native behaviour (like characters input), we must simulate it.
'keypress': '_onKeypress',
},
}),
//--------------------------------------------------------------------------
// Private
@@ -40,9 +40,8 @@ var FieldFloatScannable = basicFields.FieldFloat.extend({
*/
_onKeypress: function (e) {
/* only simulate a keypress if it has been previously prevented */
if (e.originalEvent.dispatched_by_barcode_reader !== true) {
if (e.dispatched_by_barcode_reader !== true) {
e.preventDefault();
this.$input.blur();
return;
}
var character = String.fromCharCode(e.which);
@@ -52,23 +51,12 @@ var FieldFloatScannable = basicFields.FieldFloat.extend({
e.target.value = str_before_carret + character + str_after_carret;
var new_carret_index = str_before_carret.length + character.length;
e.target.setSelectionRange(new_carret_index, new_carret_index);
// Note: FieldChar (that FieldFloat extends) calls store_dom_value upon change
// event, which is triggered when the input loses focus and its internal dirty
// flag is set. But here, we directly modify the value property of the input,
// which doesn't set the dirty flag. So we could call store_dom_value upon blur.
// But we also want the DOM value to be stored when a barcode_event occurs and
// triggers an onchange. We could listen to barcode_event in order to call
// store_dom_value, but that would have to happen before the onchange is triggered.
// So the safest method is still to store the value each time it changes.
// This long explanation is here to avoid having to do the thinking all over agan
// in case this strategy doesn't work / breaks.
// TL;DR Safest way not to lose the value when a barcode scan triggers an onchange.
this._setValue(e.target.value);
// trigger an 'input' event to notify the widget that it's value changed
$(e.target).trigger('input');
},
});
// Field to use scan barcodes
var FormViewBarcodeHandler = AbstractField.extend({
/**
* @override
@@ -78,8 +66,6 @@ var FormViewBarcodeHandler = AbstractField.extend({
this.trigger_up('activeBarcode', {
name: this.name,
fieldName: 'pack_operation_product_ids',
quantity: 'qty_done',
commands: {
barcode: '_barcodeAddX2MQuantity',
}
@@ -26,19 +26,23 @@ FormController.include({
this.activeBarcode = {
form_view: {
commands: {
'O-CMD.NEW': 'createRecord',
'O-CMD.EDIT': 'toEditMode',
'O-CMD.CANCEL': 'discardChange',
'O-CMD.SAVE': function () { return this.saveRecord({reload: true}); },
// 'O-CMD.PAGER-PREV':
// 'O-CMD.PAGER-NEXT':
}
}
'O-CMD.EDIT': this._barcodeEdit.bind(this),
'O-CMD.CANCEL': this._barcodeDiscard.bind(this),
'O-CMD.SAVE': this._barcodeSave.bind(this),
'O-CMD.PAGER-PREV': this._barcodePagerPrevious.bind(this),
'O-CMD.PAGER-NEXT': this._barcodePagerNext.bind(this),
'O-CMD.PAGER-FIRST': this._barcodePagerFirst.bind(this),
'O-CMD.PAGER-LAST': this._barcodePagerLast.bind(this),
},
},
};
this.barcodeMutex = new concurrency.Mutex();
this._barcodeStartListening();
},
/**
* @override
*/
destroy: function () {
this._barcodeStopListening();
this._super();
@@ -70,6 +74,55 @@ FormController.include({
}
},
/**
* @private
*/
_barcodeDiscard: function () {
return this.discardChanges();
},
/**
* @private
*/
_barcodeEdit: function () {
return this._setMode('edit');
},
/**
* @private
*/
_barcodePagerFirst: function () {
var self = this;
return this.mutex.exec(function () {}).then(function () {
self.pager.updateState({
current_min: 1,
}, {notifyChange: true});
});
},
/**
* @private
*/
_barcodePagerLast: function () {
var self = this;
return this.mutex.exec(function () {}).then(function () {
var state = self.model.get(self.handle, {raw: true});
self.pager.updateState({
current_min: state.count,
}, {notifyChange: true});
});
},
/**
* @private
*/
_barcodePagerNext: function () {
return this.mutex.exec(function () {}).then(this.pager.next.bind(this.pager));
},
/**
* @private
*/
_barcodePagerPrevious: function () {
return this.mutex.exec(function () {}).then(this.pager.previous.bind(this.pager));
},
/**
* Returns true iff the given barcode matches the given record (candidate).
*
* @private
* @param {Object} candidate: record in the x2m
* @param {string} barcode sent by the scanner (string generate from keypress series)
@@ -79,6 +132,12 @@ FormController.include({
_barcodeRecordFilter: function (candidate, barcode, activeBarcode) {
return candidate.data.product_barcode === barcode;
},
/**
* @private
*/
_barcodeSave: function () {
return this.saveRecord();
},
/**
* @private
* @param {Object} candidate: record in the x2m
@@ -89,8 +148,14 @@ FormController.include({
*/
_barcodeSelectedCandidate: function (candidate, record, barcode, activeBarcode) {
var changes = {};
changes[activeBarcode.quantity] = candidate.data[activeBarcode.quantity] + 1;
return this.model.notifyChanges(candidate.id, changes);
var candidateChanges = {};
candidateChanges[activeBarcode.quantity] = candidate.data[activeBarcode.quantity] + 1;
changes[activeBarcode.fieldName] = {
operation: 'UPDATE',
id: candidate.id,
data: candidateChanges,
};
return this.model.notifyChanges(this.handle, changes);
},
/**
* @private
@@ -99,7 +164,6 @@ FormController.include({
core.bus.on('barcode_scanned', this, this._barcodeScanned);
core.bus.on('keypress', this, this._quantityListener);
},
/**
* @private
*/
@@ -128,7 +192,7 @@ FormController.include({
*/
_getBarCodeRecord: function (record, barcode, activeBarcode) {
var self = this;
if (!activeBarcode.fieldName) {
if (!activeBarcode.fieldName || !record.data[activeBarcode.fieldName]) {
return;
}
return _.find(record.data[activeBarcode.fieldName].data, function (record) {
@@ -167,6 +231,10 @@ FormController.include({
candidate: this.activeBarcode[name] && this.activeBarcode[name].handle === this.handle ?
this.activeBarcode[name].candidate : null,
};
// we want to disable autofocus when activating the barcode to avoid
// putting the scanned value in the focused field
this.disableAutofocus = true;
},
/**
* @private
@@ -232,8 +300,13 @@ FormController.include({
if (prefixed && !hasCommand) {
self.do_warn(_t('Error : Barcode command is undefined'), barcode);
}
return $.when.apply($, defs).then(function () {
self.update({}, {reload: false});
return self.alive($.when.apply($, defs)).then(function () {
if (!prefixed) {
// redraw the view if we scanned a real barcode (required if
// we manually apply the change in JS, e.g. incrementing the
// quantity)
self.update({}, {reload: false});
}
});
});
},
@@ -319,8 +392,6 @@ FormRenderer.include({
commands['O-BTN.' + node.attrs.barcode_trigger] = function () {
if (!$button.hasClass('o_invisible_modifier')) {
$button.click();
} else {
this.do_warn(_t('Action currently unavailable'));
}
return $.when();
};
@@ -359,6 +430,21 @@ FormRenderer.include({
}
return $button;
},
/**
* Add barcode event handler
*
* @override
* @private
* @param {Object} node
* @returns {jQueryElement}
*/
_renderTagButton: function (node) {
var $button = this._super.apply(this, arguments);
if (node.attrs.barcode_trigger) {
this._barcodeButtonHandler($button, node);
}
return $button;
}
});
BarcodeEvents.ReservedBarcodePrefixes.push('O-BTN');
@@ -0,0 +1,406 @@
odoo.define('barcodes.tests', function (require) {
"use strict";
var barcodeEvents = require('barcodes.BarcodeEvents');
var AbstractField = require('web.AbstractField');
var fieldRegistry = require('web.field_registry');
var FormController = require('web.FormController');
var FormView = require('web.FormView');
var testUtils = require('web.test_utils');
var createView = testUtils.createView;
var triggerKeypressEvent = testUtils.triggerKeypressEvent;
QUnit.module('Barcodes', {
beforeEach: function () {
this.data = {
order: {
fields: {
_barcode_scanned: {string: 'Barcode scanned', type: 'char'},
line_ids: {string: 'Order lines', type: 'one2many', relation: 'order_line'},
},
records: [
{id: 1, line_ids: [1, 2]},
],
},
order_line: {
fields: {
product_id: {string: 'Product', type: 'many2one', relation: 'product'},
product_barcode: {string: 'Product Barcode', type: 'char'},
quantity: {string: 'Quantity', type: 'integer'},
},
records: [
{id: 1, product_id: 1, quantity: 0, product_barcode: '1234567890'},
{id: 2, product_id: 2, quantity: 0, product_barcode: '0987654321'},
],
},
product: {
fields: {
name: {string : "Product name", type: "char"},
int_field: {string : "Integer", type: "integer"},
barcode: {string: "Barcode", type: "char"},
},
records: [
{id: 1, name: "iPad Mini", barcode: '1234567890'},
{id: 2, name: "Mouse, Optical", barcode: '0987654321'},
],
},
};
}
});
QUnit.test('Button with barcode_trigger', function (assert) {
assert.expect(2);
var form = createView({
View: FormView,
model: 'product',
data: this.data,
arch: '<form>' +
'<header>' +
'<button name="do_something" string="Validate" type="object" barcode_trigger="doit"/>' +
'<button name="do_something_else" string="Validate" type="object" invisible="1" barcode_trigger="dothat"/>' +
'</header>' +
'</form>',
res_id: 2,
intercepts: {
execute_action: function (event) {
assert.strictEqual(event.data.action_data.name, 'do_something',
"do_something method call verified");
},
warning: function () {
assert.step('warn');
},
},
});
// O-BTN.doit
_.each(['O','-','B','T','N','.','d','o','i','t','Enter'], triggerKeypressEvent);
// O-BTN.dothat (should not call execute_action as the button isn't visible)
_.each(['O','-','B','T','N','.','d','o','t','h','a','t','Enter'], triggerKeypressEvent);
assert.verifySteps([], "no warning should be displayed");
form.destroy();
});
QUnit.test('edit, save and cancel buttons', function (assert) {
assert.expect(6);
var form = createView({
View: FormView,
model: 'product',
data: this.data,
arch: '<form><field name="display_name"/></form>',
mockRPC: function (route, args) {
if (args.method === 'write') {
assert.step('save');
}
return this._super.apply(this, arguments);
},
res_id: 1,
});
// O-CMD.EDIT
_.each(["O","-","C","M","D",".","E","D","I","T","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$(".o_form_editable").length, 1,
"should have switched to 'edit' mode");
// dummy change to check that it actually saves
form.$('.o_field_widget').val('test').trigger('input');
// O-CMD.SAVE
_.each(["O","-","C","M","D",".","S","A","V","E","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$(".o_form_readonly").length, 1,
"should have switched to 'readonly' mode");
assert.verifySteps(['save'], 'should have saved');
// O-CMD.EDIT
_.each(["O","-","C","M","D",".","E","D","I","T","Enter"], triggerKeypressEvent);
// dummy change to check that it correctly discards
form.$('.o_field_widget').val('test').trigger('input');
// O-CMD.CANCEL
_.each(["O","-","C","M","D",".","C","A","N","C","E","L","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$(".o_form_readonly").length, 1,
"should have switched to 'readonly' mode");
assert.verifySteps(['save'], 'should not have saved');
form.destroy();
});
QUnit.test('pager buttons', function (assert) {
assert.expect(5);
var form = createView({
View: FormView,
model: 'product',
data: this.data,
arch: '<form><field name="display_name"/></form>',
res_id: 1,
viewOptions: {
ids: [1, 2],
index: 0,
},
});
assert.strictEqual(form.$('.o_field_widget').text(), 'iPad Mini');
// O-CMD.PAGER-NEXT
_.each(["O","-","C","M","D",".","P","A","G","E","R","-","N","E","X","T","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$('.o_field_widget').text(), 'Mouse, Optical');
// O-CMD.PAGER-PREV
_.each(["O","-","C","M","D",".","P","A","G","E","R","-","P","R","E","V","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$('.o_field_widget').text(), 'iPad Mini');
// O-CMD.PAGER-LAST
_.each(["O","-","C","M","D",".","P","A","G","E","R","-","L","A","S","T","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$('.o_field_widget').text(), 'Mouse, Optical');
// O-CMD.PAGER-FIRST
_.each(["O","-","C","M","D",".","P","A","G","E","R","-","F","I","R","S","T","Enter"], triggerKeypressEvent);
assert.strictEqual(form.$('.o_field_widget').text(), 'iPad Mini');
form.destroy();
});
QUnit.test('do no update form twice after a command barcode scanned', function (assert) {
assert.expect(7);
var delay = barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms;
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = 0;
var formUpdate = FormController.prototype.update;
FormController.prototype.update = function () {
assert.step('update');
return formUpdate.apply(this, arguments);
};
var form = createView({
View: FormView,
model: 'product',
data: this.data,
arch: '<form>' +
'<field name="display_name"/>' +
'<field name="int_field" widget="field_float_scannable"/>' +
'</form>',
mockRPC: function (route, args) {
if (args.method === 'read') {
assert.step('read');
}
return this._super.apply(this, arguments);
},
res_id: 1,
viewOptions: {
ids: [1, 2],
index: 0,
},
});
assert.verifySteps(['read'], "update should not have been called yet");
// switch to next record
_.each(["O","-","C","M","D",".","P","A","G","E","R","-","N","E","X","T","Enter"], triggerKeypressEvent);
// a first update is done to reload the data (thus followed by a read), but
// update shouldn't be called afterwards
assert.verifySteps(['read', 'update', 'read']);
_.each(['5','4','3','9','8','2','6','7','1','2','5','2','Enter'], triggerKeypressEvent);
// a real barcode has been scanned -> an update should be requested (with
// option reload='false', so it isn't followed by a read)
assert.verifySteps(['read', 'update', 'read', 'update']);
form.destroy();
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = delay;
FormController.prototype.update = formUpdate;
});
QUnit.test('widget field_float_scannable', function (assert) {
var done = assert.async();
assert.expect(11);
var delay = barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms;
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = 0;
this.data.product.records[0].int_field = 4;
this.data.product.onchanges = {
int_field: function () {},
};
var form = createView({
View: FormView,
model: 'product',
data: this.data,
arch: '<form>' +
'<field name="display_name"/>' +
'<field name="int_field" widget="field_float_scannable"/>' +
'</form>',
mockRPC: function (route, args) {
if (args.method === 'onchange') {
assert.step('onchange');
assert.strictEqual(args.args[1].int_field, 426,
"should send correct value for int_field");
}
return this._super.apply(this, arguments);
},
fieldDebounce: 1000,
res_id: 1,
});
assert.strictEqual(form.$('.o_field_widget[name=int_field]').text(), '4',
"should display the correct value in readonly");
form.$buttons.find('.o_form_button_edit').click();
assert.strictEqual(form.$('.o_field_widget[name=int_field]').val(), '4',
"should display the correct value in edit");
// simulates keypress events in the input to replace 0.00 by 26 (should not trigger onchanges)
form.$('.o_field_widget[name=int_field]').focus();
assert.strictEqual(form.$('.o_field_widget[name=int_field]').get(0), document.activeElement,
"int field should be focused");
form.$('.o_field_widget[name=int_field]').trigger({type: 'keypress', which: 50, keyCode: 50}); // 2
assert.strictEqual(form.$('.o_field_widget[name=int_field]').get(0), document.activeElement,
"int field should still be focused");
form.$('.o_field_widget[name=int_field]').trigger({type: 'keypress', which: 54, keyCode: 54}); // 6
assert.strictEqual(form.$('.o_field_widget[name=int_field]').get(0), document.activeElement,
"int field should still be focused");
setTimeout(function () {
assert.strictEqual(form.$('.o_field_widget[name=int_field]').val(), '426',
"should display the correct value in edit");
assert.strictEqual(form.$('.o_field_widget[name=int_field]').get(0), document.activeElement,
"int field should still be focused");
assert.verifySteps([], 'should not have done any onchange RPC');
form.$('.o_field_widget[name=int_field]').trigger('change'); // should trigger the onchange
assert.verifySteps(['onchange'], 'should have done the onchange RPC');
form.destroy();
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = delay;
done();
});
});
QUnit.test('widget barcode_handler', function (assert) {
assert.expect(4);
var delay = barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms;
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = 0;
this.data.product.fields.barcode_scanned = {string : "Scanned barcode", type: "char"};
this.data.product.onchanges = {
barcode_scanned: function (obj) {
// simulate an onchange that increment the int_field value
// at each barcode scanned
obj.int_field = obj.int_field + 1;
},
};
var form = createView({
View: FormView,
model: 'product',
data: this.data,
arch: '<form>' +
'<field name="display_name"/>' +
'<field name="int_field"/>' +
'<field name="barcode_scanned" widget="barcode_handler" invisible="1"/>' +
'</form>',
mockRPC: function (route, args) {
if (args.method === 'onchange') {
assert.step('onchange');
}
return this._super.apply(this, arguments);
},
res_id: 1,
viewOptions: {
mode: 'edit',
},
});
assert.strictEqual(form.$('.o_field_widget[name=int_field]').val(), '0',
"initial value should be correct");
_.each(['5','4','3','9','8','2','6','7','1','2','5','2','Enter'], triggerKeypressEvent);
assert.strictEqual(form.$('.o_field_widget[name=int_field]').val(), '1',
"value should have been incremented");
assert.verifySteps(['onchange'], "an onchange should have been done");
form.destroy();
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = delay;
});
QUnit.test('specification of widget barcode_handler', function (assert) {
assert.expect(5);
var delay = barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms;
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = 0;
// Define a specific barcode_handler widget for this test case
var TestBarcodeHandler = AbstractField.extend({
init: function () {
this._super.apply(this, arguments);
this.trigger_up('activeBarcode', {
name: 'test',
fieldName: 'line_ids',
quantity: 'quantity',
commands: {
barcode: '_barcodeAddX2MQuantity',
}
});
},
});
fieldRegistry.add('test_barcode_handler', TestBarcodeHandler);
var form = createView({
View: FormView,
model: 'order',
data: this.data,
arch: '<form>' +
'<field name="_barcode_scanned" widget="test_barcode_handler"/>' +
'<field name="line_ids">' +
'<tree>' +
'<field name="product_id"/>' +
'<field name="product_barcode" invisible="1"/>' +
'<field name="quantity"/>' +
'</tree>' +
'</field>' +
'</form>',
mockRPC: function (route, args) {
if (args.method === 'onchange') {
assert.notOK(true, "should not do any onchange RPC");
}
if (args.method === 'write') {
assert.deepEqual(args.args[1].line_ids, [
[1, 1, {quantity: 2}], [1, 2, {quantity: 1}],
], "should have generated the correct commands");
}
return this._super.apply(this, arguments);
},
res_id: 1,
viewOptions: {
mode: 'edit',
},
});
assert.strictEqual(form.$('.o_data_row').length, 2,
"one2many should contain 2 rows");
// scan twice product 1
_.each(['1','2','3','4','5','6','7','8','9','0','Enter'], triggerKeypressEvent);
assert.strictEqual(form.$('.o_data_row:first .o_data_cell:nth(1)').text(), '1',
"quantity of line one should have been incremented");
_.each(['1','2','3','4','5','6','7','8','9','0','Enter'], triggerKeypressEvent);
assert.strictEqual(form.$('.o_data_row:first .o_data_cell:nth(1)').text(), '2',
"quantity of line one should have been incremented");
// scan once product 2
_.each(['0','9','8','7','6','5','4','3','2','1','Enter'], triggerKeypressEvent);
assert.strictEqual(form.$('.o_data_row:nth(1) .o_data_cell:nth(1)').text(), '1',
"quantity of line one should have been incremented");
form.$buttons.find('.o_form_button_save').click();
form.destroy();
barcodeEvents.BarcodeEvents.max_time_between_keys_in_ms = delay;
delete fieldRegistry.map.test_barcode_handler;
});
});
@@ -10,4 +10,10 @@
</xpath>
</template>
<template id="qunit_suite" name="barcode_tests" inherit_id="web.qunit_suite">
<xpath expr="//t[@t-set='head']" position="inside">
<script type="text/javascript" src="/barcodes/static/tests/barcode_tests.js"/>
</xpath>
</template>
</odoo>
@@ -12,6 +12,7 @@ from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, SUPERUSER_ID
from odoo.modules.registry import Registry
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
@@ -350,7 +351,7 @@ class BaseAutomation(models.Model):
except Exception:
_logger.error(traceback.format_exc())
action.write({'last_run': fields.Datetime.now()})
action.write({'last_run': now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
if automatic:
# auto-commit for batch processing
@@ -117,6 +117,11 @@
.o_kanban_view .o_kanban_record .oe_kanban_list_many2many .o_field_many2manytags {
border: none;
}
// Override height of graph. min-height doesn't do the trick
.o_graph {
height: 500px;
}
}
}
}
@@ -201,6 +201,7 @@
<form string="Contribution">
<group>
<field name="name"/>
<field name="partner_id"/>
<field name="company_id" groups="base.group_multi_company" options="{'no_create': True}" class="oe_inline"/>
</group>
<newline/>
@@ -353,4 +354,4 @@
view_id="hr_salary_rule_list"
id="act_children_salary_rules"/>
</odoo>
</odoo>
+10 -6
View File
@@ -73,22 +73,26 @@ class AccountChartTemplate(models.Model):
@api.multi
def _process_accounts_translations(self, company_id, langs, field):
in_ids = self.env['account.account.template'].search([('chart_template_id', '=', self.id)], order='id')
out_ids = self.env['account.account'].search([('company_id', '=', company_id)], order='id')
in_ids, out_ids = self._get_template_from_model(company_id, 'account.account')
return self.process_translations(langs, field, in_ids, out_ids)
@api.multi
def _process_taxes_translations(self, company_id, langs, field):
in_ids = self.env['account.tax.template'].search([('chart_template_id', '=', self.id)], order='id')
out_ids = self.env['account.tax'].search([('company_id', '=', company_id)], order='id')
in_ids, out_ids = self._get_template_from_model(company_id, 'account.tax')
return self.process_translations(langs, field, in_ids, out_ids)
@api.multi
def _process_fiscal_pos_translations(self, company_id, langs, field):
in_ids = self.env['account.fiscal.position.template'].search([('chart_template_id', '=', self.id)], order='id')
out_ids = self.env['account.fiscal.position'].search([('company_id', '=', company_id)], order='id')
in_ids, out_ids = self._get_template_from_model(company_id, 'account.fiscal.position')
return self.process_translations(langs, field, in_ids, out_ids)
def _get_template_from_model(self, company_id, model):
out_data = self.env['ir.model.data'].search([('model', '=', model), ('name', '=like', str(company_id)+'\_%')])
out_ids = self.env[model].search([('id', 'in', out_data.mapped('res_id'))], order='id')
in_xml_id_names = [xml_id.partition(str(company_id) + '_')[-1] for xml_id in out_data.mapped('name')]
in_xml_ids = self.env['ir.model.data'].search([('model', '=', model+'.template'), ('name', 'in', in_xml_id_names)])
in_ids = self.env[model+'.template'].search([('id', 'in', in_xml_ids.mapped('res_id'))], order='id')
return (in_ids, out_ids)
class BaseLanguageInstall(models.TransientModel):
""" Install Language"""
@@ -1546,6 +1546,9 @@ exports.Orderline = Backbone.Model.extend({
if (!no_map_tax){
tax = self._map_tax_fiscal_position(tax);
}
if (!tax){
return;
}
if (tax.amount_type === 'group'){
var ret = self.compute_all(tax.children_tax_ids, price_unit, quantity, currency_rounding);
total_excluded = ret.total_excluded;
+1 -1
View File
@@ -57,7 +57,7 @@ class ReportProjectTaskUser(models.Model):
t.partner_id,
t.stage_id as stage_id,
t.kanban_state as state,
(extract('epoch' from (t.write_date-t.create_date)))/(3600*24) as closing_days,
(extract('epoch' from (NULLIF(t.date_end, t.write_date)-t.create_date)))/(3600*24) as closing_days,
(extract('epoch' from (t.date_start-t.create_date)))/(3600*24) as opening_days,
(extract('epoch' from (t.date_deadline-(now() at time zone 'UTC'))))/(3600*24) as delay_endings_days
"""
+2 -3
View File
@@ -324,9 +324,8 @@
<record id="ir_actions_server_project_sample" model="ir.actions.server">
<field name="name">Project: Activate Sample Project</field>
<field name="model_id" ref="project.model_project_project"/>
<field name="code">
action = model.activate_sample_project()
</field>
<field name="state">code</field>
<field name="code">action = model.activate_sample_project()</field>
</record>
<record id="open_view_project_all" model="ir.actions.act_window">
+5 -5
View File
@@ -26,10 +26,10 @@ class AccountAnalyticLine(models.Model):
@api.multi
def write(self, values):
# prevent to update invoiced timesheets
#if self.filtered(lambda timesheet: timesheet.timesheet_invoice_id):
# if any([field_name in values for field_name in ['unit_amount', 'employee_id', 'task_id', 'timesheet_revenue', 'so_line', 'amount', 'date']]):
# raise UserError(_('You can not modify already invoiced timesheets.'))
# prevent to update invoiced timesheets if product_id is not of type order
if self.so_line.product_id.invoice_policy != "order" and self.filtered(lambda timesheet: timesheet.timesheet_invoice_id):
if any([field_name in values for field_name in ['unit_amount', 'employee_id', 'task_id', 'timesheet_revenue', 'so_line', 'amount', 'date']]):
raise UserError(_('You can not modify already invoiced timesheets.'))
so_lines = self.mapped('so_line')
if values.get('task_id'):
@@ -134,7 +134,7 @@ class AccountAnalyticLine(models.Model):
total_revenue_invoiced = sum(analytic_lines.mapped('timesheet_revenue'))
# compute (new) revenue of current timesheet line
revenue = min(
analytic_account.currency_id.round(unit_amount * so_line.currency_id.compute(so_line.price_unit, analytic_account.currency_id) * (1-so_line.discount)),
analytic_account.currency_id.round(unit_amount * so_line.currency_id.compute(so_line.price_unit, analytic_account.currency_id) * (1-(so_line.discount/100))),
total_revenue_so - total_revenue_invoiced
)
billable_type = 'billable_fixed'
@@ -2,6 +2,7 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale.tests.test_sale_common import TestSale
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_repr
@@ -185,6 +186,16 @@ class TestSaleTimesheet(TestSale):
self.assertEquals(timesheet2.timesheet_invoice_id, invoice)
self.assertEquals(timesheet3.timesheet_invoice_id, invoice)
# check that analytic line for product 'ordered' can be altered
with self.assertRaises(UserError):
timesheet1.write(dict(unit_amount=10))
self.assertNotEquals(timesheet1.unit_amount, 10)
# check that analytic line for product 'delivered' cannot be altered
timesheet3.write(dict(unit_amount=10))
self.assertEquals(timesheet3.unit_amount, 10)
def test_revenue_multi_currency(self):
""" Create a SO with 2 lines : one for a delivered service, one for a ordered service. Confirm
and invoice it. For this, we use a partner having a DIFFERENT currency from the current company.
+1 -1
View File
@@ -152,7 +152,7 @@ class ProcurementOrder(models.Model):
qty_done = sum(self.move_ids.filtered(lambda move: move.state == 'done').mapped('product_uom_qty'))
qty_left = max(self.product_qty - qty_done, 0)
return {
'name': self.name,
'name': self.name[:2000],
'company_id': self.rule_id.company_id.id or self.rule_id.location_src_id.company_id.id or self.rule_id.location_id.company_id.id or self.company_id.id,
'product_id': self.product_id.id,
'product_uom': self.product_uom.id,
+6 -1
View File
@@ -117,7 +117,12 @@
<span t-if="pack_operation.package_id">:</span>
<span t-field="pack_operation.package_id"/>
<span t-field="pack_operation.ordered_qty"/>
<span t-field="pack_operation.product_uom_id"/>
<t t-if="pack_operation.linked_move_operation_ids">
<span t-field="pack_operation.linked_move_operation_ids[0].move_id.product_uom"></span>
</t>
<t t-else="1">
<span t-field="pack_operation.product_uom_id"></span>
</t>
</td>
<td class="text-right" t-if="pack_operation.state == 'done'">
<t t-if="pack_operation.ordered_qty != pack_operation.qty_done">
+7 -1
View File
@@ -97,10 +97,16 @@ var Pager = Widget.extend({
/**
* Sets the state of the pager and renders it
* @param {Object} [state] the values to update (size, current_min and limit)
* @param {Object} [options]
* @param {boolean} [options.notifyChange] set to true to make the pager
* notify the environment that its state changed
*/
updateState: function (state) {
updateState: function (state, options) {
_.extend(this.state, state);
this._render();
if (options && options.notifyChange) {
this.trigger('pager_changed', _.clone(this.state));
}
},
//--------------------------------------------------------------------------
@@ -363,7 +363,7 @@ var ViewManager = Widget.extend(ControlPanelMixin, {
var View = this.registry.get(arch.attrs.js_class || view_descr.type);
var params = _.extend({}, view_options, {userContext: this.getSession().user_context});
if (view_descr.type === "form" && ((this.action.target === 'new' || this.action.target === 'inline') ||
(view_options && view_options.mode === 'edit'))) {
(view_options && (view_options.mode === 'edit' || view_options.context.form_view_initial_mode)))) {
params.mode = params.initial_mode || 'edit';
}
view_descr.searchview_hidden = View.prototype.searchview_hidden;
@@ -1735,7 +1735,7 @@ var FieldProgressBar = AbstractField.extend({
} else {
this.$el.on('click', function () {
if (!self.write_mode) {
var $input = $('<input>', {type: 'text', class: 'o_progressbar_value'});
var $input = $('<input>', {type: 'text', class: 'o_progressbar_value o_input'});
$input.on('blur', _.bind(self.on_change_input, self));
self.$('.o_progressbar_value').replaceWith($input);
self.write_mode = true;
@@ -2738,8 +2738,7 @@ var BasicModel = AbstractModel.extend({
var fieldInfo = element.fieldsInfo[element.viewType][fieldName];
var rawModifiers = JSON.parse(fieldInfo.modifiers || "{}");
var modifiers = self._evalModifiers(record, rawModifiers);
var required = 'required' in modifiers ? modifiers.required : field.required;
if (required && !self._isFieldSet(recordData[fieldName], field.type)) {
if (modifiers.required && !self._isFieldSet(recordData[fieldName], field.type)) {
isValid = false;
}
});
@@ -28,6 +28,7 @@ var FormController = BasicController.extend({
this._super.apply(this, arguments);
this.actionButtons = params.actionButtons;
this.disableAutofocus = params.disableAutofocus;
this.footerToButtons = params.footerToButtons;
this.defaultButtons = params.defaultButtons;
this.hasSidebar = params.hasSidebar;
@@ -42,7 +43,9 @@ var FormController = BasicController.extend({
* Calls autofocus on the renderer
*/
autofocus: function () {
this.renderer.autofocus();
if (!this.disableAutofocus) {
this.renderer.autofocus();
}
},
/**
* This method switches the form view in edit mode, with a new record.
@@ -305,7 +308,7 @@ var FormController = BasicController.extend({
this.set('title', title);
this._updateButtons();
this._updateSidebar();
return this._super.apply(this, arguments);
return this._super.apply(this, arguments).then(this.autofocus.bind(this));
},
/**
* @private
@@ -245,10 +245,6 @@ var FormRenderer = BasicRenderer.extend({
_renderButtonBox: function (node) {
var self = this;
var $result = $('<' + node.tag + '>', { 'class': 'o_not_full' });
// Avoid to show buttons if we are in create mode (edit mode without res_id)
if (this.mode === 'edit' && !this.state.res_id) {
return $result;
}
var buttons = _.map(node.children, function (child) {
if (child.tag === 'button') {
return self._renderStatButton(child);
@@ -818,9 +814,6 @@ var FormRenderer = BasicRenderer.extend({
self._addFieldTooltip(widget, $label);
}
});
// Focus the default field (in edit mode)
self.autofocus();
},
/**
* Sets id attribute of given widget to idForLabel
@@ -29,6 +29,7 @@ var FormView = BasicView.extend({
this.loadParams.type = 'record';
this.loadParams.parentID = params.parentID;
this.controllerParams.disableAutofocus = params.disable_autofocus;
this.controllerParams.hasSidebar = params.sidebar;
this.controllerParams.toolbarActions = viewInfo.toolbar;
this.controllerParams.footerToButtons = params.footer_to_buttons;
@@ -101,11 +101,21 @@ var GraphController = AbstractController.extend({
self._updateButtons();
});
},
/**
* @private
*/
_update: function () {
this._updateButtons();
return this._super.apply(this, arguments);
},
/**
* makes sure that the buttons in the control panel matches the current
* state (so, correct active buttons and stuff like that)
*/
_updateButtons: function () {
if (!this.$buttons) {
return;
}
var state = this.model.get();
this.$buttons.find('.o_graph_button').removeClass('active');
this.$buttons
@@ -55,14 +55,15 @@ return AbstractModel.extend({
* to keep track of various entities.
*/
load: function (params) {
this.initialGroupBys = params.groupBys;
var groupBys = params.context.graph_groupbys || params.groupBys;
this.initialGroupBys = groupBys;
this.fields = params.fields;
this.modelName = params.modelName;
this.chart = {
data: [],
groupedBy: params.groupedBy.length ? params.groupedBy : params.groupBys,
measure: params.measure,
mode: params.mode,
groupedBy: params.groupedBy.length ? params.groupedBy : groupBys,
measure: params.context.graph_measure || params.measure,
mode: params.context.graph_mode || params.mode,
domain: params.domain,
context: params.context,
};
@@ -85,6 +86,12 @@ return AbstractModel.extend({
* @returns {Deferred}
*/
reload: function (handle, params) {
if ('context' in params) {
this.chart.context = params.context;
this.chart.groupedBy = params.context.graph_groupbys || this.chart.groupedBy;
this.chart.measure = params.context.graph_measure || this.chart.measure;
this.chart.mode = params.context.graph_mode || this.chart.mode;
}
if ('domain' in params) {
this.chart.domain = params.domain;
}
@@ -27,7 +27,7 @@ var GraphView = AbstractView.extend({
/**
* @override
*/
init: function (viewInfo, params) {
init: function (viewInfo) {
this._super.apply(this, arguments);
var measure;
@@ -57,9 +57,9 @@ var GraphView = AbstractView.extend({
this.controllerParams.measures = measures;
this.rendererParams.stacked = viewInfo.arch.attrs.stacked !== "False";
this.loadParams.mode = params.context.graph_mode || viewInfo.arch.attrs.type || 'bar';
this.loadParams.measure = params.context.graph_measure || measure || '__count__';
this.loadParams.groupBys = params.context.graph_groupbys || groupBys || [];
this.loadParams.mode = viewInfo.arch.attrs.type || 'bar';
this.loadParams.measure = measure || '__count__';
this.loadParams.groupBys = groupBys || [];
this.loadParams.fields = viewInfo.fields;
},
});
@@ -223,15 +223,15 @@ var PivotModel = AbstractModel.extend({
*/
load: function (params) {
this.initialDomain = params.domain;
this.initialRowGroupBys = params.rowGroupBys;
this.initialRowGroupBys = params.context.pivot_row_groupby || params.rowGroupBys;
this.fields = params.fields;
this.modelName = params.modelName;
this.data = {
domain: params.domain,
context: _.extend({}, session.user_context, params.context),
groupedBy: params.groupedBy,
colGroupBys: params.colGroupBys,
measures: params.measures,
colGroupBys: params.context.pivot_column_groupby || params.colGroupBys,
measures: this._processMeasures(params.context.pivot_measures) || params.measures,
sorted_column: {},
};
this.defaultGroupedBy = params.groupedBy;
@@ -245,6 +245,12 @@ var PivotModel = AbstractModel.extend({
*/
reload: function (handle, params) {
var self = this;
if ('context' in params) {
this.data.context = params.context;
this.data.colGroupBys = params.context.pivot_column_groupby || this.data.colGroupBys;
this.data.groupedBy = params.context.pivot_row_groupby || this.data.groupedBy;
this.data.measures = this._processMeasures(params.context.pivot_measures) || this.data.measures;
}
if ('domain' in params) {
this.data.domain = params.domain;
} else {
@@ -261,7 +267,7 @@ var PivotModel = AbstractModel.extend({
var old_col_root = this.data.main_col.root;
return this._loadData().then(function () {
var new_groupby_length;
if (!('groupBy' in params)) {
if (!('groupBy' in params) && !('pivot_row_groupby' in (params.context || {}))) {
// we only update the row groupbys according to the old groupbys
// if we don't have the key 'groupBy' in params. In that case,
// we want to have the full open state for the groupbys.
@@ -648,6 +654,29 @@ var PivotModel = AbstractModel.extend({
this.data.main_row.root = main_row_header;
this.data.main_col.root = main_col_header;
},
/**
* In the preview implementation of the pivot view (a.k.a. version 2),
* the virtual field used to display the number of records was named
* __count__, whereas __count is actually the one used in xml. So
* basically, activating a filter specifying __count as measures crashed.
* Unfortunately, as __count__ was used in the JS, all filters saved as
* favorite at that time were saved with __count__, and not __count.
* So in order the make them still work with the new implementation, we
* handle both __count__ and __count.
*
* This function replaces in the given array of measures occurences of
* '__count__' by '__count'.
*
* @param {Array[string] || undefined} measures
* @return {Array[string] || undefined}
*/
_processMeasures: function (measures) {
if (measures) {
return _.map(measures, function (measure) {
return measure === '__count__' ? '__count' : measure;
});
}
},
/**
* Format a value to a usable string, for the renderer to display.
*
@@ -87,9 +87,9 @@ var PivotView = AbstractView.extend({
activeMeasures.push('__count');
}
this.loadParams.measures = params.context.pivot_measures || activeMeasures;
this.loadParams.colGroupBys = params.context.pivot_column_groupby || colGroupBys;
this.loadParams.rowGroupBys = params.context.pivot_row_groupby || rowGroupBys;
this.loadParams.measures = activeMeasures;
this.loadParams.colGroupBys = colGroupBys;
this.loadParams.rowGroupBys = rowGroupBys;
this.loadParams.fields = fields;
this.controllerParams.title = params.title || arch.attrs.string || _t("Untitled");
@@ -1259,6 +1259,8 @@ QUnit.module('basic_fields', {
// Copying from a div tag with white-space:pre-wrap doesn't work in Firefox
assert.strictEqual(form.$('[name="txt"]').prop("tagName").toLowerCase(), 'span',
"the field contents should be surrounded by a span tag");
form.destroy();
});
QUnit.module('FieldBinary');
@@ -5352,6 +5352,43 @@ QUnit.module('relational_fields', {
form.destroy();
});
QUnit.test('onchange and required fields with override in arch', function (assert) {
assert.expect(4);
this.data.partner.onchanges = {
turtles: function (obj) {}
};
this.data.turtle.fields.turtle_foo.required = true;
this.data.partner.records[0].turtles = [];
var form = createView({
View: FormView,
model: 'partner',
data: this.data,
arch:'<form string="Partners">' +
'<field name="turtles">' +
'<tree editable="bottom">' +
'<field name="turtle_int"/>' +
'<field name="turtle_foo" required="0"/>' +
'</tree>' +
'</field>' +
'</form>',
res_id: 1,
mockRPC: function (route, args) {
assert.step(args.method);
return this._super.apply(this, arguments);
},
});
form.$buttons.find('.o_form_button_edit').click();
// triggers an onchange on partner, because the new record is valid
form.$('.o_field_x2many_list_row_add a').click();
assert.verifySteps(['read', 'default_get', 'onchange']);
form.destroy();
});
QUnit.module('FieldMany2Many');
@@ -468,6 +468,20 @@ function triggerPositionalMouseEvent(x, y, type){
return el;
}
/**
* simulate a keypress event for a given character
* @param {string} the character
*/
function triggerKeypressEvent(char) {
var keycode;
if (char === "Enter") {
keycode = $.ui.keyCode.ENTER;
} else {
keycode = char.charCodeAt(0);
}
return $('body').trigger($.Event('keypress', {which: keycode, keyCode: keycode}));
}
/**
* Removes the src attribute on images and iframes to prevent not found errors,
* and optionally triggers an rpc with the src url as route on a widget.
@@ -509,6 +523,7 @@ return session.is_bound.then(function () {
dragAndDrop: dragAndDrop,
triggerMouseEvent: triggerMouseEvent,
triggerPositionalMouseEvent: triggerPositionalMouseEvent,
triggerKeypressEvent: triggerKeypressEvent,
removeSrcAttribute: removeSrcAttribute,
};
});
+29 -3
View File
@@ -2678,7 +2678,7 @@ QUnit.module('Views', {
form.destroy();
});
QUnit.test('button box is not rendered in create mode', function (assert) {
QUnit.test('button box is rendered in create mode', function (assert) {
assert.expect(3);
var form = createView({
@@ -2708,8 +2708,8 @@ QUnit.module('Views', {
// create mode (leave edition first!)
form.$buttons.find('.o_form_button_cancel').click();
form.$buttons.find('.o_form_button_create').click();
assert.strictEqual(form.$('.oe_stat_button').length, 0,
"button box should not be displayed when creating a new record");
assert.strictEqual(form.$('.oe_stat_button').length, 1,
"button box should be displayed when creating a new record as well");
form.destroy();
});
@@ -4233,6 +4233,32 @@ QUnit.module('Views', {
form.destroy();
});
QUnit.test('no autofocus with disable_autofocus option [REQUIRE FOCUS]', function (assert) {
assert.expect(2);
var form = createView({
View: FormView,
model: 'partner',
data: this.data,
arch: '<form string="Partners">' +
'<field name="int_field"/>' +
'<field name="foo"/>' +
'</form>',
viewOptions: {
disable_autofocus: true,
},
});
assert.notStrictEqual(document.activeElement, form.$('input[name="int_field"]')[0],
"int_field field should not have focus");
form.update({});
assert.notStrictEqual(document.activeElement, form.$('input[name="int_field"]')[0],
"int_field field should not have focus");
form.destroy();
});
QUnit.test('open one2many form containing many2many_tags', function (assert) {
assert.expect(4);
@@ -372,6 +372,52 @@ QUnit.module('Views', {
});
});
QUnit.test('correctly uses graph_ keys from the context (at reload)', function (assert) {
var done = assert.async();
assert.expect(8);
var graph = createView({
View: GraphView,
model: "foo",
data: this.data,
arch: '<graph><field name="product_id"/></graph>',
});
assert.strictEqual(graph.renderer.state.mode, "bar", "should be in bar chart mode");
assert.ok(graph.$buttons.find('button[data-mode="bar"]').hasClass('active'),
'bar chart button should be active');
var reloadParams = {
context: {
graph_measure: 'foo',
graph_mode: 'line',
graph_groupbys: ['color_id'],
},
};
graph.reload(reloadParams);
return concurrency.delay(0).then(function () {
// check measure
assert.strictEqual(graph.$('text.nv-legend-text:contains(Foo)').length, 1,
"should now use the 'foo' measure");
// check mode
assert.strictEqual(graph.renderer.state.mode, "line", "should be in line chart mode");
assert.notOk(graph.$buttons.find('button[data-mode="bar"]').hasClass('active'),
'bar chart button should not be active');
assert.ok(graph.$buttons.find('button[data-mode="line"]').hasClass('active'),
'line chart button should be active');
// check groupbys
assert.strictEqual(graph.$('text:contains(xphone)').length, 0,
"should not contain a text element with product in legend");
assert.strictEqual(graph.$('text:contains(red)').length, 1,
"should contain a text element with color in legend");
graph.destroy();
done();
});
});
QUnit.test('reload graph with correct fields', function (assert) {
assert.expect(2);
@@ -825,6 +825,53 @@ QUnit.module('Views', {
pivot.destroy();
});
QUnit.test('correctly uses pivot_ keys from the context (at reload)', function (assert) {
assert.expect(8);
this.data.partner.fields.amount = {string: "Amount", type: "float"};
var pivot = createView({
View: PivotView,
model: "partner",
data: this.data,
arch: '<pivot>' +
'<field name="date" interval="day" type="col"/>' +
'<field name="amount" type="measure"/>' +
'</pivot>',
});
assert.strictEqual(pivot.$('tbody tr:first td.o_pivot_cell_value:last').text(), '0.00',
"the active measure should be amount");
var reloadParams = {
context: {
pivot_measures: ['foo'],
pivot_column_groupby: ['customer'],
pivot_row_groupby: ['product_id'],
},
};
pivot.reload(reloadParams);
assert.strictEqual(pivot.$('thead .o_pivot_header_cell_opened').length, 1,
"column: should have one opened header");
assert.strictEqual(pivot.$('thead .o_pivot_header_cell_closed:contains(First)').length, 1,
"column: should display one closed header with 'First'");
assert.strictEqual(pivot.$('thead .o_pivot_header_cell_closed:contains(Second)').length, 1,
"column: should display one closed header with 'Second'");
assert.strictEqual(pivot.$('tbody .o_pivot_header_cell_opened').length, 1,
"row: should have one opened header");
assert.strictEqual(pivot.$('tbody .o_pivot_header_cell_closed:contains(xphone)').length, 1,
"row: should display one closed header with 'xphone'");
assert.strictEqual(pivot.$('tbody .o_pivot_header_cell_closed:contains(xpad)').length, 1,
"row: should display one closed header with 'xpad'");
assert.strictEqual(pivot.$('tbody tr:first td:nth(3)').text(), '32',
"selected measure should be foo, with total 32");
pivot.destroy();
});
QUnit.test('correctly use group_by key from the context', function (assert) {
assert.expect(7);
@@ -859,4 +906,33 @@ QUnit.module('Views', {
pivot.destroy();
});
QUnit.test('pivot still handles __count__ measure', function (assert) {
// for retro-compatibility reasons, the pivot view still handles
// '__count__' measure.
assert.expect(2);
var pivot = createView({
View: PivotView,
model: "partner",
data: this.data,
arch: '<pivot></pivot>',
mockRPC: function (route, args) {
if (args.method === 'read_group') {
assert.deepEqual(args.kwargs.fields, ['__count'],
"should make a read_group with field __count");
}
return this._super(route, args);
},
viewOptions: {
context: {
pivot_measures: ['__count__'],
},
},
});
var $countMeasure = pivot.$buttons.find('li[data-field=__count]');
assert.ok($countMeasure.hasClass('selected'), "The count measure should be activated");
pivot.destroy();
});
});});
+11
View File
@@ -0,0 +1,11 @@
Vietnam, 2017-08-24
I hereby agree to the terms of the Odoo Individual Contributor License
Agreement v1.0.
I declare that I am authorized and able to make this agreement and sign this
declaration.
Signed,
Do Vuong Tien tiendv@trobz.com https://github.com/vuongtien2411
+1 -1
View File
@@ -287,7 +287,7 @@ class Foo(models.Model):
_name = 'test_new_api.foo'
name = fields.Char()
value1 = fields.Integer()
value1 = fields.Integer(change_default=True)
value2 = fields.Integer()
@@ -231,6 +231,28 @@ class TestOnChange(common.TransactionCase):
for user in discussion.participants + demo],
)
def test_onchange_default(self):
""" test the effect of a conditional user-default on a field """
Foo = self.env['test_new_api.foo']
field_onchange = Foo._onchange_spec()
self.assertTrue(Foo._fields['value1'].change_default)
self.assertEqual(field_onchange.get('value1'), '1')
# create a user-defined default based on 'value1'
self.env['ir.values'].set_default('test_new_api.foo', 'value2', 666, condition='value1=42')
# setting 'value1' to 42 should trigger the change of 'value2'
self.env.invalidate_all()
values = {'name': 'X', 'value1': 42, 'value2': False}
result = Foo.onchange(values, 'value1', field_onchange)
self.assertEqual(result['value'], {'value2': 666})
# setting 'value1' to 24 should not trigger the change of 'value2'
self.env.invalidate_all()
values = {'name': 'X', 'value1': 24, 'value2': False}
result = Foo.onchange(values, 'value1', field_onchange)
self.assertEqual(result['value'], {})
def test_onchange_one2many_value(self):
""" test the value of the one2many field inside the onchange """
discussion = self.env.ref('test_new_api.discussion_0')
+12
View File
@@ -572,6 +572,7 @@ class BaseModel(MetaModel('DummyModel', (object,), {'_register': False})):
def is_onchange(func):
return callable(func) and hasattr(func, '_onchange')
# collect onchange methods on the model's class
cls = type(self)
methods = defaultdict(list)
for attr, func in getmembers(cls, is_onchange):
@@ -580,6 +581,17 @@ class BaseModel(MetaModel('DummyModel', (object,), {'_register': False})):
_logger.warning("@onchange%r parameters must be field names", func._onchange)
methods[name].append(func)
# add onchange methods to implement "change_default" on fields
def onchange_default(field, self):
value = field.convert_to_write(self[field.name], self)
condition = "%s=%s" % (field.name, value)
defaults = self.env['ir.values'].get_defaults_dict(self._name, condition)
self.update(defaults)
for name, field in cls._fields.items():
if field.change_default:
methods[name].append(functools.partial(onchange_default, field))
# optimization: memoize result on cls, it will not be recomputed
cls._onchange_methods = methods
return methods