diff --git a/addons/beyond_base/__manifest__.py b/addons/beyond_base/__manifest__.py index 7de650c..6b973c9 100644 --- a/addons/beyond_base/__manifest__.py +++ b/addons/beyond_base/__manifest__.py @@ -53,6 +53,16 @@ enlace de "¿Olvidaste tu contraseña?" es el suyo, con su condición real. # estilo. 'beyond_base/static/src/webclient/beyond_panel_navbar.js', 'beyond_base/static/src/webclient/beyond_panel_navbar.xml', + # Widgets de campo reutilizables. Su SCSS vive en beyond_branch + # con el resto de los tokens del panel, por el mismo motivo que + # el de la barra. + 'beyond_base/static/src/fields/beyond_image_camera.js', + 'beyond_base/static/src/fields/beyond_image_camera.xml', + 'beyond_base/static/src/fields/beyond_avatar_initials.js', + 'beyond_base/static/src/fields/beyond_avatar_initials.xml', + ], + 'web.assets_unit_tests': [ + 'beyond_base/static/tests/**/*.test.js', ], # The login screen renders before there is a session: it gets the # frontend bundle and nothing else, so the face travels with it. diff --git a/addons/beyond_base/static/src/fields/beyond_avatar_initials.js b/addons/beyond_base/static/src/fields/beyond_avatar_initials.js new file mode 100644 index 0000000..8864a02 --- /dev/null +++ b/addons/beyond_base/static/src/fields/beyond_avatar_initials.js @@ -0,0 +1,75 @@ +/** Part of Beyond. Collina Systems proprietary module. */ +import { Component } from "@odoo/owl"; +import { registry } from "@web/core/registry"; +import { imageUrl } from "@web/core/utils/urls"; +import { standardFieldProps } from "@web/views/fields/standard_field_props"; +import { _t } from "@web/core/l10n/translation"; + +/** + * Photo, or initials on peach when there is none (Panel General design). + * + * WHY NOT avatar_128. res.partner inherits avatar.mixin, which already draws + * an SVG when the record has no photo, so this looked like reinventing the + * core. It is not, for two reasons that CSS cannot reach: + * + * · The mixin writes ONE letter (`name[0]`), and the design asks for two. + * · Its background is an HSL colour hashed from name + create_date, and the + * text is hardcoded white — inside a base64 SVG served as an . The + * colour is baked into the image, so no stylesheet can turn it into the + * panel's peach. + * + * The other way out would be overriding _avatar_generate_svg on res.partner, + * which is tempting and shorter. It was not taken because avatar_128 is used + * far beyond this screen — the POS among them — and repainting every partner + * avatar in the system is a decision for whoever designs those screens, not a + * side effect of the customer list. + */ +export class BeyondAvatarInitials extends Component { + static template = "beyond_base.AvatarInitials"; + static props = { ...standardFieldProps }; + + get valor() { + return this.props.record.data[this.props.name]; + } + + get nombre() { + const datos = this.props.record.data; + return (datos.name || datos.display_name || "").trim(); + } + + /** + * First letter of the first word plus first letter of the last one: + * "Alejandro Mcdonald" → "AM". A single word gives a single letter rather + * than two from the same word, which reads like a typo. + */ + get iniciales() { + const palabras = this.nombre.split(/\s+/).filter(Boolean); + if (!palabras.length) { + return "?"; + } + const primera = palabras[0][0]; + const ultima = palabras.length > 1 ? palabras[palabras.length - 1][0] : ""; + return (primera + ultima).toUpperCase(); + } + + get url() { + return imageUrl(this.props.record.resModel, this.props.record.resId, this.props.name, { + unique: this.props.record.data.write_date, + }); + } +} + +export const beyondAvatarInitials = { + component: BeyondAvatarInitials, + displayName: _t("Foto o iniciales"), + supportedTypes: ["binary"], + // name feeds the initials; write_date busts the image cache after a new + // photo. Declaring them makes the views load them without each view + // having to remember. + fieldDependencies: [ + { name: "name", type: "char" }, + { name: "write_date", type: "datetime" }, + ], +}; + +registry.category("fields").add("beyond_avatar_initials", beyondAvatarInitials); diff --git a/addons/beyond_base/static/src/fields/beyond_avatar_initials.xml b/addons/beyond_base/static/src/fields/beyond_avatar_initials.xml new file mode 100644 index 0000000..a6afb58 --- /dev/null +++ b/addons/beyond_base/static/src/fields/beyond_avatar_initials.xml @@ -0,0 +1,7 @@ + + + + +
+ + diff --git a/addons/beyond_base/static/src/fields/beyond_image_camera.js b/addons/beyond_base/static/src/fields/beyond_image_camera.js new file mode 100644 index 0000000..c306ab1 --- /dev/null +++ b/addons/beyond_base/static/src/fields/beyond_image_camera.js @@ -0,0 +1,228 @@ +/** Part of Beyond. Collina Systems proprietary module. */ +import { Component, onWillUnmount, useRef, useState } from "@odoo/owl"; +import { Dialog } from "@web/core/dialog/dialog"; +import { registry } from "@web/core/registry"; +import { useService, useExternalListener } from "@web/core/utils/hooks"; +import { browser } from "@web/core/browser/browser"; +import { _t } from "@web/core/l10n/translation"; +import { ImageField, imageField } from "@web/views/fields/image/image_field"; +import { FileUploader } from "@web/views/fields/file_handler"; + +/** + * Photo field with a camera of its own (BRIEF §5.1). + * + * Extends the native ImageField instead of replacing it: uploading, clearing, + * the URL cache key and the record update all keep working the way every + * other image field in Odoo works. What this adds is the menu from the design + * and a capture dialog. + * + * SECURE CONTEXT — the one thing to know before touching this file. + * navigator.mediaDevices only exists over https or on localhost. Production + * has no TLS yet (docs/despliegue.md), so ON THE BRANCH TABLETS THE CAMERA + * DIALOG CANNOT OPEN AT ALL. That is not a bug to fix here; it is an + * infrastructure dependency. What this widget does is refuse to show a button + * that would throw: "Tomar fotografía" is rendered only when the API is + * actually reachable, and "Subir archivo" carries capture="environment", which + * makes Android open its own camera app without needing a secure context. The + * customer still gets photographed; it just costs one more tap. + */ + +const LADO_MAXIMO = 1280; +const CALIDAD_JPEG = 0.9; + +/** The native uploader with one more attribute: see the note above. */ +export class BeyondFileUploader extends FileUploader { + static template = "beyond_base.FileUploader"; + static props = { + ...FileUploader.props, + capture: { type: String, optional: true }, + }; +} + +export class BeyondCameraDialog extends Component { + static template = "beyond_base.CameraDialog"; + static components = { Dialog }; + static props = { + close: Function, + onCapture: Function, + }; + + setup() { + this.notification = useService("notification"); + this.video = useRef("video"); + this.state = useState({ + listo: false, + error: false, + variasCamaras: false, + // "environment" = trasera. El caso de uso es el mostrador + // fotografiando al cliente, no una selfie. + camara: "environment", + }); + this.stream = null; + this.destruido = false; + + // Releasing the stream is not optional: a camera left running keeps + // the tablet's indicator light on and looks like the shop is filming. + // onWillUnmount covers the three ways out of this dialog — the X, + // Escape and navigating away inside the client — because all three + // destroy the component. pagehide covers leaving the page entirely. + onWillUnmount(() => { + this.destruido = true; + this.detener(); + }); + useExternalListener(window, "pagehide", () => this.detener()); + + this.arrancar(); + } + + async arrancar() { + this.detener(); + try { + this.stream = await browser.navigator.mediaDevices.getUserMedia({ + video: { facingMode: this.state.camara }, + audio: false, + }); + } catch { + this.state.error = true; + return; + } + // The component may have been destroyed while getUserMedia was + // resolving: the user can close the dialog faster than a camera turns + // on, and the stream would stay live with nobody left to stop it. + if (this.destruido) { + this.detener(); + return; + } + if (this.video.el) { + this.video.el.srcObject = this.stream; + } + this.state.listo = true; + try { + const dispositivos = await browser.navigator.mediaDevices.enumerateDevices(); + this.state.variasCamaras = + dispositivos.filter((d) => d.kind === "videoinput").length > 1; + } catch { + this.state.variasCamaras = false; + } + } + + detener() { + this.stream?.getTracks().forEach((pista) => pista.stop()); + this.stream = null; + if (this.video.el) { + this.video.el.srcObject = null; + } + } + + cambiarCamara() { + this.state.camara = this.state.camara === "environment" ? "user" : "environment"; + this.state.listo = false; + this.arrancar(); + } + + capturar() { + const video = this.video.el; + if (!video || !this.state.listo) { + return; + } + const ancho = video.videoWidth; + const alto = video.videoHeight; + if (!ancho || !alto) { + return; + } + // Scale down to LADO_MAXIMO on the longest side. A tablet camera hands + // back several megapixels and the field stores base64 in the record: + // full size would make every read of this customer drag the photo. + const escala = Math.min(1, LADO_MAXIMO / Math.max(ancho, alto)); + const lienzo = document.createElement("canvas"); + lienzo.width = Math.round(ancho * escala); + lienzo.height = Math.round(alto * escala); + lienzo.getContext("2d").drawImage(video, 0, 0, lienzo.width, lienzo.height); + const datos = lienzo.toDataURL("image/jpeg", CALIDAD_JPEG).split(",")[1]; + this.detener(); + this.props.onCapture(datos); + this.props.close(); + } +} + +export class BeyondImageCamera extends ImageField { + static template = "beyond_base.ImageCamera"; + static components = { ...ImageField.components, FileUploader: BeyondFileUploader }; + + setup() { + super.setup(); + this.dialog = useService("dialog"); + this.notification = useService("notification"); + this.menu = useState({ abierto: false, fijado: false }); + } + + /** + * True only where the browser can actually open a camera. + * + * Checking mediaDevices is enough and is the whole test: outside a secure + * context (https or localhost) the browser does not merely refuse + * getUserMedia — it does not define navigator.mediaDevices at all. Going + * through `browser` rather than the global is Odoo's own indirection, and + * it is what lets a test take the camera away. + */ + get camaraDisponible() { + return !!browser.navigator.mediaDevices?.getUserMedia; + } + + get tieneImagen() { + return !!this.props.record.data[this.props.name] && this.state.isValid; + } + + mostrarMenu() { + this.menu.abierto = true; + } + + ocultarMenu() { + if (!this.menu.fijado) { + this.menu.abierto = false; + } + } + + /** Touch has no hover: a tap pins the menu open, another closes it. */ + alternarMenu() { + this.menu.fijado = !this.menu.fijado; + this.menu.abierto = this.menu.fijado || this.menu.abierto; + } + + cerrarMenu() { + this.menu.fijado = false; + this.menu.abierto = false; + } + + abrirCamara() { + this.cerrarMenu(); + if (!this.camaraDisponible) { + // Should be unreachable: the option is not rendered without a + // camera. Kept as a spoken failure rather than a silent one. + this.notification.add( + _t("Este navegador no permite usar la cámara aquí. Usa «Subir archivo»."), + { type: "warning" } + ); + return; + } + this.dialog.add(BeyondCameraDialog, { + onCapture: (datos) => { + this.state.isValid = true; + this.props.record.update({ [this.props.name]: datos }); + }, + }); + } + + eliminar() { + this.cerrarMenu(); + this.onFileRemove(); + } +} + +export const beyondImageCamera = { + ...imageField, + component: BeyondImageCamera, + displayName: _t("Foto con cámara"), +}; + +registry.category("fields").add("beyond_image_camera", beyondImageCamera); diff --git a/addons/beyond_base/static/src/fields/beyond_image_camera.xml b/addons/beyond_base/static/src/fields/beyond_image_camera.xml new file mode 100644 index 0000000..b796fcf --- /dev/null +++ b/addons/beyond_base/static/src/fields/beyond_image_camera.xml @@ -0,0 +1,97 @@ + + + + + + + props.capture or false + + + + +
+ + + +
+ +
+ +
+ + + + + + + + + + +
+
+
+
+ + + +
+ +

+ No se pudo abrir la cámara. Puede que el navegador no + tenga permiso, o que otra aplicación la esté usando. + Cierra este cuadro y usa «Subir archivo». +

+
+ + +
+ + + + + +
+
+ +
diff --git a/addons/beyond_base/static/tests/beyond_image_camera.test.js b/addons/beyond_base/static/tests/beyond_image_camera.test.js new file mode 100644 index 0000000..6049081 --- /dev/null +++ b/addons/beyond_base/static/tests/beyond_image_camera.test.js @@ -0,0 +1,183 @@ +/** Part of Beyond. Collina Systems proprietary module. */ +import { expect, test, describe } from "@odoo/hoot"; +import { click, queryAll, queryFirst } from "@odoo/hoot-dom"; +import { animationFrame } from "@odoo/hoot-mock"; +import { + defineModels, + fields, + models, + mountView, + patchWithCleanup, +} from "@web/../tests/web_test_helpers"; +import { browser } from "@web/core/browser/browser"; + +/** + * Unit tests for beyond_image_camera. + * + * The one that matters most is the secure-context one: production has no TLS + * yet, so navigator.mediaDevices does not exist on the branch tablets and the + * widget must not offer a button that would throw. That is the case a person + * cannot easily check by hand — dev runs on localhost, where the camera + * always works. + */ + +describe.current.tags("desktop"); + +class ResPartner extends models.Model { + _name = "res.partner"; + + name = fields.Char(); + image_1920 = fields.Binary(); + + _records = [{ id: 1, name: "Alejandro Mcdonald", image_1920: "FOTO==" }]; +} + +defineModels([ResPartner]); + +const VISTA = /* xml */ ` +
+ + `; + +/** Fakes a camera: one track whose stop() we can watch. */ +function camaraFalsa({ camaras = 1 } = {}) { + const pista = { stop: () => (pista.detenida = true), detenida: false, kind: "video" }; + const stream = { getTracks: () => [pista] }; + patchWithCleanup(browser, { + navigator: { + ...browser.navigator, + mediaDevices: { + getUserMedia: async () => stream, + enumerateDevices: async () => + Array.from({ length: camaras }, () => ({ kind: "videoinput" })), + }, + }, + }); + return pista; +} + +/** Takes the camera away, the way an http:// page does. */ +function sinCamara() { + patchWithCleanup(browser, { + navigator: { ...browser.navigator, mediaDevices: undefined }, + }); +} + +test("el menú de la foto se abre al pasar el mouse y se cierra al salir", async () => { + camaraFalsa(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + expect(".beyond_foto_menu").toHaveCount(0); + + await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseenter")); + await animationFrame(); + expect(".beyond_foto_menu").toHaveCount(1); + + await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseleave")); + await animationFrame(); + expect(".beyond_foto_menu").toHaveCount(0); +}); + +test("un toque fija el menú y otro lo suelta (en táctil no hay hover)", async () => { + camaraFalsa(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + expect(".beyond_foto_menu").toHaveCount(1); + + // Fijado: salir con el mouse ya no lo cierra. + await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseleave")); + await animationFrame(); + expect(".beyond_foto_menu").toHaveCount(1); + + await click(".beyond_foto"); + await animationFrame(); + expect(".beyond_foto_menu").toHaveCount(0); +}); + +test("sin cámara no se ofrece «Tomar fotografía», y sí «Subir archivo»", async () => { + // Es el caso de las tablets de sucursal mientras producción no tenga TLS: + // fuera de contexto seguro el navegador ni siquiera define mediaDevices. + sinCamara(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + + const opciones = queryAll(".beyond_foto_opcion").map((b) => b.textContent.trim()); + expect(opciones).not.toInclude("Tomar fotografía"); + expect(opciones).toInclude("Subir archivo"); +}); + +test("con cámara sí se ofrece «Tomar fotografía»", async () => { + camaraFalsa(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + + const opciones = queryAll(".beyond_foto_opcion").map((b) => b.textContent.trim()); + expect(opciones).toInclude("Tomar fotografía"); +}); + +test("«Subir archivo» pide la cámara trasera, no la frontal", async () => { + // Coherencia con el diálogo propio: el caso de uso es el mostrador + // fotografiando al cliente, no una selfie. + sinCamara(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + + expect("input[type=file]").toHaveAttribute("capture", "environment"); +}); + +test("«Eliminar» limpia el campo", async () => { + camaraFalsa(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + await click(".beyond_foto_borrar"); + await animationFrame(); + + // Sin imagen no hay nada que borrar: la opción desaparece. + expect(".beyond_foto_borrar").toHaveCount(0); +}); + +test("cerrar el diálogo apaga la cámara", async () => { + // Una cámara que se queda encendida deja el testigo del aparato prendido + // y parece que el local está grabando. + const pista = camaraFalsa(); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + await click(".beyond_foto_opcion"); // «Tomar fotografía» + await animationFrame(); + await animationFrame(); + expect(".beyond_camara_video").toHaveCount(1); + expect(pista.detenida).toBe(false); + + await click(".beyond_camara_dialogo .btn-secondary:last-child"); // Cancelar + await animationFrame(); + + expect(pista.detenida).toBe(true); +}); + +test("con una sola cámara no se ofrece cambiarla", async () => { + camaraFalsa({ camaras: 1 }); + await mountView({ type: "form", resModel: "res.partner", resId: 1, arch: VISTA }); + + await click(".beyond_foto"); + await animationFrame(); + await click(".beyond_foto_opcion"); + await animationFrame(); + await animationFrame(); + + const botones = queryAll(".beyond_camara_dialogo .modal-footer .btn").map((b) => + b.textContent.trim() + ); + expect(botones).not.toInclude("Cambiar de cámara"); +}); diff --git a/addons/beyond_branch/__manifest__.py b/addons/beyond_branch/__manifest__.py index c9a5364..2745428 100644 --- a/addons/beyond_branch/__manifest__.py +++ b/addons/beyond_branch/__manifest__.py @@ -41,6 +41,7 @@ Fase 1 — Arquitectura base (BRIEF §5.3 y §4): 'beyond_branch/static/src/panel/beyond_panel_variables.scss', 'beyond_branch/static/src/panel/beyond_panel.scss', 'beyond_branch/static/src/panel/beyond_prefs.scss', + 'beyond_branch/static/src/panel/beyond_fields.scss', 'beyond_branch/static/src/matriz_precios/matriz_precios.js', 'beyond_branch/static/src/matriz_precios/matriz_precios.xml', 'beyond_branch/static/src/matriz_precios/matriz_precios.scss', diff --git a/addons/beyond_branch/static/src/panel/beyond_fields.scss b/addons/beyond_branch/static/src/panel/beyond_fields.scss new file mode 100644 index 0000000..fd61397 --- /dev/null +++ b/addons/beyond_branch/static/src/panel/beyond_fields.scss @@ -0,0 +1,143 @@ +// ============================================================================= +// Panel General · widgets propios (ADR-013) +// +// The widgets themselves live in beyond_base, because Mis preferencias and the +// customer form both use the camera one. Their LOOK lives here, with the rest +// of the panel's tokens, for the same reason the navbar's does: beyond_base +// cannot import variables from a module that depends on it. +// +// Today both widgets are only ever rendered inside the panel, so scoping them +// under body.beyond_panel costs nothing. If one of them is ever reused outside +// — the POS in Fase 2 is the obvious candidate — its styling moves out with +// it, and that is a good moment to reconsider whether the peach graduates to a +// token. +// ============================================================================= + +body.beyond_panel { + + // ── Foto con cámara ─────────────────────────────────────────────────── + .beyond_foto { + position: relative; + width: 100%; + aspect-ratio: 4 / 5; // el retrato del diseño, no un cuadrado + border-radius: 26px; + overflow: hidden; + background: $beyond-panel-durazno; + cursor: pointer; + + .beyond_foto_img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + } + + .beyond_foto_velo { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgba(35, 32, 29, 0.5); + } + } + + .beyond_foto_menu { + position: absolute; + top: 100%; + left: 0; + z-index: 30; + min-width: 208px; + margin-top: 8px; + padding: 6px; + background: #FFFFFF; + border: 1px solid $beyond-surface-active; + border-radius: 16px; + box-shadow: 0 16px 36px rgba(35, 32, 29, 0.16); + display: flex; + flex-direction: column; + gap: 2px; + cursor: default; + } + + .beyond_foto_opcion { + all: unset; + box-sizing: border-box; + cursor: pointer; + display: flex; + align-items: center; + gap: 10px; + width: 100%; + padding: 10px 12px; + border-radius: 11px; + font-size: 14px; + font-weight: 700; + color: $beyond-ink; + transition: background 140ms ease; + + svg { color: $beyond-ink-softer; flex: none; } + &:hover, &:focus-visible { background: $beyond-surface; } + + &.beyond_foto_borrar { + color: $beyond-panel-rojo; + svg { color: $beyond-panel-rojo; } + &:hover, &:focus-visible { background: $beyond-panel-rojo-suave; } + } + } + + // ── Foto o iniciales ────────────────────────────────────────────────── + // The size comes from wherever it is used (kanban card, list row), so + // that one widget serves the 92px card and the 38px row. + .beyond_avatar_img, + .beyond_avatar_iniciales { + width: 100%; + height: 100%; + border-radius: inherit; + display: block; + } + + .beyond_avatar_img { object-fit: cover; } + + .beyond_avatar_iniciales { + display: flex; + align-items: center; + justify-content: center; + background: $beyond-panel-durazno; + color: $beyond-panel-acento-pressed; + font-weight: 800; + letter-spacing: -0.01em; + // Scales with the box it is given: 92px card → 28px letters, + // 38px row → 13px, which is what the design draws. + font-size: 0.32em; + } +} + +// El diálogo de la cámara se portaliza a , fuera del alcance de la +// clase del panel, así que se apunta por su propia clase. +.beyond_camara_dialogo { + .beyond_camara { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + } + + .beyond_camara_video { + width: 100%; + max-height: 60vh; + border-radius: 18px; + background: #23201D; + // La vista previa se refleja como un espejo solo con la cámara + // frontal; con la trasera, que es la de este flujo, se ve tal cual. + object-fit: cover; + } + + .beyond_camara_espera, + .beyond_camara_error { + margin: 0; + font-size: 14px; + font-weight: 600; + color: #7A736A; + text-align: center; + } +} diff --git a/addons/beyond_customer/__manifest__.py b/addons/beyond_customer/__manifest__.py index b037f81..a7ffd6b 100644 --- a/addons/beyond_customer/__manifest__.py +++ b/addons/beyond_customer/__manifest__.py @@ -28,7 +28,14 @@ Fase 2 junto con beyond_pos_theme. 'data/menu_cleanup.xml', 'views/res_partner_views.xml', ], - 'demo': [], + 'assets': { + 'web.assets_backend': [ + 'beyond_customer/static/src/clientes.scss', + ], + }, + 'demo': [ + 'demo/demo_clientes.xml', + ], 'installable': True, 'application': False, } diff --git a/addons/beyond_customer/demo/demo_clientes.xml b/addons/beyond_customer/demo/demo_clientes.xml new file mode 100644 index 0000000..6f808cb --- /dev/null +++ b/addons/beyond_customer/demo/demo_clientes.xml @@ -0,0 +1,49 @@ + + + + + Alejandro Mcdonald + +52 222 873 3602 + Av. Juárez 1820, La Paz + Puebla + Prefiere cita temprano. Alérgico al amoniaco. + + + + + Marisol Ibáñez + +52 222 145 9080 + Calle 7 Sur 304 + Puebla + + + + Rodrigo Cantú + +52 55 4412 7788 + Adamanto 45 + Ciudad de México + Llega siempre con su hijo. + + + + Ximena + +52 222 900 1122 + San Andrés Cholula + + diff --git a/addons/beyond_customer/static/src/clientes.scss b/addons/beyond_customer/static/src/clientes.scss new file mode 100644 index 0000000..1897f09 --- /dev/null +++ b/addons/beyond_customer/static/src/clientes.scss @@ -0,0 +1,142 @@ +// ============================================================================= +// Panel General · Clientes (ADR-013, Fase 1) +// +// Sits on top of the panel's base skin (beyond_branch/static/src/panel), which +// already dressed lists, kanban cards, forms and buttons. Only what the +// Clientes design does differently lives here. +// +// Scoped under body.beyond_panel like everything else: Contactos nativo and +// the POS keep their own views and never see a rule from this file. +// ============================================================================= + +body.beyond_panel { + + // ── Tarjeta de cliente (kanban) ─────────────────────────────────────── + .o_beyond_clientes_kanban { + .beyond_cliente_tarjeta { + display: flex; + flex-direction: column; + gap: 14px; + } + + .beyond_cliente_cabeza { + display: flex; + align-items: center; + gap: 16px; + min-width: 0; + } + + // La foto manda el tamaño; el widget se adapta al hueco. + .beyond_cliente_foto { + flex: none; + width: 92px; + height: 92px; + border-radius: 26px; + overflow: hidden; + } + + .beyond_cliente_datos { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; + } + + .beyond_cliente_nombre { + font-size: 17px; + font-weight: 800; + letter-spacing: -0.01em; + color: $beyond-ink; + } + + .beyond_cliente_telefono { + font-size: 13.5px; + font-weight: 600; + color: $beyond-ink-softer; + } + + .beyond_cliente_pie { + display: flex; + align-items: center; + justify-content: flex-end; + } + + .beyond_pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 12px; + border-radius: 999px; + background: $beyond-panel-durazno; + color: $beyond-panel-acento-pressed; + font-size: 12.5px; + font-weight: 800; + } + } + + // ── Lista ───────────────────────────────────────────────────────────── + .o_beyond_clientes_lista { + // La celda de la foto: cuadro redondeado de 38px, como el diseño. + td[name="image_128"] { + width: 56px; + + > div, > span { + width: 38px; + height: 38px; + border-radius: 13px; + overflow: hidden; + display: block; + } + } + + // Las visitas se leen como pill, igual que en la tarjeta. + td[name="beyond_visit_count"] { + .o_field_widget { + display: inline-flex; + align-items: center; + padding: 4px 11px; + border-radius: 999px; + background: $beyond-panel-durazno; + color: $beyond-panel-acento-pressed; + font-size: 12.5px; + font-weight: 800; + } + } + } + + // ── Ficha ───────────────────────────────────────────────────────────── + .o_form_view .o_field_widget[name="image_1920"] { + // El retrato 4:5 del diseño, no el cuadrado del contacto nativo. + flex: none; + width: 250px; + max-width: 40%; + } + + // Notas: un renglón que crece hasta 132px y luego se desplaza dentro, + // para que la ficha no se estire sin límite y el resto no se mueva. + .beyond_cliente_notas { + textarea { + min-height: 22px; + max-height: 132px; + overflow-y: auto; + resize: none; + line-height: 1.45; + font-size: 15px; + font-weight: 600; + } + } + + // ── Responsivo ──────────────────────────────────────────────────────── + @media (max-width: 767px) { + .o_form_view .o_field_widget[name="image_1920"] { + width: 100%; + max-width: none; + } + + .o_beyond_clientes_kanban .beyond_cliente_foto { + width: 64px; + height: 64px; + border-radius: 18px; + } + } +} diff --git a/addons/beyond_customer/tests/__init__.py b/addons/beyond_customer/tests/__init__.py index e3df48a..d626101 100644 --- a/addons/beyond_customer/tests/__init__.py +++ b/addons/beyond_customer/tests/__init__.py @@ -1,2 +1,3 @@ from . import test_clientes_poblacion from . import test_ficha_360 +from . import test_clientes_vistas diff --git a/addons/beyond_customer/tests/test_clientes_vistas.py b/addons/beyond_customer/tests/test_clientes_vistas.py new file mode 100644 index 0000000..c475277 --- /dev/null +++ b/addons/beyond_customer/tests/test_clientes_vistas.py @@ -0,0 +1,170 @@ +# Part of Beyond. Collina Systems proprietary module. +from lxml import etree + +from odoo.exceptions import AccessError +from odoo.tests import TransactionCase, tagged + +ACCION = 'beyond_customer.action_beyond_clientes' + +# Vistas atadas a la acción de Clientes. Son herencias en modo primary, no +# vistas escritas de cero (ADR-013). +VISTAS = ( + 'beyond_customer.view_beyond_cliente_form', + 'beyond_customer.view_beyond_cliente_kanban', + 'beyond_customer.view_beyond_cliente_list', + 'beyond_customer.view_beyond_cliente_search', +) + + +@tagged('post_install', '-at_install') +class TestClientesVistas(TransactionCase): + """Fase 1 del rediseño: Clientes revestido sobre las vistas nativas.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.cliente = cls.env['res.partner'].create({ + 'name': 'Alejandro Mcdonald', + 'phone': '+52 222 873 3602', + 'city': 'Puebla', + }) + + def _arch(self, xmlid): + return self.env.ref(xmlid).get_combined_arch() + + def _usuario(self, xmlid_grupo, login): + return self.env['res.users'].create({ + 'name': login, 'login': login, + 'group_ids': [(6, 0, [self.env.ref(xmlid_grupo).id])], + }) + + # ── El compromiso con el cliente: nada de correo ────────────────────── + + def test_ninguna_vista_de_clientes_expone_el_correo(self): + """No mostrar el correo es un compromiso, no una preferencia: por eso + va en vistas primary y no en un invisible por contexto, que se pierde + al llegar al registro desde una miga, un enlace o el POS.""" + for xmlid in VISTAS: + arch = etree.fromstring(self._arch(xmlid)) + self.assertFalse( + arch.xpath("//field[@name='email']"), + f"{xmlid} expone el correo electrónico") + + def test_el_buscador_de_clientes_no_busca_por_correo(self): + """El buscador de mostrador encuentra por nombre y por teléfono. El + correo no se muestra, así que tampoco se busca.""" + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_search')) + for campo in arch.xpath("//field"): + self.assertNotIn( + 'email', campo.get('filter_domain') or '', + "el buscador de Clientes sigue buscando por correo") + + def test_contactos_nativo_conserva_lo_suyo(self): + """Las vistas primary existen justamente para no tocar lo nativo: la + cuenta técnica sigue viendo un contacto completo.""" + nativa = etree.fromstring(self._arch('base.view_partner_form')) + self.assertTrue(nativa.xpath("//field[@name='email']"), + "el formulario nativo de contacto perdió el correo") + self.assertTrue(nativa.xpath("//field[@name='vat']"), + "el formulario nativo de contacto perdió el RFC") + + # ── Lo que la ficha sí tiene, y lo que no ───────────────────────────── + + def test_la_ficha_tiene_lo_del_diseno(self): + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_form')) + for campo in ('name', 'phone', 'street', 'state_id', 'comment', + 'beyond_last_visit', 'beyond_usual_branch_id', + 'beyond_avg_ticket'): + self.assertTrue(arch.xpath(f"//field[@name='{campo}']"), + f"la ficha del cliente perdió {campo}") + + def test_la_ficha_no_tiene_datos_fiscales(self): + """El sistema no factura (BRIEF §5.7) y el diseño los descarta.""" + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_form')) + for campo in ('vat', 'website', 'property_account_position_id'): + self.assertFalse(arch.xpath(f"//field[@name='{campo}']"), + f"la ficha del cliente expone {campo}") + + def test_la_foto_usa_el_widget_de_camara(self): + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_form')) + foto = arch.xpath("//field[@name='image_1920']") + self.assertTrue(foto, "la ficha perdió la foto") + self.assertEqual(foto[0].get('widget'), 'beyond_image_camera') + + def test_las_estadisticas_son_solo_dos(self): + """Visitas y Gasto acumulado. «Órdenes de PdV» salió del diseño.""" + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_form')) + botones = arch.xpath("//div[@name='button_box']//button") + self.assertEqual(len(botones), 2, + f"la ficha tiene {len(botones)} botones estadísticos y deben ser dos") + + def test_la_lista_lleva_las_columnas_del_diseno(self): + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_list')) + columnas = [f.get('name') for f in arch.xpath('/list/field')] + self.assertEqual( + columnas, + ['image_128', 'name', 'phone', 'beyond_visit_count', 'city']) + + # ── Anonimizar (LFPDPPP) ───────────────────────────────────────────── + + def test_anonimizar_solo_para_admin_general(self): + arch = etree.fromstring(self._arch('beyond_customer.view_beyond_cliente_form')) + boton = arch.xpath("//button[@name='action_beyond_anonymize']") + self.assertTrue(boton, "la ficha perdió el botón de anonimizar") + self.assertEqual(boton[0].get('groups'), + 'beyond_base.beyond_group_admin_general') + self.assertEqual(boton[0].get('invisible'), 'not id', + "no hay nada que anonimizar en un registro nuevo") + self.assertTrue(boton[0].get('confirm'), + "anonimizar es irreversible: conserva su confirmación") + + def test_anonimizar_borra_tambien_la_foto(self): + """La foto es dato personal (BRIEF §5.1, nota de cumplimiento).""" + self.cliente.write({'image_1920': FOTO_MINIMA}) + self.assertTrue(self.cliente.image_1920) + + self.cliente.action_beyond_anonymize() + + self.assertFalse(self.cliente.image_1920, "la foto sobrevivió al anonimizado") + self.assertFalse(self.cliente.phone) + self.assertNotIn('Alejandro', self.cliente.name) + self.assertTrue(self.cliente.beyond_anonymized) + + def test_un_admin_de_sucursal_no_puede_anonimizar(self): + gerente = self._usuario('beyond_base.beyond_group_admin_sucursal', + 'gerente.anonimiza@beyond.example') + with self.assertRaises(AccessError): + self.cliente.with_user(gerente).action_beyond_anonymize() + + # ── La acción y su dominio ─────────────────────────────────────────── + + def test_el_dominio_de_clientes_sigue_intacto(self): + """C-018: clientes y empleados son poblaciones distintas. El + revestimiento no toca el dominio.""" + accion = self.env.ref(ACCION) + self.assertEqual( + eval(accion.domain), # noqa: S307 — dominio propio + [('is_company', '=', False), ('user_ids', '=', False), + ('employee_ids', '=', False)]) + + def test_la_ficha_carga_para_los_tres_roles(self): + """Una vista que no carga para un rol es una pantalla en blanco sin + error en el servidor: se comprueba pidiéndola como cada uno.""" + for grupo in ('beyond_base.beyond_group_admin_general', + 'beyond_base.beyond_group_admin_sucursal', + 'beyond_base.beyond_group_empleado'): + usuario = self._usuario(grupo, f'ficha.{grupo.split(".")[-1]}@beyond.example') + for vista, modo in (('view_beyond_cliente_form', 'form'), + ('view_beyond_cliente_kanban', 'kanban'), + ('view_beyond_cliente_list', 'list')): + datos = self.env['res.partner'].with_user(usuario).get_view( + self.env.ref(f'beyond_customer.{vista}').id, modo) + self.assertTrue(datos.get('arch'), + f"{vista} no carga para {grupo}") + + +# PNG de 1x1 transparente: basta para probar que el anonimizado borra la foto. +FOTO_MINIMA = ( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmM' + 'IQAAAABJRU5ErkJggg==' +) diff --git a/addons/beyond_customer/views/res_partner_views.xml b/addons/beyond_customer/views/res_partner_views.xml index d116d18..5ad894e 100644 --- a/addons/beyond_customer/views/res_partner_views.xml +++ b/addons/beyond_customer/views/res_partner_views.xml @@ -62,10 +62,30 @@ oro §4). Decisión documentada: el consumo del personal NO cuenta como cliente ni entra a las métricas comparativas de Fase 5; si el negocio quiere seguirlo, será un reporte aparte. --> + + + res.partner.search.beyond.cliente + res.partner + + primary + + + [('phone', 'ilike', self)] + + + + + + Clientes res.partner - kanban,form,list + kanban,list,form + [('is_company', '=', False), ('user_ids', '=', False), ('employee_ids', '=', False)]

Registra tu primer cliente

@@ -73,6 +93,176 @@
+ + + + + res.partner.form.beyond.cliente + res.partner + + primary + 32 + + + + + + + beyond_image_camera + {'preview_image': 'avatar_128'} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + not id + +
+
+ + + res.partner.kanban.beyond.cliente + res.partner + + + + + +
+
+ +
+
+ + +
+
+
+ + visitas + +
+
+
+
+
+
+ + + res.partner.list.beyond.cliente + res.partner + + + + + + + + + + + + + + + kanban + + + + + + list + + + + + + form + + + +