diff --git a/.tx/config b/.tx/config index 01696fa99b7..3a276d80eb4 100644 --- a/.tx/config +++ b/.tx/config @@ -682,9 +682,9 @@ file_filter = addons/stock_landed_costs/i18n/.po source_file = addons/stock_landed_costs/i18n/stock_landed_costs.pot source_lang = en -[odoo-master.stock_picking_wave] -file_filter = addons/stock_picking_wave/i18n/.po -source_file = addons/stock_picking_wave/i18n/stock_picking_wave.pot +[odoo-master.stock_picking_batch] +file_filter = addons/stock_picking_batch/i18n/.po +source_file = addons/stock_picking_batch/i18n/stock_picking_batch.pot source_lang = en [odoo-master.survey] diff --git a/addons/account/models/account_invoice.py b/addons/account/models/account_invoice.py index 825588aceba..3cc8ae14a7f 100644 --- a/addons/account/models/account_invoice.py +++ b/addons/account/models/account_invoice.py @@ -355,22 +355,19 @@ class AccountInvoice(models.Model): has_outstanding = fields.Boolean(compute='_get_outstanding_info_JSON', groups="account.group_account_invoice") #fields use to set the sequence, on the first invoice of the journal - sequence_number_next = fields.Char(string='Next Number', compute="_get_sequence_prefix", inverse="_set_sequence_next") + sequence_number_next = fields.Char(string='Next Number', compute="_get_sequence_number_next", inverse="_set_sequence_next") sequence_number_next_prefix = fields.Char(string='Next Number', compute="_get_sequence_prefix") _sql_constraints = [ ('number_uniq', 'unique(number, company_id, journal_id, type)', 'Invoice Number must be unique per Company!'), ] - def _compute_portal_url(self): - super(AccountInvoice, self)._compute_portal_url() - for order in self: - order.portal_url = '/my/invoices/%s' % (order.id) - - def _no_existing_validated_invoice(self): + def _get_seq_number_next_stuff(self): self.ensure_one() + journal_sequence = self.journal_id.sequence_id if self.journal_id.refund_sequence: domain = [('type', '=', self.type)] + journal_sequence = self.type in ['in_refund', 'out_refund'] and self.journal_id.refund_sequence_id or self.journal_id.sequence_id elif self.type in ['in_invoice', 'in_refund']: domain = [('type', 'in', ['in_invoice', 'in_refund'])] else: @@ -378,11 +375,16 @@ class AccountInvoice(models.Model): if self.id: domain += [('id', '<>', self.id)] domain += [('journal_id', '=', self.journal_id.id), ('state', 'not in', ['draft', 'cancel'])] - return not self.search(domain, limit=1) + return journal_sequence, domain + + def _compute_portal_url(self): + super(AccountInvoice, self)._compute_portal_url() + for order in self: + order.portal_url = '/my/invoices/%s' % (order.id) @api.depends('state', 'journal_id', 'date_invoice') def _get_sequence_prefix(self): - """ computes the number that will be assigned to the first invoice/bill/refund of a journal, in order to + """ computes the prefix of the number that will be assigned to the first invoice/bill/refund of a journal, in order to let the user manually change it. """ if not self.env.user._is_admin(): @@ -391,18 +393,25 @@ class AccountInvoice(models.Model): invoice.sequence_number_next = '' return for invoice in self: - if invoice.journal_id.refund_sequence: - journal_sequence = invoice.type in ['in_refund', 'out_refund'] and invoice.journal_id.refund_sequence_id or invoice.journal_id.sequence_id - else: - journal_sequence = invoice.journal_id.sequence_id - - if (invoice.state == 'draft') and self._no_existing_validated_invoice(): - prefix, dummy = journal_sequence.with_context(ir_sequence_date=invoice.date_invoice)._get_prefix_suffix() + journal_sequence, domain = invoice._get_seq_number_next_stuff() + if (invoice.state == 'draft') and not self.search(domain, limit=1): + prefix, dummy = journal_sequence.with_context(ir_sequence_date=invoice.date_invoice, + ir_sequence_date_range=invoice.date_invoice)._get_prefix_suffix() invoice.sequence_number_next_prefix = prefix + else: + invoice.sequence_number_next_prefix = False + + @api.depends('state', 'journal_id') + def _get_sequence_number_next(self): + """ computes the number that will be assigned to the first invoice/bill/refund of a journal, in order to + let the user manually change it. + """ + for invoice in self: + journal_sequence, domain = invoice._get_seq_number_next_stuff() + if (invoice.state == 'draft') and not self.search(domain, limit=1): number_next = journal_sequence._get_current_sequence().number_next_actual invoice.sequence_number_next = '%%0%sd' % journal_sequence.padding % number_next else: - invoice.sequence_number_next_prefix = False invoice.sequence_number_next = '' @api.multi diff --git a/addons/account/models/account_move.py b/addons/account/models/account_move.py index 184bad0184c..21d1fad78d6 100644 --- a/addons/account/models/account_move.py +++ b/addons/account/models/account_move.py @@ -627,19 +627,40 @@ class AccountMoveLine(models.Model): @api.model def get_reconciliation_proposition(self, account_id, partner_id=False): """ Returns two lines whose amount are opposite """ + + target_currency = (self.currency_id and self.amount_currency) and self.currency_id or self.company_id.currency_id + partner_id_condition = partner_id and 'AND a.partner_id = %(partner_id)s' or '' + rec_prop = self.env['account.move.line'] # Get pairs - partner_id_condition = partner_id and 'AND a.partner_id = %(partner_id)s AND b.partner_id = %(partner_id)s' or '' - query = """ - SELECT a.id, b.id - FROM account_move_line a, account_move_line b - WHERE a.amount_residual = -b.amount_residual - AND NOT a.reconciled AND NOT b.reconciled - AND a.account_id = %(account_id)s AND b.account_id = %(account_id)s - {partner_id_condition} - ORDER BY a.date desc - LIMIT 10 - """.format(**locals()) + move_line_id = self.env.context.get('move_line_id', False) + if move_line_id: + move_line = self.env['account.move.line'].browse(move_line_id) + amount = move_line.amount_residual; + rec_prop = move_line + query = """ + SELECT a.id, a.id FROM account_move_line a + WHERE a.amount_residual = -%(amount)s + AND NOT a.reconciled + AND a.account_id = %(account_id)s + AND a.id != %(move_line_id)s + {partner_id_condition} + ORDER BY a.date desc + LIMIT 10 + """.format(**locals()) + else: + partner_id_condition = partner_id_condition and partner_id_condition+' AND b.partner_id = %(partner_id)s' or '' + query = """ + SELECT a.id, b.id + FROM account_move_line a, account_move_line b + WHERE a.amount_residual = -b.amount_residual + AND NOT a.reconciled AND NOT b.reconciled + AND a.account_id = %(account_id)s AND b.account_id = %(account_id)s + {partner_id_condition} + ORDER BY a.date desc + LIMIT 10 + """.format(**locals()) + self.env.cr.execute(query, locals()) pairs = self.env.cr.fetchall() @@ -648,11 +669,12 @@ class AccountMoveLine(models.Model): allowed_ids = set(self.env['account.move.line'].browse(all_pair_ids).ids) pairs = [pair for pair in pairs if pair[0] in allowed_ids and pair[1] in allowed_ids] - # Return lines formatted if len(pairs) > 0: - target_currency = (self.currency_id and self.amount_currency) and self.currency_id or self.company_id.currency_id - lines = self.browse(list(pairs[0])) - return lines.prepare_move_lines_for_reconciliation_widget(target_currency=target_currency) + rec_prop += self.browse(list(set(pairs[0]))) + + if len(rec_prop) > 0: + # Return lines formatted + return rec_prop.prepare_move_lines_for_reconciliation_widget(target_currency=target_currency) return [] @api.model diff --git a/addons/account/models/account_payment.py b/addons/account/models/account_payment.py index d43d767ee69..4bae1793ddd 100644 --- a/addons/account/models/account_payment.py +++ b/addons/account/models/account_payment.py @@ -298,11 +298,18 @@ class account_payment(models.Model): def open_payment_matching_screen(self): # Open reconciliation view for customers/suppliers - action_context = {'show_mode_selector': False, 'company_ids': [self.company_id.id], 'partner_ids': [self.partner_id.commercial_partner_id.id]} + move_line_id = False + for move_line in self.move_line_ids: + if move_line.account_id.reconcile: + move_line_id = move_line.id + break; + action_context = {'company_ids': [self.company_id.id], 'partner_ids': [self.partner_id.commercial_partner_id.id]} if self.partner_type == 'customer': action_context.update({'mode': 'customers'}) elif self.partner_type == 'supplier': action_context.update({'mode': 'suppliers'}) + if move_line_id: + action_context.update({'move_line_id': move_line_id}) return { 'type': 'ir.actions.client', 'tag': 'manual_reconciliation_view', diff --git a/addons/account/static/src/js/reconciliation/reconciliation_action.js b/addons/account/static/src/js/reconciliation/reconciliation_action.js index 8763d5acaa1..fabfee1ad00 100644 --- a/addons/account/static/src/js/reconciliation/reconciliation_action.js +++ b/addons/account/static/src/js/reconciliation/reconciliation_action.js @@ -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); + } } }); } diff --git a/addons/account/static/src/js/reconciliation/reconciliation_model.js b/addons/account/static/src/js/reconciliation/reconciliation_model.js index 019e761f3d3..864037a65ef 100644 --- a/addons/account/static/src/js/reconciliation/reconciliation_model.js +++ b/addons/account/static/src/js/reconciliation/reconciliation_model.js @@ -1061,6 +1061,7 @@ var ManualModel = StatementModel.extend({ model: 'account.move.line', method: 'get_data_for_manual_reconciliation', args: args, + context: context, }) .then(function (result) { var defs = _.map(result, self._formatLine.bind(self, context.mode)); @@ -1073,6 +1074,7 @@ var ManualModel = StatementModel.extend({ model: 'account.move.line', method: 'get_data_for_manual_reconciliation', args: ['account', self.account_ids], + context: context, }) .then(function (result) { var defs = _.map(result, self._formatLine.bind(self, 'accounts')); @@ -1091,6 +1093,7 @@ var ManualModel = StatementModel.extend({ model: 'account.move.line', method: 'get_data_for_manual_reconciliation_widget', args: [partner_ids, account_ids], + context: context, }) .then(function (result) { var defs = _.map(result.accounts, self._formatLine.bind(self, 'accounts')); @@ -1269,6 +1272,10 @@ var ManualModel = StatementModel.extend({ this._super(line, props); if (props.length) { _.each(props, function (prop) { + var tmp_value = prop.debit || prop.credit; + prop.credit = prop.credit !== 0 ? 0 : tmp_value; + prop.debit = prop.debit !== 0 ? 0 : tmp_value; + prop.amount = -prop.amount; prop.journal_id = self._formatNameGet(prop.journal_id || line.journal_id); }); } diff --git a/addons/account/static/src/js/reconciliation/reconciliation_renderer.js b/addons/account/static/src/js/reconciliation/reconciliation_renderer.js index 2530a6043c2..d9f1f8ad5a4 100644 --- a/addons/account/static/src/js/reconciliation/reconciliation_renderer.js +++ b/addons/account/static/src/js/reconciliation/reconciliation_renderer.js @@ -260,10 +260,13 @@ var LineRenderer = Widget.extend(FieldManagerMixin, { 'click .accounting_view .line_info_button.fa-exclamation-triangle': '_onTogglePartialReconcile', 'click .reconcile_model_create': '_onCreateReconcileModel', 'click .reconcile_model_edit': '_onEditReconcileModel', + 'keyup input': '_onInputKeyup', + 'blur input': '_onInputKeyup', }, custom_events: _.extend({}, FieldManagerMixin.custom_events, { 'field_changed': '_onFieldChanged', }), + _avoidFieldUpdate: {}, /** * create partner_id field in editable mode @@ -407,6 +410,7 @@ var LineRenderer = Widget.extend(FieldManagerMixin, { this.model.notifyChanges(this.handleCreateRecord, state.createForm); var record = this.model.get(this.handleCreateRecord); _.each(this.fields, function (field, fieldName) { + if (self._avoidFieldUpdate[fieldName]) return; if (fieldName === "partner_id") return; if ((data[fieldName] || state.createForm[fieldName]) && !_.isEqual(state.createForm[fieldName], data[fieldName])) { field.reset(record); @@ -598,6 +602,32 @@ var LineRenderer = Widget.extend(FieldManagerMixin, { _onFilterChange: function () { this.trigger_up('change_filter', {'data': _.str.strip($(event.target).val())}); }, + /** + * @private + * @param {keyup event} event + */ + _onInputKeyup: function (event) { + if(event.keyCode === 13) { + if (_.findWhere(this.model.lines, {mode: 'create'}).balance.amount) { + this._onCreateProposition(); + } + return; + } + + var self = this; + for (var fieldName in this.fields) { + var field = this.fields[fieldName]; + if (!field.$el.is(event.target)) { + continue; + } + this._avoidFieldUpdate[field.name] = event.type !== 'focusout'; + field.value = false; + field._setValue($(event.target).val()).then(function () { + self._avoidFieldUpdate[field.name] = false; + }); + break; + } + }, /** * @private */ diff --git a/addons/account/static/tests/reconciliation_tests.js b/addons/account/static/tests/reconciliation_tests.js index 511656906d9..cdf32c4010e 100644 --- a/addons/account/static/tests/reconciliation_tests.js +++ b/addons/account/static/tests/reconciliation_tests.js @@ -995,9 +995,9 @@ QUnit.module('account', { " Agrolait 101200 ", "should display the partner and the account code as title"); - assert.strictEqual(clientAction.$('.o_reconciliation_line:first .match tr:first .cell_left').text(), + assert.strictEqual(clientAction.$('.o_reconciliation_line:first .match tr:first .cell_right').text(), "$ 11,000.00", "sould display the line in $"); - assert.strictEqual(clientAction.$('.o_reconciliation_line:first .match tr:first .cell_left .o_multi_currency').data('content'), + assert.strictEqual(clientAction.$('.o_reconciliation_line:first .match tr:first .cell_right .o_multi_currency').data('content'), "10,222.00 €", "sould display the monetary information in €"); assert.strictEqual(clientAction.$('.accounting_view:first .o_no_valid:visible').length, 1, "should display the skip button"); @@ -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"); diff --git a/addons/barcodes/static/src/js/barcode_events.js b/addons/barcodes/static/src/js/barcode_events.js index 04c03a41308..0f13c59fe66 100644 --- a/addons/barcodes/static/src/js/barcode_events.js +++ b/addons/barcodes/static/src/js/barcode_events.js @@ -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); }, }); diff --git a/addons/barcodes/static/src/js/barcode_field.js b/addons/barcodes/static/src/js/barcode_field.js index aa31b4d8261..7b9b29aa4c8 100644 --- a/addons/barcodes/static/src/js/barcode_field.js +++ b/addons/barcodes/static/src/js/barcode_field.js @@ -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', } diff --git a/addons/barcodes/static/src/js/barcode_form_view.js b/addons/barcodes/static/src/js/barcode_form_view.js index 73df8a3c03f..da90b198352 100644 --- a/addons/barcodes/static/src/js/barcode_form_view.js +++ b/addons/barcodes/static/src/js/barcode_form_view.js @@ -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}); + } }); }); }, @@ -321,8 +394,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(); }; @@ -361,6 +432,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'); diff --git a/addons/barcodes/static/tests/barcode_tests.js b/addons/barcodes/static/tests/barcode_tests.js new file mode 100644 index 00000000000..7487972ea62 --- /dev/null +++ b/addons/barcodes/static/tests/barcode_tests.js @@ -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: '
' + + '
' + + '
' + + '
', + 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: '
', + 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: '
', + 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: '
' + + '' + + '' + + '', + 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: '
' + + '' + + '' + + '', + 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: '
' + + '' + + '' + + '' + + '', + 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: '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '', + 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; +}); +}); diff --git a/addons/barcodes/views/barcodes_templates.xml b/addons/barcodes/views/barcodes_templates.xml index 420a069a491..cb16a40c178 100644 --- a/addons/barcodes/views/barcodes_templates.xml +++ b/addons/barcodes/views/barcodes_templates.xml @@ -10,4 +10,10 @@ +