|
| 1 | +from odoo import models, fields, api |
| 2 | +from datetime import date |
| 3 | + |
| 4 | + |
| 5 | +class ProductTemplate(models.Model): |
| 6 | + _inherit = "product.template" |
| 7 | + |
| 8 | + @api.model |
| 9 | + def name_search(self, name, args=None, operator="ilike", limit=100): |
| 10 | + args = list(args) if args else [] |
| 11 | + partner_id = self.env.context.get("partner_id") |
| 12 | + results = [] |
| 13 | + matched_ids = [] |
| 14 | + |
| 15 | + lines = self.env["account.move.line"].search([ |
| 16 | + ("move_id.move_type", "=", "out_invoice"), |
| 17 | + ("move_id.partner_id", "=", partner_id), |
| 18 | + ("move_id.state", "=", "posted"), |
| 19 | + ("product_id.product_tmpl_id", "!=", False), |
| 20 | + ]) |
| 21 | + |
| 22 | + lines = sorted( |
| 23 | + lines, key=lambda l: l.move_id.invoice_date or fields.Date.today(), |
| 24 | + reverse=True) |
| 25 | + |
| 26 | + tmpl_map = {} |
| 27 | + for line in lines: |
| 28 | + tmpl = line.product_id.product_tmpl_id |
| 29 | + if tmpl.id not in tmpl_map: |
| 30 | + tmpl_map[tmpl.id] = {"tmpl": tmpl, "date": line.move_id.invoice_date} |
| 31 | + if len(tmpl_map) >= limit: |
| 32 | + break |
| 33 | + |
| 34 | + name_lower = name.lower() if name else "" |
| 35 | + today = date.today() |
| 36 | + |
| 37 | + for info in tmpl_map.values(): |
| 38 | + tmpl = info["tmpl"] |
| 39 | + invoice_date = info["date"] |
| 40 | + if not name or (operator == "ilike" and name_lower in tmpl.name.lower()): |
| 41 | + days = (today - invoice_date).days if invoice_date else "?" |
| 42 | + display = f"{tmpl.display_name} (Last ordered {days} days ago)" |
| 43 | + results.append((tmpl.id, display)) |
| 44 | + matched_ids.append(tmpl.id) |
| 45 | + if len(results) >= limit: |
| 46 | + break |
| 47 | + |
| 48 | + remaining = limit - len(results) |
| 49 | + if remaining > 0: |
| 50 | + domain = args[:] |
| 51 | + if name: |
| 52 | + domain.append(("name", operator, name)) |
| 53 | + if matched_ids: |
| 54 | + domain.append(("id", "not in", matched_ids)) |
| 55 | + others = super().name_search(name, args=domain, operator=operator, limit=remaining) |
| 56 | + results.extend(others) |
| 57 | + |
| 58 | + return results |
0 commit comments