191 lines
8.5 KiB
Python
191 lines
8.5 KiB
Python
# Part of Beyond. Collina Systems proprietary module.
|
|
import logging
|
|
|
|
from odoo import _, api, fields, models
|
|
|
|
from odoo.addons.beyond_base.tools.arranque import ejecutar_en_arranque
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
# Estados de una orden de POS que cuentan como consumo real
|
|
POS_ORDER_STATES = ('paid', 'done', 'invoiced')
|
|
|
|
|
|
# FUENTE ÚNICA de "qué es un cliente" (C-018 y mostrador POS): empleados,
|
|
# usuarios del sistema y compañías NO son clientes. La vista Clientes del
|
|
# backend y TODAS las rutas de carga/búsqueda del POS consumen esta
|
|
# definición; un test verifica que el XML de la acción no se desincronice.
|
|
DOMINIO_CLIENTES = [
|
|
('user_ids', '=', False),
|
|
('employee_ids', '=', False),
|
|
('is_company', '=', False),
|
|
]
|
|
|
|
|
|
class ResPartner(models.Model):
|
|
_inherit = 'res.partner'
|
|
|
|
@api.model
|
|
def _beyond_dominio_clientes(self):
|
|
return list(DOMINIO_CLIENTES)
|
|
|
|
# El mismo criterio, pero como DATO, para que pueda viajar a donde el
|
|
# dominio no llega. El POS arma su selector con lo que tiene en memoria,
|
|
# y a memoria llegan partners por referencia —el cliente de una venta
|
|
# pasada, por ejemplo—, sin pasar por ningún dominio. Sin este campo, esa
|
|
# ruta no tiene forma de aplicar el criterio.
|
|
beyond_es_cliente = fields.Boolean(
|
|
string='Es cliente', compute='_compute_beyond_es_cliente', store=True,
|
|
help='Calculado con la MISMA definición que usa la vista Clientes y '
|
|
'la carga del POS.')
|
|
|
|
@api.depends('user_ids', 'employee_ids', 'is_company')
|
|
def _compute_beyond_es_cliente(self):
|
|
"""Se evalúa con el dominio mismo, no con una copia de sus reglas:
|
|
así es imposible que el campo y la definición diverjan."""
|
|
clientes = set(self.sudo().search(
|
|
self._beyond_dominio_clientes() + [('id', 'in', self.ids)]).ids)
|
|
for partner in self:
|
|
partner.beyond_es_cliente = partner.id in clientes
|
|
|
|
@api.model
|
|
def _beyond_demo_limpiar_contactos_hijos(self):
|
|
"""DEMO ONLY: archives Odoo's sample contacts that hang off a company.
|
|
|
|
Odoo's own demo data ships two dozen people attached to companies
|
|
(Floyd Steward at Acme Corporation and friends). They match the
|
|
Clientes domain — they are people, with no user and no employee — so
|
|
they crowd the screen with 33 records, show a breadcrumb reading
|
|
"Acme Corporation, Floyd Steward" and pull their parent's address
|
|
into the form. None of that would reach production, where a customer
|
|
is created from the POS with no parent, but it makes the screen
|
|
impossible to review.
|
|
|
|
THE DOMAIN IS DELIBERATELY NOT TOUCHED. Excluding contacts with a
|
|
parent would have been the other way out, and it is a change to the
|
|
SALE path, not to a screen: _beyond_dominio_clientes also feeds the
|
|
POS in its two routes — the load domain and the stored
|
|
beyond_es_cliente the selector reads (beyond_pos_theme). A customer
|
|
who happens to be linked to a company would quietly disappear from
|
|
the cashier's selector, and the migrated customers of D4 are exactly
|
|
the ones that could arrive with such a link. A demo nuisance does not
|
|
justify that risk.
|
|
|
|
Archived and not deleted: the records stay for whatever else in the
|
|
demo refers to them. Idempotent, and demo-only — this never runs in
|
|
production, where demo data is not installed.
|
|
"""
|
|
return ejecutar_en_arranque(
|
|
self.env, 'Limpieza de contactos demo de Odoo',
|
|
self._beyond_demo_archivar_hijos)
|
|
|
|
@api.model
|
|
def _beyond_demo_archivar_hijos(self):
|
|
ruido = self.sudo().search(
|
|
self._beyond_dominio_clientes() + [('parent_id', '!=', False)])
|
|
# Los de Beyond no tienen padre, así que no pueden caer aquí; el
|
|
# filtro extra es por si alguien agrega uno colgado de una compañía.
|
|
nuestros = self.env['ir.model.data'].sudo().search([
|
|
('model', '=', 'res.partner'), ('module', '=', 'beyond_customer'),
|
|
]).mapped('res_id')
|
|
ruido = ruido.filtered(lambda p: p.id not in nuestros)
|
|
if ruido:
|
|
ruido.write({'active': False})
|
|
_logger.warning(
|
|
'Beyond · datos demo: %s contactos de ejemplo de Odoo archivados '
|
|
'para que no se mezclen con los clientes de Beyond.', len(ruido))
|
|
return len(ruido)
|
|
|
|
beyond_visit_count = fields.Integer(
|
|
string='Visitas', compute='_compute_beyond_metrics')
|
|
beyond_last_visit = fields.Datetime(
|
|
string='Última visita', compute='_compute_beyond_metrics')
|
|
beyond_total_spent = fields.Monetary(
|
|
string='Gasto acumulado', compute='_compute_beyond_metrics',
|
|
currency_field='currency_id')
|
|
beyond_avg_ticket = fields.Monetary(
|
|
string='Ticket promedio', compute='_compute_beyond_metrics',
|
|
currency_field='currency_id')
|
|
beyond_usual_branch_id = fields.Many2one(
|
|
'beyond.branch', string='Sucursal habitual',
|
|
compute='_compute_beyond_metrics')
|
|
beyond_anonymized = fields.Boolean(string='Anonimizado', readonly=True, copy=False)
|
|
|
|
# ── Las descargas de la tabla ───────────────────────────────────────
|
|
# Viven aquí porque el botón está en la lista de res.partner y Odoo
|
|
# llama el método sobre el modelo de la vista. La lógica es de
|
|
# `beyond.cliente`, que es quien sabe de columnas y de archivos.
|
|
|
|
@api.model
|
|
def beyond_descargar_clientes_excel(self):
|
|
return self.env['beyond.cliente'].beyond_ir_a_descarga('xlsx')
|
|
|
|
@api.model
|
|
def beyond_descargar_clientes_pdf(self):
|
|
return self.env['beyond.cliente'].beyond_ir_a_descarga('pdf')
|
|
|
|
def _compute_beyond_metrics(self):
|
|
"""Historial de consumo GLOBAL del cliente (Ficha 360, BRIEF §5.1).
|
|
|
|
Se consulta con sudo a propósito: el valor de la ficha es ver el
|
|
historial completo del cliente sin importar en qué sucursal esté el
|
|
mostrador (ADR-002). Las órdenes crudas siguen aisladas por las
|
|
reglas de beyond_branch; aquí solo se agregan totales.
|
|
"""
|
|
Order = self.env['pos.order'].sudo()
|
|
grouped = Order._read_group(
|
|
domain=[('partner_id', 'in', self.ids), ('state', 'in', POS_ORDER_STATES)],
|
|
groupby=['partner_id'],
|
|
aggregates=['id:count', 'date_order:max', 'amount_total:sum'],
|
|
)
|
|
stats = {partner.id: (count, last, total) for partner, count, last, total in grouped}
|
|
by_branch = Order._read_group(
|
|
domain=[('partner_id', 'in', self.ids), ('state', 'in', POS_ORDER_STATES),
|
|
('branch_id', '!=', False)],
|
|
groupby=['partner_id', 'branch_id'],
|
|
aggregates=['id:count'],
|
|
)
|
|
usual = {}
|
|
for partner, branch, count in by_branch:
|
|
best = usual.get(partner.id)
|
|
if not best or count > best[1]:
|
|
usual[partner.id] = (branch, count)
|
|
for partner in self:
|
|
count, last, total = stats.get(partner.id, (0, False, 0.0))
|
|
partner.beyond_visit_count = count
|
|
partner.beyond_last_visit = last
|
|
partner.beyond_total_spent = total or 0.0
|
|
partner.beyond_avg_ticket = (total / count) if count else 0.0
|
|
partner.beyond_usual_branch_id = usual.get(partner.id, (False,))[0]
|
|
|
|
def action_view_beyond_orders(self):
|
|
self.ensure_one()
|
|
return {
|
|
'type': 'ir.actions.act_window',
|
|
'name': _('Consumo de %s', self.display_name),
|
|
'res_model': 'pos.order',
|
|
'view_mode': 'list,form',
|
|
'domain': [('partner_id', '=', self.id)],
|
|
'context': {'create': False},
|
|
}
|
|
|
|
def action_beyond_anonymize(self):
|
|
"""Elimina los datos personales del cliente a solicitud del titular
|
|
(LFPDPPP). Conserva el registro y sus órdenes para no romper la
|
|
integridad histórica, pero sin datos identificables."""
|
|
for partner in self:
|
|
partner.write({
|
|
'name': _('Cliente anonimizado #%s', partner.id),
|
|
'image_1920': False,
|
|
'email': False,
|
|
'phone': False,
|
|
'street': False,
|
|
'street2': False,
|
|
'city': False,
|
|
'zip': False,
|
|
'vat': False,
|
|
'comment': False,
|
|
'active': False,
|
|
'beyond_anonymized': True,
|
|
})
|