diff --git a/om_quick_add/README.rst b/om_quick_add/README.rst new file mode 100644 index 00000000..9ce5bfca --- /dev/null +++ b/om_quick_add/README.rst @@ -0,0 +1,19 @@ +================== +Quick Add Products +================== + +Quick ways to add products to a document with lines, next to the Catalog button of its lines: + +* **Paste lines**: rows copied from Excel, an email or a message, one product per row with its barcode, + reference or name, the quantity and, if wanted, the price. The rows are checked first: found, to choose + between several products, or not found. +* **Scan to add**: a barcode scanned outside a text field adds the product, or raises its quantity by one. +* **History**: the products the customer bought (or the vendor supplied) with their last date, quantity and + price; type the quantities to add, fill the last quantities, or repeat the last document. +* **Copy lines**: the lines of another document, all or some, at today's prices or the prices copied. + +A product already on the document, in the same unit and at the same price, gets its quantity raised instead +of a second line. A price pasted or kept stays on the line like a price typed by hand. + +The documents come with their own modules, installed by themselves with their app: Quick Add Products - Sales +(sales orders), - Purchase (purchase orders), - Invoicing (invoices and bills) and - Inventory (transfers). diff --git a/om_quick_add/__init__.py b/om_quick_add/__init__.py new file mode 100644 index 00000000..9b429614 --- /dev/null +++ b/om_quick_add/__init__.py @@ -0,0 +1,2 @@ +from . import models +from . import wizard diff --git a/om_quick_add/__manifest__.py b/om_quick_add/__manifest__.py new file mode 100644 index 00000000..d7f0a96f --- /dev/null +++ b/om_quick_add/__manifest__.py @@ -0,0 +1,31 @@ +{ + 'name': 'Quick Add Products', + 'version': '20.0.1.0.0', + 'category': 'Productivity', + 'summary': 'Add products to sales orders, purchase orders, invoices, bills and transfers in seconds: ' + 'paste a list from Excel or an email, scan barcodes, re-order from the customer or vendor history, ' + 'copy lines from another document', + 'description': 'Paste lines: rows of codes, barcodes or names with quantities and prices, from Excel, an email ' + 'or a message, checked before they are added. Scan to add: a scanned product is added to the ' + 'document, or its quantity raised. History: the products the customer bought or the vendor ' + 'supplied, with their last date, quantity and price, added again in one click. Copy lines: the ' + 'lines of any other order, invoice, bill or transfer.', + 'author': 'Odoo Mates', + 'maintainer': 'Odoo Mates', + 'support': 'odoomates@gmail.com', + 'license': 'LGPL-3', + 'depends': ['product', 'barcodes'], + 'data': [ + 'security/ir.access.csv', + 'wizard/quick_add_paste_views.xml', + 'wizard/quick_add_history_views.xml', + 'wizard/quick_add_copy_views.xml', + ], + 'assets': { + 'web.assets_backend': [ + 'om_quick_add/static/src/**/*', + ], + }, + 'installable': True, + 'application': False, +} diff --git a/om_quick_add/models/__init__.py b/om_quick_add/models/__init__.py new file mode 100644 index 00000000..fc5c9bf8 --- /dev/null +++ b/om_quick_add/models/__init__.py @@ -0,0 +1 @@ +from . import quick_add_mixin diff --git a/om_quick_add/models/quick_add_mixin.py b/om_quick_add/models/quick_add_mixin.py new file mode 100644 index 00000000..68372ec7 --- /dev/null +++ b/om_quick_add/models/quick_add_mixin.py @@ -0,0 +1,517 @@ +import re + +from odoo import _, api, fields, models +from odoo.exceptions import UserError +from odoo.fields import Command, Domain +from odoo.tools import float_compare +from odoo.tools.sql import escape_like_value + +SEARCH_LIMIT = 8 +HISTORY_LINES = 2000 +HISTORY_PRODUCTS = 300 + + +def clean_context(context): + """Only the user's settings of a context: the list of lines of a form gives its buttons the defaults + and the views of a new line and other keys of its own, which must not reach the dialogs nor the + lines they add.""" + return {key: context[key] for key in ('lang', 'tz', 'uid', 'allowed_company_ids') if key in context} + + +def parse_number(text): + """A quantity or a price as people type it: 2, 2.5, 2,5, 1,250.00, 1.250,00 or 1 250; None if it is not + a number. A lone comma is a decimal comma.""" + text = re.sub(r"[\s\u00a0\u202f']", '', text or '') + if not re.fullmatch(r'-?\d+(?:[.,]\d+)*', text): + return None + if ',' in text and '.' in text: + decimal = ',' if text.rfind(',') > text.rfind('.') else '.' + text = text.replace('.' if decimal == ',' else ',', '').replace(decimal, '.') + elif text.count(',') > 1 or text.count('.') > 1: + text = text.replace(',', '').replace('.', '') + else: + text = text.replace(',', '.') + return float(text) + + +SEPARATOR_TOKENS = {'x', 'X', '×', '*', ':', '=', '-'} + + +def split_cells(row): + """The cells of a row copied from a spreadsheet (tabs) or written as a list (semicolons, commas + between words); None for a row of words and numbers separated by spaces.""" + if '\t' in row: + cells = row.split('\t') + elif ';' in row: + cells = row.split(';') + elif re.search(r',\s*\D|\D\s*,', row): + cells = row.split(',') + else: + return None + return [cell.strip() for cell in cells if cell.strip()] + + +def row_candidates(row): + """The ways to read a row, as [(reference, quantity, price)], the one with the most numbers first.""" + cells = split_cells(row) + if cells is not None: + if not cells: + return [] + numbers = [parse_number(cell) for cell in cells] + ref_index = next((i for i, number in enumerate(numbers) if number is None), 0) + before = [n for n in numbers[:ref_index] if n is not None] + after = [n for n in numbers[ref_index + 1:] if n is not None] + quantity = (after[:1] or before[:1] or [None])[0] + price = after[1] if len(after) > 1 else None + return [(cells[ref_index], quantity, price)] + tokens = row.split() + candidates = [] + # numbers at the end: quantity, then price + trailing = 0 + while trailing < min(2, len(tokens) - 1) and parse_number(tokens[-1 - trailing]) is not None: + trailing += 1 + for count in range(trailing, -1, -1): + ref_tokens = tokens[:len(tokens) - count] + while len(ref_tokens) > 1 and ref_tokens[-1] in SEPARATOR_TOKENS: + ref_tokens = ref_tokens[:-1] + numbers = [parse_number(t) for t in tokens[len(tokens) - count:]] + candidates.append((' '.join(ref_tokens), numbers[0] if numbers else None, + numbers[1] if len(numbers) > 1 else None)) + # a quantity first: "5 Desk", "5 x Desk", "5x Desk" + match = re.match(r'^(\d[\d.,]*)\s*(?:[xX×*]\s+|\s+)(.*\D.*)$', row) + if match and parse_number(match.group(1)) is not None: + candidates.append((match.group(2).strip(), parse_number(match.group(1)), None)) + return candidates + + +class OmQuickAddMixin(models.AbstractModel): + """Quick ways to add products to a document with lines: paste a list, scan barcodes, the history of + the partner, the lines of another document. A document inherits this mixin and says where its + lines are and how a line is made.""" + _name = 'om.quick.add.mixin' + _description = 'Quick Add Products' + + # the lines of the document and their quantity field + _om_qa_line_field = False + _om_qa_quantity_field = False + # whether the lines have a price + _om_qa_has_prices = True + + om_quick_add_ok = fields.Boolean(compute='_compute_om_quick_add_ok') + + def _compute_om_quick_add_ok(self): + for record in self: + record.om_quick_add_ok = record._om_qa_editable() + + # ------------------------------------------------------------------ + # What a document says + # ------------------------------------------------------------------ + + def _om_qa_editable(self): + """Whether lines may be added.""" + return True + + def _om_qa_partner(self): + """The customer or vendor whose history is shown.""" + return self.env['res.partner'] + + def _om_qa_product_domain(self): + """The products the document may take.""" + return Domain('company_id', 'in', [False, self.company_id.id]) + + def _om_qa_code_domain(self, code): + """Other references of a product for this document, such as the code of the vendor; None if none.""" + return None + + def _om_qa_lines(self): + """The product lines of the document.""" + raise NotImplementedError() + + def _om_qa_line_data(self, line): + """{'product', 'quantity', 'uom', 'price_unit', 'discount', 'date', 'document'} of a line, of this + document or of another one of the same kind.""" + raise NotImplementedError() + + def _om_qa_new_line_vals(self, product, quantity, uom, price_unit, discount): + """The values of a new line; uom, price_unit and discount may be None: the defaults apply.""" + raise NotImplementedError() + + def _om_qa_history_lines(self): + """The lines of the earlier documents of the partner, of the kind of this one.""" + return self.env[self._fields[self._om_qa_line_field].comodel_name] + + # ------------------------------------------------------------------ + # Finding products + # ------------------------------------------------------------------ + + def _om_qa_exact_domains(self, ref): + domains = [Domain('barcode', '=', ref), Domain('default_code', '=ilike', escape_like_value(ref))] + code_domain = self._om_qa_code_domain(ref) + if code_domain is not None: + domains.append(code_domain) + return domains + + def _om_qa_find_products(self, ref, exact_only=False): + """The products a reference designates: by barcode, internal reference or another code first, + then by name; several when it is ambiguous, none when nothing matches.""" + ref = (ref or '').strip() + if not ref: + return self.env['product.product'] + Product = self.env['product.product'] + base = Domain(self._om_qa_product_domain()) + for domain in self._om_qa_exact_domains(ref): + products = Product.search(base & domain, limit=SEARCH_LIMIT) + if products: + return products + if exact_only: + return Product + products = Product.search(base & Domain('name', '=ilike', escape_like_value(ref)), limit=SEARCH_LIMIT) + if products: + return products + return Product.search(base & (Domain('name', 'ilike', ref) | Domain('default_code', 'ilike', ref)), + limit=SEARCH_LIMIT) + + # ------------------------------------------------------------------ + # Adding lines + # ------------------------------------------------------------------ + + def _om_qa_check_editable(self): + for record in self: + if not record._om_qa_editable(): + raise UserError(_("Products can no longer be added to %s.", record.display_name)) + + def _om_qa_same(self, value, other, digits='Product Price'): + if value is None: + return True + precision = self.env['decimal.precision'].precision_get(digits) + return not float_compare(value or 0.0, other or 0.0, precision_digits=precision) + + def _om_qa_add(self, items): + """Add products: items are {'product', 'quantity'} with optional 'uom', 'price_unit' and + 'discount'. A product already on the document, in the same unit and at the same price, gets its + quantity raised instead of a second line. Returns (lines added, lines raised).""" + self.ensure_one() + self._om_qa_check_editable() + # the same product twice in the items: one line + merged = {} + for item in items: + product = item.get('product') + quantity = item.get('quantity') or 0.0 + if not product or quantity <= 0: + continue + uom = item.get('uom') or None + price = item.get('price_unit') if self._om_qa_has_prices else None + discount = item.get('discount') if self._om_qa_has_prices else None + key = (product.id, uom and uom.id, price, discount) + if key in merged: + merged[key]['quantity'] += quantity + else: + merged[key] = {'product': product, 'quantity': quantity, 'uom': uom, 'price_unit': price, + 'discount': discount} + lines = [(line, self._om_qa_line_data(line)) for line in self._om_qa_lines()] + quantities = {} + creates = [] + prices = [] + for item in merged.values(): + match = next((line for line, data in lines + if data['product'] == item['product'] + and (item['uom'] is None or data['uom'] == item['uom']) + and self._om_qa_same(item['price_unit'], data.get('price_unit')) + and self._om_qa_same(item['discount'], data.get('discount'), 'Discount')), None) + if match: + quantities[match.id] = quantities.get(match.id, match[self._om_qa_quantity_field]) + item['quantity'] + else: + creates.append(Command.create(self._om_qa_new_line_vals( + item['product'], item['quantity'], item['uom'], None, None))) + prices.append(self._om_qa_price_vals(item['price_unit'], item['discount'])) + commands = [Command.update(line_id, {self._om_qa_quantity_field: quantity}) + for line_id, quantity in quantities.items()] + creates + if commands: + before = set(self._om_qa_lines().ids) + self.write({self._om_qa_line_field: commands}) + # the prices given are written after the lines are made, as a user types them: kept as + # set by hand, not computed again when the quantity changes + new_lines = sorted(set(self._om_qa_lines().ids) - before) + updates = [Command.update(line_id, vals) for line_id, vals in zip(new_lines, prices) if vals] + if updates: + self.write({self._om_qa_line_field: updates}) + return len(creates), len(quantities) + + def _om_qa_price_vals(self, price_unit, discount): + """The values of a price and a discount given for a new line; None for the default.""" + vals = {} + if price_unit is not None: + vals['price_unit'] = price_unit + if discount is not None: + vals['discount'] = discount + return vals + + def om_quick_add_scan(self, barcode): + """A scanned barcode: the product added, or its quantity raised by one.""" + self.ensure_one() + products = self._om_qa_find_products(barcode, exact_only=True) + if not products: + return {'type': 'warning', 'message': _("No product with the barcode or reference %s.", barcode)} + if len(products) > 1: + return {'type': 'warning', + 'message': _("Several products have the barcode or reference %s.", barcode)} + added, _raised = self._om_qa_add([{'product': products, 'quantity': 1.0}]) + message = _("%s added.", products.display_name) if added else _("%s: one more.", products.display_name) + return {'type': 'success', 'message': message} + + # ------------------------------------------------------------------ + # History + # ------------------------------------------------------------------ + + def _om_qa_history(self): + """[{'product', 'uom', 'date', 'document', 'quantity', 'price_unit', 'discount', 'count', + 'total'}] per product (and unit) the partner had, the latest first.""" + self.ensure_one() + if not self._om_qa_partner(): + return [] + result = {} + for line in self._om_qa_history_lines()[:HISTORY_LINES]: + data = self._om_qa_line_data(line) + key = (data['product'].id, data['uom'].id) + entry = result.get(key) + if entry is None: + entry = result[key] = {**data, 'count': 0, 'total': 0.0, 'documents': set()} + elif data['date'] and (not entry['date'] or data['date'] > entry['date']): + entry.update({k: data[k] for k in ('date', 'document', 'quantity', 'price_unit', 'discount')}) + entry['documents'].add(data['document'].id) + entry['total'] += data['quantity'] + entries = list(result.values()) + for entry in entries: + entry['count'] = len(entry.pop('documents')) + entries.sort(key=lambda e: (e['date'] or fields.Date.to_date('1900-01-01'), e['document'].id), reverse=True) + return entries[:HISTORY_PRODUCTS] + + # ------------------------------------------------------------------ + # Copy lines + # ------------------------------------------------------------------ + + @api.model + def _om_qa_copy_models(self): + """[(model, label)] of the documents lines can be copied from.""" + mixin = self.pool['om.quick.add.mixin'] + models_ = [(name, self.env[name]._om_qa_copy_label()) for name, cls in self.pool.items() + if not cls._abstract and not cls._transient and issubclass(cls, mixin)] + return sorted(models_, key=lambda m: m[1]) + + @api.model + def _om_qa_copy_label(self): + """The name of the documents in the Copy lines picker.""" + return self.env['ir.model']._get(self._name).name + + # ------------------------------------------------------------------ + # Reading a row: "FURN_8888 4 35", "3 x Office Lamp", a barcode... + # ------------------------------------------------------------------ + + def _om_qa_read_row(self, row): + """{'ref', 'quantity', 'price_unit', 'products'} of a row: the reading that designates one product, + else the first that finds some, else the first; None for an empty row.""" + candidates = row_candidates(row) + if not candidates: + return None + readings = [] + for ref, quantity, price in candidates: + products = self._om_qa_find_products(ref) + readings.append((ref, quantity, price, products)) + if len(products) == 1: + break + ref, quantity, price, products = next((r for r in readings if len(r[3]) == 1), None) \ + or next((r for r in readings if r[3]), None) or readings[0] + return { + 'ref': ref, + 'quantity': quantity if quantity and quantity > 0 else 1.0, + 'price_unit': price if self._om_qa_has_prices else None, + 'products': products, + } + + # ------------------------------------------------------------------ + # The add bar + # ------------------------------------------------------------------ + + def _om_qa_bar_price(self, product): + """The price shown next to a product in the add bar; None for documents without prices.""" + return product.lst_price if self._om_qa_has_prices else None + + def _om_qa_bar_product(self, product): + values = { + 'id': product.id, + 'name': product.display_name, + 'code': product.default_code or '', + 'price': self._om_qa_bar_price(product), + 'uom': product.uom_id.name, + } + if 'qty_available' in product._fields and product.is_storable: + values['on_hand'] = product.qty_available + return values + + def _om_qa_bar_search_products(self, ref, limit=SEARCH_LIMIT): + """The products matching what is typed: the exact codes first, then the names.""" + ref = (ref or '').strip() + Product = self.env['product.product'] + if not ref: + return Product + base = Domain(self._om_qa_product_domain()) + found = Product + for domain in self._om_qa_exact_domains(ref): + found |= Product.search(base & domain, limit=limit) + if len(found) < limit: + found |= Product.search(base & (Domain('name', 'ilike', ref) | Domain('default_code', 'ilike', ref)) + & Domain('id', 'not in', found.ids), limit=limit - len(found)) + return found[:limit] + + def _om_qa_bar_result(self, added, raised, product=None): + if product and added: + return _("%s added.", product.display_name) + if product and raised: + return _("%s: quantity raised.", product.display_name) + parts = [] + if added: + parts.append(_("%s product(s) added", added)) + if raised: + parts.append(_("%s quantity(ies) raised", raised)) + return ", ".join(parts) + "." if parts else _("Nothing to add.") + + def om_quick_add_bar_data(self): + """What the add bar shows before anything is typed: the history of the partner per product, + and its usual products.""" + self.ensure_one() + entries = self._om_qa_history() if self._om_qa_partner() else [] + history = {} + for entry in entries: + history.setdefault(entry['product'].id, { + 'last_quantity': entry['quantity'], + 'last_price': entry.get('price_unit'), + 'count': entry['count'], + 'date': fields.Date.to_string(entry['date']) if entry['date'] else False, + }) + usual = sorted(entries, key=lambda e: (e['count'], e['date'] or fields.Date.to_date('1900-01-01')), + reverse=True)[:12] + return { + 'has_prices': self._om_qa_has_prices, + 'history': history, + 'usual': [self._om_qa_bar_product(entry['product']) for entry in usual], + 'has_last': bool(entries), + } + + def om_quick_add_bar_search(self, query): + """The products for what is typed, and the quantity and price typed with them.""" + self.ensure_one() + candidates = row_candidates(query or '') + ref, quantity, price = candidates[0] if candidates else ('', None, None) + products = self._om_qa_bar_search_products(ref) + if not products and len(candidates) > 1: + # "Desk 2000": the number is part of the name + ref, quantity, price = candidates[-1] + products = self._om_qa_bar_search_products(ref) + return { + 'quantity': quantity if quantity and quantity > 0 else 1.0, + 'price': price if self._om_qa_has_prices else None, + 'products': [self._om_qa_bar_product(product) for product in products], + } + + def om_quick_add_bar_add(self, product_id, quantity=1.0, price=None): + """Add one product chosen in the add bar.""" + self.ensure_one() + product = self.env['product.product'].browse(product_id).exists() + if not product: + return {'type': 'warning', 'message': _("This product no longer exists.")} + added, raised = self._om_qa_add([{'product': product, 'quantity': quantity or 1.0, 'price_unit': price}]) + return {'type': 'success', 'message': self._om_qa_bar_result(added, raised, product), 'product_id': product.id} + + def om_quick_add_bar_enter(self, query): + """Enter in the add bar without a product chosen: a code or a scan adds its product at once; + several products are given back to choose from.""" + self.ensure_one() + reading = self._om_qa_read_row(query or '') + if not reading or not reading['products']: + return {'type': 'warning', 'message': _("Nothing found for %s.", (query or '').strip())} + products = reading['products'] + if len(products) > 1: + return {'choices': [self._om_qa_bar_product(p) for p in products], + 'quantity': reading['quantity'], 'price': reading['price_unit']} + return self.om_quick_add_bar_add(products.id, reading['quantity'], reading['price_unit']) + + def om_quick_add_bar_paste(self, text): + """Rows pasted in the add bar: those naming one product are added, the others are given back to + choose from.""" + self.ensure_one() + items, pending = [], [] + for row in (text or '').splitlines(): + reading = self._om_qa_read_row(row) + if not reading: + continue + if len(reading['products']) == 1: + items.append({'product': reading['products'], 'quantity': reading['quantity'], + 'price_unit': reading['price_unit']}) + else: + pending.append({'row': row.strip(), 'quantity': reading['quantity'], 'price': reading['price_unit'], + 'choices': [self._om_qa_bar_product(p) for p in reading['products']]}) + added, raised = self._om_qa_add(items) if items else (0, 0) + return {'type': 'success' if items else 'warning', 'message': self._om_qa_bar_result(added, raised), + 'pending': pending} + + def om_quick_add_bar_usual(self, mode): + """The usual products of the partner at their last quantities ('usual'), or every line of its last + document ('last').""" + self.ensure_one() + entries = self._om_qa_history() if self._om_qa_partner() else [] + if mode == 'last': + last = entries[0]['document'] if entries else False + items = [{'product': data['product'], 'quantity': data['quantity'], 'uom': data['uom']} + for data in map(last._om_qa_line_data, last._om_qa_lines())] if last else [] + else: + usual = sorted(entries, key=lambda e: (e['count'], e['date'] or fields.Date.to_date('1900-01-01')), + reverse=True)[:12] + items = [{'product': e['product'], 'quantity': e['quantity'], 'uom': e['uom']} for e in usual] + added, raised = self._om_qa_add(items) if items else (0, 0) + return {'type': 'success' if items else 'warning', 'message': self._om_qa_bar_result(added, raised)} + + # ------------------------------------------------------------------ + # Actions + # ------------------------------------------------------------------ + + def _om_qa_open(self, wizard_model, title): + self.ensure_one() + self._om_qa_check_editable() + wizard = self.env[wizard_model].create({'res_model': self._name, 'res_id': self.id}) + wizard._om_qa_load() + return wizard._om_qa_action(title) + + def om_action_quick_paste(self): + return self._om_qa_open('om.quick.add.paste', _("Paste lines")) + + def om_action_quick_history(self): + self.ensure_one() + return self._om_qa_open('om.quick.add.history', _("History of %s", self._om_qa_partner().display_name)) + + def om_action_quick_copy(self): + return self._om_qa_open('om.quick.add.copy', _("Copy lines")) + + +class OmQuickAddLineMixin(models.AbstractModel): + """The lines of a document: the Quick Add buttons of the list of lines run here, on the lines, and + open the dialogs of the document given in the context (om_quick_add_id).""" + _name = 'om.quick.add.line.mixin' + _description = 'Quick Add Products: Lines' + + # the model of the document of the lines + _om_qa_document_model = False + + def _om_qa_document_from_context(self): + document = self.env[self._om_qa_document_model].browse(self.env.context.get('om_quick_add_id')) + if not document.exists(): + raise UserError(_("Save the document first.")) + return document.with_context(clean_context(self.env.context)) + + def om_action_quick_paste(self): + return self._om_qa_document_from_context().om_action_quick_paste() + + def om_action_quick_history(self): + return self._om_qa_document_from_context().om_action_quick_history() + + def om_action_quick_copy(self): + return self._om_qa_document_from_context().om_action_quick_copy() diff --git a/om_quick_add/security/ir.access.csv b/om_quick_add/security/ir.access.csv new file mode 100644 index 00000000..c13551e8 --- /dev/null +++ b/om_quick_add/security/ir.access.csv @@ -0,0 +1,7 @@ +id,name,model_id,group_id/id,operation,domain +access_om_quick_add_paste,om.quick.add.paste user,om.quick.add.paste,base.group_user,crud, +access_om_quick_add_paste_line,om.quick.add.paste.line user,om.quick.add.paste.line,base.group_user,crud, +access_om_quick_add_history,om.quick.add.history user,om.quick.add.history,base.group_user,crud, +access_om_quick_add_history_line,om.quick.add.history.line user,om.quick.add.history.line,base.group_user,crud, +access_om_quick_add_copy,om.quick.add.copy user,om.quick.add.copy,base.group_user,crud, +access_om_quick_add_copy_line,om.quick.add.copy.line user,om.quick.add.copy.line,base.group_user,crud, diff --git a/om_quick_add/static/src/add_bar.js b/om_quick_add/static/src/add_bar.js new file mode 100644 index 00000000..d9ec107c --- /dev/null +++ b/om_quick_add/static/src/add_bar.js @@ -0,0 +1,319 @@ +import { Component, proxy, signal, useProps } from "@odoo/owl"; +import { useHotkey } from "@web/core/hotkeys/hotkey_hook"; +import { _t } from "@web/core/l10n/translation"; +import { registry } from "@web/core/registry"; +import { useService } from "@web/core/utils/hooks"; +import { useDebounced } from "@web/core/utils/timing"; +import { formatFloat } from "@web/views/fields/formatters"; +import { standardWidgetProps } from "@web/views/widgets/standard_widget_props"; + +/** + * The add bar, above the lines of a document: type a name or a code with a quantity and Enter, paste rows, + * or scan into it. Empty, it lists the usual products of the partner. + */ +export class QuickAddBar extends Component { + static template = "om_quick_add.AddBar"; + props = useProps({ ...standardWidgetProps }); + inputRef = signal.ref(); + + setup() { + this.orm = useService("orm"); + this.state = proxy({ + query: "", + open: false, + results: [], + resultsFor: null, + parsed: { quantity: 1, price: null }, + active: 0, + pending: [], + flash: null, + usualOpen: false, + data: null, + }); + this.searchSeq = 0; + this.lastProduct = null; + this.debouncedSearch = useDebounced((query) => this.runSearch(query), 200); + useHotkey("alt+shift+a", () => this.inputRef()?.focus(), { bypassEditableProtection: true }); + } + + get record() { + return this.props.record; + } + + get visible() { + return !this.props.readonly && this.record.data.om_quick_add_ok; + } + + get items() { + if (this.state.query.trim()) { + return this.state.resultsFor === this.state.query ? this.state.results : []; + } + return this.state.data?.usual || []; + } + + get parsedLabel() { + const { quantity, price } = this.state.parsed; + if (!this.state.query.trim() || (quantity === 1 && price === null)) { + return ""; + } + let label = _t("Quantity %s", formatFloat(quantity, { digits: [16, 2] })); + if (price !== null && price !== undefined) { + label += " · " + _t("price %s", formatFloat(price, { digits: [16, 2] })); + } + return label; + } + + info(product) { + const parts = []; + if (product.code) { + parts.push(product.code); + } + if (product.price !== null && product.price !== undefined) { + parts.push(formatFloat(product.price, { digits: [16, 2] })); + } + const history = this.state.data?.history?.[product.id]; + if (history) { + let last = _t("last %s", formatFloat(history.last_quantity, { digits: [16, 2] })); + if (history.last_price !== null && history.last_price !== undefined && this.state.data.has_prices) { + last += " @ " + formatFloat(history.last_price, { digits: [16, 2] }); + } + parts.push(last + " · " + history.count + "×"); + } + if (product.on_hand !== undefined) { + parts.push(_t("on hand %s", formatFloat(product.on_hand, { digits: [16, 2] }))); + } + return parts.join(" · "); + } + + // ------------------------------------------------------------------ + // Server + // ------------------------------------------------------------------ + + async ensureSaved() { + const record = this.record; + if (record.isNew || (await record.isDirty())) { + return await record.save(); + } + return true; + } + + async call(method, args = []) { + if (!(await this.ensureSaved())) { + this.showFlash({ type: "warning", message: _t("Fill in the document first: it is saved before adding.") }); + return null; + } + return this.orm.call(this.record.resModel, method, [[this.record.resId], ...args]); + } + + async loadData() { + if (this.record.isNew) { + return; + } + this.state.data = await this.orm.call(this.record.resModel, "om_quick_add_bar_data", [[this.record.resId]]); + } + + async runSearch(query) { + const seq = ++this.searchSeq; + const result = await this.call("om_quick_add_bar_search", [query]); + if (!result || seq !== this.searchSeq) { + return; + } + this.state.results = result.products; + this.state.parsed = { quantity: result.quantity, price: result.price }; + this.state.resultsFor = query; + this.state.active = 0; + } + + async afterAdd(result, product = null) { + if (!result) { + return; + } + this.showFlash(result); + if (result.type === "success") { + if (product || result.product_id) { + this.lastProduct = product || { id: result.product_id }; + } + this.state.query = ""; + this.state.results = []; + this.state.resultsFor = null; + this.state.parsed = { quantity: 1, price: null }; + await this.record.load(); + } + // the list stays closed after an add, so the lines and the rows to choose are seen; typing or the + // arrow down opens it again + this.state.open = false; + const input = this.inputRef(); + if (input && document.activeElement !== input) { + this.skipOpen = true; + input.focus(); + } + } + + showFlash(result) { + this.state.flash = { type: result.type, message: result.message }; + clearTimeout(this.flashTimeout); + this.flashTimeout = setTimeout(() => (this.state.flash = null), 4000); + } + + // ------------------------------------------------------------------ + // Adding + // ------------------------------------------------------------------ + + async addProduct(product) { + let quantity = this.state.parsed.quantity; + let price = this.state.parsed.price; + if (!this.state.query.trim()) { + // from the usual products: the last quantity of the partner + quantity = this.state.data?.history?.[product.id]?.last_quantity || 1; + price = null; + } + const result = await this.call("om_quick_add_bar_add", [product.id, quantity, price]); + await this.afterAdd(result, product); + } + + async enter(query) { + if (!query.trim()) { + return; + } + const result = await this.call("om_quick_add_bar_enter", [query]); + if (result && result.choices) { + this.state.pending.unshift({ + row: query.trim(), + quantity: result.quantity, + price: result.price, + choices: result.choices, + }); + this.state.query = ""; + this.state.resultsFor = null; + return; + } + await this.afterAdd(result); + } + + async choose(item, productId) { + const result = await this.call("om_quick_add_bar_add", [productId, item.quantity, item.price]); + if (result && result.type === "success") { + this.state.pending = this.state.pending.filter((pending) => pending !== item); + } + await this.afterAdd(result); + } + + onChoose(item, ev) { + const productId = parseInt(ev.target.value, 10); + if (productId) { + this.choose(item, productId); + } + } + + closeUsualLater() { + setTimeout(() => (this.state.usualOpen = false), 200); + } + + dismiss(item) { + this.state.pending = this.state.pending.filter((pending) => pending !== item); + } + + async addUsual(mode) { + this.state.usualOpen = false; + const result = await this.call("om_quick_add_bar_usual", [mode]); + await this.afterAdd(result); + } + + // ------------------------------------------------------------------ + // Events + // ------------------------------------------------------------------ + + async onFocus() { + if (this.skipOpen) { + this.skipOpen = false; + } else { + this.state.open = true; + } + if (await this.ensureSaved()) { + if (!this.state.data) { + await this.loadData(); + } + } + } + + onBlur() { + this.state.open = false; + } + + onInput(ev) { + this.state.query = ev.target.value; + this.state.active = 0; + this.state.open = true; + if (this.state.query.trim()) { + this.debouncedSearch(this.state.query); + } else { + this.state.results = []; + this.state.resultsFor = null; + this.state.parsed = { quantity: 1, price: null }; + } + } + + onKeydown(ev) { + const items = this.items; + switch (ev.key) { + case "ArrowDown": + ev.preventDefault(); + if (!this.state.open) { + this.state.open = true; + break; + } + this.state.active = Math.min(this.state.active + 1, items.length - 1); + break; + case "ArrowUp": + ev.preventDefault(); + this.state.active = Math.max(this.state.active - 1, 0); + break; + case "Enter": { + ev.preventDefault(); + ev.stopPropagation(); + const query = ev.target.value; + // the list shown is the one of what is typed: add the product picked; a scan or a code + // typed faster than the search is resolved by the server + if (this.state.open && items.length && (!query.trim() || this.state.resultsFor === query)) { + this.addProduct(items[this.state.active] || items[0]); + } else { + this.enter(query); + } + break; + } + case "Escape": + if (this.state.query) { + ev.preventDefault(); + ev.stopPropagation(); + this.state.query = ""; + this.state.resultsFor = null; + } + this.state.open = false; + break; + case "+": + if (!this.state.query && this.lastProduct) { + ev.preventDefault(); + this.call("om_quick_add_bar_add", [this.lastProduct.id, 1, null]).then((result) => + this.afterAdd(result, this.lastProduct) + ); + } + break; + } + } + + async onPaste(ev) { + const text = ev.clipboardData?.getData("text") || ""; + if (!text.includes("\n")) { + return; + } + ev.preventDefault(); + const result = await this.call("om_quick_add_bar_paste", [text]); + if (!result) { + return; + } + this.state.pending.push(...result.pending); + await this.afterAdd(result); + } +} + +registry.category("view_widgets").add("om_quick_add_bar", { component: QuickAddBar }); diff --git a/om_quick_add/static/src/add_bar.xml b/om_quick_add/static/src/add_bar.xml new file mode 100644 index 00000000..3d0b95f1 --- /dev/null +++ b/om_quick_add/static/src/add_bar.xml @@ -0,0 +1,77 @@ + + + + +
+
+
+ + + +
+ +
+
+
+ +
+ Choose + Not found + + + +
+
+
+
+ + + diff --git a/om_quick_add/static/src/quick_add.scss b/om_quick_add/static/src/quick_add.scss new file mode 100644 index 00000000..e6d12e8c --- /dev/null +++ b/om_quick_add/static/src/quick_add.scss @@ -0,0 +1,40 @@ +.o_om_quick_add { + .o_om_quick_add_text textarea { + min-height: 14rem; + font-family: $font-family-monospace; + } + .o_om_quick_add_example { + background: transparent; + border-left: 3px solid $border-color; + padding-left: .75rem; + } +} + +.o_om_quick_add_bar { + .o_om_qab_input { + .o_om_qab_icon { + position: absolute; + left: .5rem; + top: 50%; + transform: translateY(-50%); + } + > input { + padding: .4rem .5rem .4rem 2rem; + border: 1px solid $border-color; + border-radius: $border-radius; + &:focus { + border-color: $primary; + } + } + } + .o_om_qab_menu { + max-height: 22rem; + overflow-y: auto; + .dropdown-item.active .o_om_qab_info { + color: inherit; + } + .o_om_qab_info { + color: $text-muted; + } + } +} diff --git a/om_quick_add/static/src/scanner.js b/om_quick_add/static/src/scanner.js new file mode 100644 index 00000000..f6ac42dd --- /dev/null +++ b/om_quick_add/static/src/scanner.js @@ -0,0 +1,47 @@ +import { Component, useListener, usePlugin, useProps } from "@odoo/owl"; +import { BarcodePlugin } from "@barcodes/barcode_plugin"; +import { registry } from "@web/core/registry"; +import { useService } from "@web/core/utils/hooks"; +import { standardWidgetProps } from "@web/views/widgets/standard_widget_props"; + +/** + * Scan to add: on a form carrying this widget, a barcode scanned outside a text field adds the + * product to the document, or raises its quantity. The document is saved first. + */ +export class QuickAddScanner extends Component { + static template = "om_quick_add.Scanner"; + props = useProps({ ...standardWidgetProps }); + + setup() { + this.orm = useService("orm"); + this.notification = useService("notification"); + // one scan after the other: a quick series of scans must not save the document twice at once + this.queue = Promise.resolve(); + const barcode = usePlugin(BarcodePlugin); + useListener(barcode.bus, "barcode_scanned", (ev) => { + const code = ev.detail.barcode; + this.queue = this.queue.then(() => this.add(code)).catch(() => {}); + }); + } + + async add(code) { + const record = this.props.record; + if (this.props.readonly || !record.data.om_quick_add_ok) { + return; + } + // a dialog open over the form (Paste lines, a line...) takes the scans, not the document behind it + if (!this.env.inDialog && document.querySelector(".o_dialog")) { + return; + } + if (record.isNew || (await record.isDirty())) { + if (!(await record.save())) { + return; + } + } + const result = await this.orm.call(record.resModel, "om_quick_add_scan", [[record.resId], code]); + await record.load(); + this.notification.add(result.message, { type: result.type }); + } +} + +registry.category("view_widgets").add("om_quick_add_scanner", { component: QuickAddScanner }); diff --git a/om_quick_add/static/src/scanner.xml b/om_quick_add/static/src/scanner.xml new file mode 100644 index 00000000..177fc825 --- /dev/null +++ b/om_quick_add/static/src/scanner.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/om_quick_add/wizard/__init__.py b/om_quick_add/wizard/__init__.py new file mode 100644 index 00000000..bde83d18 --- /dev/null +++ b/om_quick_add/wizard/__init__.py @@ -0,0 +1,4 @@ +from . import quick_add_wizard +from . import quick_add_paste +from . import quick_add_history +from . import quick_add_copy diff --git a/om_quick_add/wizard/quick_add_copy.py b/om_quick_add/wizard/quick_add_copy.py new file mode 100644 index 00000000..d291d9ff --- /dev/null +++ b/om_quick_add/wizard/quick_add_copy.py @@ -0,0 +1,77 @@ +from odoo import api, fields, models +from odoo.fields import Command + + +class OmQuickAddCopy(models.TransientModel): + _name = 'om.quick.add.copy' + _inherit = 'om.quick.add.wizard' + _description = 'Copy Lines' + + source_model = fields.Selection(selection='_selection_documents', string="Document type") + source_id = fields.Many2oneReference(model_field='source_model', string="Copy from") + several_models = fields.Boolean(compute='_compute_several_models') + keep_prices = fields.Boolean(string="Keep the prices", + help="Add the lines at the price of the document copied instead of today's price.") + line_ids = fields.One2many('om.quick.add.copy.line', 'wizard_id') + + @api.model + def _selection_documents(self): + return self.env['om.quick.add.mixin']._om_qa_copy_models() + + def _compute_several_models(self): + several = len(self._selection_documents()) > 1 + for wizard in self: + wizard.several_models = several + + def _om_qa_load(self): + self.source_model = self.res_model + + @api.onchange('source_model') + def _onchange_source_model(self): + self.source_id = False + + @api.onchange('source_model', 'source_id') + def _onchange_source_id(self): + commands = [Command.clear()] + source = self.env[self.source_model].browse(self.source_id) if self.source_model and self.source_id else False + if source and source == self._om_qa_document(): + self.source_id = False + self.line_ids = commands + return {'warning': {'title': self.env._("Copy lines"), + 'message': self.env._("This is the document itself: pick another one.")}} + if source: + for data in map(source._om_qa_line_data, source._om_qa_lines()): + commands.append(Command.create({ + 'product_id': data['product'].id, + 'uom_id': data['uom'].id, + 'source_quantity': data['quantity'], + 'quantity': data['quantity'], + 'price_unit': data.get('price_unit') or 0.0, + 'discount': data.get('discount') or 0.0, + })) + self.line_ids = commands + + def action_add(self): + self.ensure_one() + items = [{ + 'product': line.product_id, + 'quantity': line.quantity, + 'uom': line.uom_id if line.uom_id and line.uom_id._has_common_reference(line.product_id.uom_id) + else None, + 'price_unit': line.price_unit if self.keep_prices else None, + 'discount': line.discount if self.keep_prices else None, + } for line in self.line_ids if line.product_id and line.quantity > 0] + return self._om_qa_add_and_close(items) + + +class OmQuickAddCopyLine(models.TransientModel): + _name = 'om.quick.add.copy.line' + _description = 'Line to Copy' + + wizard_id = fields.Many2one('om.quick.add.copy', required=True, ondelete='cascade') + product_id = fields.Many2one('product.product', string="Product", readonly=True) + uom_id = fields.Many2one('uom.uom', string="Unit", readonly=True) + source_quantity = fields.Float(string="Quantity", digits='Product Unit', readonly=True) + quantity = fields.Float(string="Add", digits='Product Unit') + price_unit = fields.Float(string="Price", digits='Product Price', readonly=True) + discount = fields.Float(string="Disc. %", digits='Discount', readonly=True) diff --git a/om_quick_add/wizard/quick_add_copy_views.xml b/om_quick_add/wizard/quick_add_copy_views.xml new file mode 100644 index 00000000..827a7a71 --- /dev/null +++ b/om_quick_add/wizard/quick_add_copy_views.xml @@ -0,0 +1,43 @@ + + + + + om.quick.add.copy.form + om.quick.add.copy + +
+ + + + + + + + + + + +

+ Pick a document: its lines are listed here, to add all or some. +

+ + + + + + + + + + +
+
+ +
+
+ +
diff --git a/om_quick_add/wizard/quick_add_history.py b/om_quick_add/wizard/quick_add_history.py new file mode 100644 index 00000000..ba2d84d9 --- /dev/null +++ b/om_quick_add/wizard/quick_add_history.py @@ -0,0 +1,94 @@ +from odoo import api, fields, models +from odoo.fields import Command + + +class OmQuickAddHistory(models.TransientModel): + _name = 'om.quick.add.history' + _inherit = 'om.quick.add.wizard' + _description = 'Products Bought or Supplied Before' + + partner_id = fields.Many2one('res.partner', readonly=True) + keep_prices = fields.Boolean(string="Use the last prices", + help="Add the products at the price of their last line instead of today's price.") + line_ids = fields.One2many('om.quick.add.history.line', 'wizard_id') + last_document_ref = fields.Reference(selection='_selection_documents', readonly=True) + + @api.model + def _selection_documents(self): + return self.env['om.quick.add.mixin']._om_qa_copy_models() + + def _om_qa_load(self): + document = self._om_qa_document() + entries = document._om_qa_history() + lines = [Command.create({ + 'product_id': entry['product'].id, + 'uom_id': entry['uom'].id, + 'last_date': entry['date'], + 'last_document_ref': '%s,%s' % (entry['document']._name, entry['document'].id), + 'last_quantity': entry['quantity'], + 'last_price': entry.get('price_unit') or 0.0, + 'last_discount': entry.get('discount') or 0.0, + 'count': entry['count'], + 'total': entry['total'], + }) for entry in entries] + last = entries[0]['document'] if entries else False + self.write({ + 'partner_id': document._om_qa_partner().id, + 'line_ids': lines, + 'last_document_ref': '%s,%s' % (last._name, last.id) if last else False, + }) + + def _om_qa_items(self, lines): + return [{ + 'product': line.product_id, + 'quantity': line.quantity, + 'uom': line.uom_id, + 'price_unit': line.last_price if self.keep_prices else None, + 'discount': line.last_discount if self.keep_prices else None, + } for line in lines if line.quantity > 0] + + def action_fill_last(self): + for line in self.line_ids: + line.quantity = line.last_quantity + return self._om_qa_action(self.env._("History of %s", self.partner_id.display_name)) + + def action_add(self): + self.ensure_one() + return self._om_qa_add_and_close(self._om_qa_items(self.line_ids)) + + def action_repeat_last(self): + """Every line of the last document of the partner, at its quantity.""" + self.ensure_one() + last = self.last_document_ref + if not last: + return self._om_qa_action(self.env._("History of %s", self.partner_id.display_name)) + items = [{ + 'product': data['product'], + 'quantity': data['quantity'], + 'uom': data['uom'], + 'price_unit': data.get('price_unit') if self.keep_prices else None, + 'discount': data.get('discount') if self.keep_prices else None, + } for data in map(last._om_qa_line_data, last._om_qa_lines())] + return self._om_qa_add_and_close(items) + + +class OmQuickAddHistoryLine(models.TransientModel): + _name = 'om.quick.add.history.line' + _description = 'Product Bought or Supplied Before' + _order = 'last_date desc, id' + + wizard_id = fields.Many2one('om.quick.add.history', required=True, ondelete='cascade') + product_id = fields.Many2one('product.product', string="Product", readonly=True) + uom_id = fields.Many2one('uom.uom', string="Unit", readonly=True) + last_date = fields.Date(string="Last", readonly=True) + last_document_ref = fields.Reference(selection='_selection_documents', string="Document", readonly=True) + last_quantity = fields.Float(string="Last Qty", digits='Product Unit', readonly=True) + last_price = fields.Float(string="Last Price", digits='Product Price', readonly=True) + last_discount = fields.Float(string="Last Disc. %", digits='Discount', readonly=True) + count = fields.Integer(string="Times", readonly=True) + total = fields.Float(string="Total Qty", digits='Product Unit', readonly=True) + quantity = fields.Float(string="Add", digits='Product Unit') + + @api.model + def _selection_documents(self): + return self.env['om.quick.add.mixin']._om_qa_copy_models() diff --git a/om_quick_add/wizard/quick_add_history_views.xml b/om_quick_add/wizard/quick_add_history_views.xml new file mode 100644 index 00000000..0f3a57bf --- /dev/null +++ b/om_quick_add/wizard/quick_add_history_views.xml @@ -0,0 +1,49 @@ + + + + + om.quick.add.history.form + om.quick.add.history + +
+ +
+ The latest first. Type a quantity in Add. +
+ +
+
+
+ Nothing confirmed for this partner yet. +
+ + + + + + + + + + + + + + + +
+
+ +
+
+ +
diff --git a/om_quick_add/wizard/quick_add_paste.py b/om_quick_add/wizard/quick_add_paste.py new file mode 100644 index 00000000..c97c3e20 --- /dev/null +++ b/om_quick_add/wizard/quick_add_paste.py @@ -0,0 +1,88 @@ +from odoo import api, fields, models +from odoo.fields import Command + +class OmQuickAddPaste(models.TransientModel): + _name = 'om.quick.add.paste' + _inherit = 'om.quick.add.wizard' + _description = 'Paste Lines' + + text = fields.Text(string="Lines") + step = fields.Selection([('paste', "Paste"), ('check', "Check")], default='paste', required=True) + line_ids = fields.One2many('om.quick.add.paste.line', 'wizard_id') + found_count = fields.Integer(compute='_compute_counts') + open_count = fields.Integer(compute='_compute_counts') + + @api.depends('line_ids.state') + def _compute_counts(self): + for wizard in self: + wizard.found_count = len(wizard.line_ids.filtered(lambda l: l.state == 'found')) + wizard.open_count = len(wizard.line_ids) - wizard.found_count + + def _om_qa_read_row(self, document, row): + """The values of a pasted line for a row; None for an empty row.""" + reading = document._om_qa_read_row(row) + if not reading: + return None + products = reading['products'] + return { + 'row': row.strip(), + 'product_id': products.id if len(products) == 1 else False, + 'candidate_ids': [Command.set(products.ids if len(products) > 1 else [])], + 'quantity': reading['quantity'], + 'price_unit': reading['price_unit'] or 0.0, + 'has_price': reading['price_unit'] is not None, + } + + def action_check(self): + self.ensure_one() + document = self._om_qa_document() + lines = [] + for sequence, row in enumerate((self.text or '').splitlines()): + if not row.strip(): + continue + values = self._om_qa_read_row(document, row) + if values: + lines.append(Command.create({**values, 'sequence': sequence})) + self.write({'line_ids': [Command.clear()] + lines, 'step': 'check'}) + return self._om_qa_action(self.env._("Paste lines")) + + def action_back(self): + self.write({'line_ids': [Command.clear()], 'step': 'paste'}) + return self._om_qa_action(self.env._("Paste lines")) + + def action_add(self): + self.ensure_one() + items = [{ + 'product': line.product_id, + 'quantity': line.quantity, + 'price_unit': line.price_unit if line.has_price else None, + } for line in self.line_ids if line.product_id and line.quantity > 0] + return self._om_qa_add_and_close(items) + + +class OmQuickAddPasteLine(models.TransientModel): + _name = 'om.quick.add.paste.line' + _description = 'Pasted Line' + _order = 'sequence, id' + + wizard_id = fields.Many2one('om.quick.add.paste', required=True, ondelete='cascade') + sequence = fields.Integer() + row = fields.Char(string="Pasted", readonly=True) + product_id = fields.Many2one('product.product', string="Product") + candidate_ids = fields.Many2many('product.product', 'om_quick_add_paste_line_candidate_rel', + 'line_id', 'product_id', string="Possible products") + quantity = fields.Float(digits='Product Unit', default=1.0) + price_unit = fields.Float(string="Price", digits="Product Price", + help="The price pasted; when none, the price of the document applies.") + has_price = fields.Boolean(string="Pasted price") + state = fields.Selection([('found', "Found"), ('choose', "Choose"), ('missing', "Not found")], + compute='_compute_state') + + @api.depends('product_id', 'candidate_ids') + def _compute_state(self): + for line in self: + line.state = 'found' if line.product_id else 'choose' if line.candidate_ids else 'missing' + + @api.onchange('price_unit') + def _onchange_price_unit(self): + self.has_price = True diff --git a/om_quick_add/wizard/quick_add_paste_views.xml b/om_quick_add/wizard/quick_add_paste_views.xml new file mode 100644 index 00000000..dc9f0c35 --- /dev/null +++ b/om_quick_add/wizard/quick_add_paste_views.xml @@ -0,0 +1,60 @@ + + + + + om.quick.add.paste.form + om.quick.add.paste + +
+ + +
+

+ One product per row: its barcode, reference or name, then the quantity and, if you want, the price. + Copy the rows from Excel, an email or a message, for example: +

+
FURN_8220    5
+Large Desk   2    450.00
+3 x Office Chair
+ +
+
+

+ found + , + to check: + choose the product of the rows in orange or red, or leave them empty to skip them. + +

+ + + + + + + + + + + + +
+
+
+ +
+
+ +
diff --git a/om_quick_add/wizard/quick_add_wizard.py b/om_quick_add/wizard/quick_add_wizard.py new file mode 100644 index 00000000..5ba31618 --- /dev/null +++ b/om_quick_add/wizard/quick_add_wizard.py @@ -0,0 +1,62 @@ +from odoo import api, fields, models + +from ..models.quick_add_mixin import clean_context + + +class OmQuickAddWizard(models.AbstractModel): + """What the Quick Add dialogs share: the document they add to.""" + _name = 'om.quick.add.wizard' + _description = 'Quick Add Dialog' + + res_model = fields.Char(required=True, readonly=True) + res_id = fields.Many2oneReference(model_field='res_model', required=True, readonly=True) + has_prices = fields.Boolean(compute='_compute_has_prices') + document_name = fields.Char(compute='_compute_document_name') + + @api.depends('res_model') + def _compute_has_prices(self): + for wizard in self: + wizard.has_prices = bool(wizard.res_model) and self.env[wizard.res_model]._om_qa_has_prices + + @api.depends('res_model', 'res_id') + def _compute_document_name(self): + for wizard in self: + wizard.document_name = wizard._om_qa_document().display_name if wizard.res_model else False + + def _om_qa_document(self): + """The document, without the context the client carries over from the list of lines of the form.""" + self.ensure_one() + return self.env[self.res_model].with_context(clean_context(self.env.context)).browse(self.res_id) + + def _om_qa_load(self): + """Fill the dialog when it opens.""" + + def _om_qa_action(self, title=None): + self.ensure_one() + return { + 'type': 'ir.actions.act_window', + 'name': title or self.env._("Quick Add"), + 'res_model': self._name, + 'res_id': self.id, + 'view_mode': 'form', + 'target': 'new', + 'context': clean_context(self.env.context), + } + + def _om_qa_add_and_close(self, items): + added, raised = self._om_qa_document()._om_qa_add(items) + parts = [] + if added: + parts.append(self.env._("%s product(s) added", added)) + if raised: + parts.append(self.env._("%s quantity(ies) raised", raised)) + message = ", ".join(parts) + "." if parts else self.env._("Nothing to add.") + return { + 'type': 'ir.actions.client', + 'tag': 'display_notification', + 'params': { + 'message': message, + 'type': 'success', + 'next': {'type': 'ir.actions.act_window_close'}, + }, + } diff --git a/om_quick_add_account/README.rst b/om_quick_add_account/README.rst new file mode 100644 index 00000000..f37b401d --- /dev/null +++ b/om_quick_add_account/README.rst @@ -0,0 +1,5 @@ +============================== +Quick Add Products - Invoicing +============================== + +Paste lines, scan to add, the history and Copy lines on the draft customer invoices, vendor bills, credit notes and receipts. Bought before or Supplied before lists the products of the posted invoices or bills of the partner; on bills, the codes of the vendor are recognized too. Installed by itself with Quick Add Products and Invoicing. diff --git a/om_quick_add_account/__init__.py b/om_quick_add_account/__init__.py new file mode 100644 index 00000000..0650744f --- /dev/null +++ b/om_quick_add_account/__init__.py @@ -0,0 +1 @@ +from . import models diff --git a/om_quick_add_account/__manifest__.py b/om_quick_add_account/__manifest__.py new file mode 100644 index 00000000..8094a60a --- /dev/null +++ b/om_quick_add_account/__manifest__.py @@ -0,0 +1,16 @@ +{ + 'name': 'Quick Add Products - Invoicing', + 'version': '20.0.1.0.0', + 'category': 'Accounting/Accounting', + 'summary': 'Paste lines, scan barcodes, re-order from the history and copy lines on invoices and bills', + 'author': 'Odoo Mates', + 'maintainer': 'Odoo Mates', + 'support': 'odoomates@gmail.com', + 'license': 'LGPL-3', + 'depends': ['om_quick_add', 'account'], + 'data': [ + 'views/account_move_views.xml', + ], + 'installable': True, + 'auto_install': True, +} diff --git a/om_quick_add_account/models/__init__.py b/om_quick_add_account/models/__init__.py new file mode 100644 index 00000000..9c0a4213 --- /dev/null +++ b/om_quick_add_account/models/__init__.py @@ -0,0 +1 @@ +from . import account_move diff --git a/om_quick_add_account/models/account_move.py b/om_quick_add_account/models/account_move.py new file mode 100644 index 00000000..de1cf497 --- /dev/null +++ b/om_quick_add_account/models/account_move.py @@ -0,0 +1,93 @@ +from odoo import api, models +from odoo.fields import Domain +from odoo.tools.sql import escape_like_value + +from odoo.addons.om_quick_add.models.quick_add_mixin import HISTORY_LINES + + +class AccountMove(models.Model): + _name = 'account.move' + _inherit = ['account.move', 'om.quick.add.mixin'] + + _om_qa_line_field = 'invoice_line_ids' + _om_qa_quantity_field = 'quantity' + + @api.model + def _om_qa_copy_label(self): + return self.env._("Invoice or Bill") + + def _om_qa_editable(self): + return self.state == 'draft' and self.is_invoice(include_receipts=True) + + def _om_qa_partner(self): + return self.commercial_partner_id + + def _om_qa_product_domain(self): + domain = super()._om_qa_product_domain() + if self.is_sale_document(include_receipts=True): + return domain & Domain('sale_ok', '=', True) + if self.is_purchase_document(include_receipts=True): + return domain & Domain('purchase_ok', '=', True) + return domain + + def _om_qa_code_domain(self, code): + partner = self._om_qa_partner() + if not partner or not self.is_purchase_document(include_receipts=True): + return None + return Domain('product_tmpl_id.seller_ids', 'any', [ + ('partner_id', 'child_of', partner.id), ('product_code', '=ilike', escape_like_value(code))]) + + def _om_qa_bar_price(self, product): + if self.is_purchase_document(include_receipts=True): + seller = product._select_seller(partner_id=self.partner_id, quantity=1.0, uom_id=product.uom_id) + return seller.price if seller else product.standard_price + return product.lst_price + + def _om_qa_lines(self): + return self.invoice_line_ids.filtered(lambda l: l.display_type == 'product' and l.product_id) + + def _om_qa_line_data(self, line): + move = line.move_id + return { + 'product': line.product_id, + 'quantity': line.quantity, + 'uom': line.product_uom_id, + 'price_unit': line.price_unit, + 'discount': line.discount, + 'date': move.invoice_date or move.date, + 'document': move, + } + + def _om_qa_new_line_vals(self, product, quantity, uom, price_unit, discount): + vals = {'product_id': product.id, 'quantity': quantity} + if uom: + vals['product_uom_id'] = uom.id + if price_unit is not None: + vals['price_unit'] = price_unit + if discount is not None: + vals['discount'] = discount + return vals + + def _om_qa_history_lines(self): + if self.is_sale_document(include_receipts=True): + move_types = ['out_invoice', 'out_receipt'] + elif self.is_purchase_document(include_receipts=True): + move_types = ['in_invoice', 'in_receipt'] + else: + return self.env['account.move.line'] + return self.env['account.move.line'].search([ + ('move_id.commercial_partner_id', '=', self._om_qa_partner().id), + ('parent_state', '=', 'posted'), + ('move_id.move_type', 'in', move_types), + ('move_id', '!=', self.id or False), + ('company_id', '=', self.company_id.id), + ('display_type', '=', 'product'), + ('product_id', '!=', False), + ], order='id desc', limit=HISTORY_LINES) + + +class AccountMoveLine(models.Model): + _name = 'account.move.line' + _inherit = ['account.move.line', 'om.quick.add.line.mixin'] + + _om_qa_document_model = 'account.move' diff --git a/om_quick_add_account/views/account_move_views.xml b/om_quick_add_account/views/account_move_views.xml new file mode 100644 index 00000000..6d02c321 --- /dev/null +++ b/om_quick_add_account/views/account_move_views.xml @@ -0,0 +1,29 @@ + + + + + account.move.form.om.quick.add + account.move + + + + + + + + + + +