Reviste Clientes y le da una cámara a la foto del cliente
Las tres vistas y el buscador de Clientes pasan a ser herencias en modo primary atadas a la acción. Siguen siendo xpath sobre lo nativo, no vistas escritas de cero, pero el compromiso de no mostrar el correo aguanta por construcción y no por propagación de contexto: al registro se llega también desde una miga, un enlace o el POS, y ahí un invisible por contexto habría dejado el correo a la vista. Contactos nativo conserva su correo y su RFC, con test que lo fija. De la ficha sale el cuaderno de pestañas entero. Traía un segundo correo, un segundo bloque de dirección y una copia de las notas, y además ofrecía una pestaña de Facturación en un sistema que no factura (BRIEF §5.7). La caja de botones estadísticos se sustituye completa: media docena de módulos del core cuelgan los suyos ahí, y quitarlos uno por uno ataría la vista a qué módulos estén instalados. Quedan los dos del diseño. El widget de foto hereda del ImageField nativo, así que subir, limpiar y guardar siguen siendo los del core; lo que agrega es el menú del diseño y un diálogo de captura con la cámara TRASERA por defecto, que es el caso de uso —el mostrador retrata al cliente, no se hace una selfie—. El stream se libera al cerrar, al salir con Escape, al navegar dentro del cliente y al dejar la página; también si el diálogo se cierra antes de que la cámara termine de encender. Sin contexto seguro el navegador ni siquiera define navigator.mediaDevices, así que en las tablets no habrá diálogo de cámara hasta que producción tenga TLS. El widget no ofrece un botón que reventaría: oculta «Tomar fotografía» y deja «Subir archivo» con capture=environment, que abre la cámara nativa de Android sin exigir https. Queda anotado en despliegue.md. Las iniciales sobre durazno son un widget propio y no avatar_128: el mixin del core dibuja UNA letra sobre un color derivado del id, dentro de un SVG en base64 servido como imagen, así que ninguna hoja de estilo puede volverlo el durazno del diseño ni darle las dos letras. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
efa42e511a
commit
a9cd2ee3a9
14 files changed
+1305
-2
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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 <img>. 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);
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="beyond_base.AvatarInitials">
|
||||
<img t-if="valor" class="beyond_avatar_img" t-att-src="url" t-att-alt="nombre"/>
|
||||
<div t-else="" class="beyond_avatar_iniciales" t-att-title="nombre" t-esc="iniciales"/>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -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);
|
||||
@@ -0,0 +1,97 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<!-- The native uploader plus one attribute. capture="environment" is what
|
||||
makes Android open its own camera app, and it needs no secure context
|
||||
— which is the whole point while production has no TLS. -->
|
||||
<t t-name="beyond_base.FileUploader" t-inherit="web.FileUploader" t-inherit-mode="primary">
|
||||
<xpath expr="//input[@type='file']" position="attributes">
|
||||
<attribute name="t-att-capture">props.capture or false</attribute>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_base.ImageCamera">
|
||||
<div class="beyond_foto"
|
||||
t-on-mouseenter="mostrarMenu"
|
||||
t-on-mouseleave="ocultarMenu"
|
||||
t-on-click="alternarMenu">
|
||||
<img class="beyond_foto_img"
|
||||
t-att-alt="imgAlt"
|
||||
t-att-src="this.getUrl(props.previewImage or props.name)"
|
||||
t-on-error.stop="onLoadFailed"/>
|
||||
|
||||
<t t-if="!props.readonly and menu.abierto">
|
||||
<div class="beyond_foto_velo">
|
||||
<svg width="38" height="38" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M4 8.6h3.2l1.4-2.2h6.8l1.4 2.2H20v10.2H4V8.6Z" stroke="#FFFFFF" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="13.4" r="3.2" stroke="#FFFFFF" stroke-width="1.8"/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="beyond_foto_menu" t-on-click.stop="">
|
||||
<!-- Rendered ONLY where the camera can actually open. See
|
||||
the note at the top of beyond_image_camera.js. -->
|
||||
<button t-if="camaraDisponible" class="beyond_foto_opcion"
|
||||
t-on-click="abrirCamara">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M4 8.6h3.2l1.4-2.2h6.8l1.4 2.2H20v10.2H4V8.6Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="13.4" r="3.2" stroke="currentColor" stroke-width="1.8"/>
|
||||
</svg>
|
||||
<span>Tomar fotografía</span>
|
||||
</button>
|
||||
|
||||
<FileUploader
|
||||
acceptedFileExtensions="'image/*'"
|
||||
capture="'environment'"
|
||||
t-key="props.record.resId"
|
||||
onUploaded.bind="onFileUploaded">
|
||||
<t t-set-slot="toggler">
|
||||
<button class="beyond_foto_opcion" t-on-click="cerrarMenu">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M12 16.4V4.8M7.6 9.2 12 4.8l4.4 4.4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4.6 15.4v3.2a1.4 1.4 0 0 0 1.4 1.4h12a1.4 1.4 0 0 0 1.4-1.4v-3.2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<span>Subir archivo</span>
|
||||
</button>
|
||||
</t>
|
||||
</FileUploader>
|
||||
|
||||
<button t-if="tieneImagen" class="beyond_foto_opcion beyond_foto_borrar"
|
||||
t-on-click="eliminar">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<path d="M5 7h14M9.5 7V4.8h5V7M6.8 7l.9 12.2h8.6L17.2 7" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<span>Eliminar</span>
|
||||
</button>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<t t-name="beyond_base.CameraDialog">
|
||||
<Dialog title="'Tomar fotografía'" size="'md'" contentClass="'beyond_camara_dialogo'">
|
||||
<div class="beyond_camara">
|
||||
<t t-if="state.error">
|
||||
<p class="beyond_camara_error">
|
||||
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».
|
||||
</p>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<video class="beyond_camara_video" t-ref="video"
|
||||
autoplay="autoplay" playsinline="playsinline" muted="muted"/>
|
||||
<p t-if="!state.listo" class="beyond_camara_espera">Encendiendo la cámara…</p>
|
||||
</t>
|
||||
</div>
|
||||
<t t-set-slot="footer">
|
||||
<button class="btn btn-primary" t-att-disabled="!state.listo"
|
||||
t-on-click="capturar">Tomar la foto</button>
|
||||
<button t-if="state.variasCamaras" class="btn btn-secondary"
|
||||
t-on-click="cambiarCamara">Cambiar de cámara</button>
|
||||
<button class="btn btn-secondary" t-on-click="() => props.close()">Cancelar</button>
|
||||
</t>
|
||||
</Dialog>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
@@ -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 */ `
|
||||
<form>
|
||||
<field name="image_1920" widget="beyond_image_camera"/>
|
||||
</form>`;
|
||||
|
||||
/** 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");
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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 <body>, 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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!--
|
||||
Datos demo de Clientes (Fase 1 del rediseño). Cuatro personas, para
|
||||
que la pantalla se pueda enseñar en dos minutos con las dos formas de
|
||||
la tarjeta: la primera trae foto y las otras tres caen en las
|
||||
iniciales sobre durazno, que es el caso normal en una red que apenas
|
||||
empieza a retratar a su clientela.
|
||||
|
||||
Sin correo electrónico a propósito: no se muestra en ninguna vista de
|
||||
Clientes (decisión del 24-ago), así que tampoco se inventa aquí.
|
||||
|
||||
Las cuatro cumplen el dominio de la acción —persona, sin usuario y
|
||||
sin empleado (C-018)—, que es justo lo que las hace aparecer.
|
||||
|
||||
La foto es la de una empleada demo reutilizada: es un retrato ficticio
|
||||
que ya vive en el repo y evita agregar un binario nuevo solo para
|
||||
esto. Si alguna vez estorba en una demo, se quita el atributo.
|
||||
-->
|
||||
<record id="demo_cliente_alejandro" model="res.partner">
|
||||
<field name="name">Alejandro Mcdonald</field>
|
||||
<field name="phone">+52 222 873 3602</field>
|
||||
<field name="street">Av. Juárez 1820, La Paz</field>
|
||||
<field name="city">Puebla</field>
|
||||
<field name="comment">Prefiere cita temprano. Alérgico al amoniaco.</field>
|
||||
<field name="image_1920" type="base64" file="beyond_base/static/demo/empleada_daniela.png"/>
|
||||
</record>
|
||||
|
||||
<record id="demo_cliente_marisol" model="res.partner">
|
||||
<field name="name">Marisol Ibáñez</field>
|
||||
<field name="phone">+52 222 145 9080</field>
|
||||
<field name="street">Calle 7 Sur 304</field>
|
||||
<field name="city">Puebla</field>
|
||||
</record>
|
||||
|
||||
<record id="demo_cliente_rodrigo" model="res.partner">
|
||||
<field name="name">Rodrigo Cantú</field>
|
||||
<field name="phone">+52 55 4412 7788</field>
|
||||
<field name="street">Adamanto 45</field>
|
||||
<field name="city">Ciudad de México</field>
|
||||
<field name="comment">Llega siempre con su hijo.</field>
|
||||
</record>
|
||||
|
||||
<record id="demo_cliente_ximena" model="res.partner">
|
||||
<field name="name">Ximena</field>
|
||||
<field name="phone">+52 222 900 1122</field>
|
||||
<field name="city">San Andrés Cholula</field>
|
||||
</record>
|
||||
</odoo>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
from . import test_clientes_poblacion
|
||||
from . import test_ficha_360
|
||||
from . import test_clientes_vistas
|
||||
@@ -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=='
|
||||
)
|
||||
@@ -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. -->
|
||||
<!-- Buscador de la acción: el de mostrador, sin correo. La vista
|
||||
heredada que sí lo busca (view_res_partner_filter_beyond) se queda
|
||||
como está para Contactos nativo. -->
|
||||
<record id="view_beyond_cliente_search" model="ir.ui.view">
|
||||
<field name="name">res.partner.search.beyond.cliente</field>
|
||||
<field name="model">res.partner</field>
|
||||
<field name="inherit_id" ref="view_res_partner_filter_beyond"/>
|
||||
<field name="mode">primary</field>
|
||||
<field name="arch" type="xml">
|
||||
<field name="phone" position="attributes">
|
||||
<attribute name="filter_domain">[('phone', 'ilike', self)]</attribute>
|
||||
</field>
|
||||
<!-- El buscador nativo trae su propio campo de correo, además del
|
||||
que la herencia de mostrador metía en el filtro del teléfono.
|
||||
Los dos fuera: si no se muestra, no se busca. -->
|
||||
<field name="email" position="replace"/>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_beyond_clientes" model="ir.actions.act_window">
|
||||
<field name="name">Clientes</field>
|
||||
<field name="res_model">res.partner</field>
|
||||
<field name="view_mode">kanban,form,list</field>
|
||||
<field name="view_mode">kanban,list,form</field>
|
||||
<field name="search_view_id" ref="view_beyond_cliente_search"/>
|
||||
<field name="domain">[('is_company', '=', False), ('user_ids', '=', False), ('employee_ids', '=', False)]</field>
|
||||
<field name="help" type="html">
|
||||
<p class="o_view_nocontent_smiling_face">Registra tu primer cliente</p>
|
||||
@@ -73,6 +93,176 @@
|
||||
</field>
|
||||
</record>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════════════════════════════════════
|
||||
Panel General · Clientes (ADR-013, Fase 1)
|
||||
|
||||
Las tres vistas y el buscador son HERENCIAS EN MODO PRIMARY atadas a
|
||||
la acción, no vistas escritas de cero: siguen siendo xpath sobre lo
|
||||
nativo, así que el revestimiento no reimplementa nada.
|
||||
|
||||
Por qué primary y no `invisible="context.get(...)"`: no mostrar el
|
||||
correo es un compromiso con el cliente, no una preferencia. El
|
||||
contexto de una acción se pierde al abrir el registro desde una miga,
|
||||
un enlace, una notificación o el «ver cliente» del POS, y ahí el
|
||||
correo volvería a aparecer. Una vista primary aguanta por
|
||||
construcción. De paso, Contactos nativo y el POS conservan sus vistas
|
||||
intactas: nada de lo de aquí los toca.
|
||||
══════════════════════════════════════════════════════════════════ -->
|
||||
|
||||
<record id="view_beyond_cliente_form" model="ir.ui.view">
|
||||
<field name="name">res.partner.form.beyond.cliente</field>
|
||||
<field name="model">res.partner</field>
|
||||
<field name="inherit_id" ref="base.view_partner_form"/>
|
||||
<field name="mode">primary</field>
|
||||
<field name="priority">32</field>
|
||||
<field name="arch" type="xml">
|
||||
<!-- FUERA el cuaderno entero, y va PRIMERO a propósito: sus
|
||||
pestañas traían un segundo correo, un segundo bloque de
|
||||
dirección y una copia de las notas, y con él fuera cada
|
||||
xpath de abajo tiene un solo nodo posible.
|
||||
Lo que se va: Contactos y direcciones (un cliente del salón
|
||||
no tiene contactos hijos), Ventas y compras, Facturación
|
||||
—que además no debería ofrecerse: el sistema no factura,
|
||||
BRIEF §5.7—, Asignación de socio y Notas, que vuelve abajo
|
||||
con la forma del diseño. -->
|
||||
<xpath expr="//notebook" position="replace"/>
|
||||
|
||||
<!-- La foto: 4:5 y con cámara propia (BRIEF §5.1). -->
|
||||
<field name="image_1920" position="attributes">
|
||||
<attribute name="widget">beyond_image_camera</attribute>
|
||||
<attribute name="options">{'preview_image': 'avatar_128'}</attribute>
|
||||
</field>
|
||||
|
||||
<!-- Persona o empresa no se pregunta: la acción ya filtra
|
||||
personas (is_company = False). -->
|
||||
<field name="company_type" position="replace"/>
|
||||
|
||||
<!-- FUERA el correo, en la ficha y en el buscador (24-ago). -->
|
||||
<field name="email" position="replace"/>
|
||||
|
||||
<!-- FUERA la empresa a la que pertenece: un cliente del salón es
|
||||
una persona, no el contacto de una compañía. -->
|
||||
<field name="parent_id" position="replace"/>
|
||||
|
||||
<!-- Del bloque de dirección solo se conservan calle y estado, que
|
||||
es lo que pide el diseño. -->
|
||||
<field name="street2" position="replace"/>
|
||||
<field name="zip" position="replace"/>
|
||||
<field name="country_id" position="replace"/>
|
||||
|
||||
<!-- FUERA los datos fiscales y lo que no es de un cliente de
|
||||
mostrador. El RFC no se pide: no se factura (BRIEF §5.7). -->
|
||||
<field name="function" position="replace"/>
|
||||
<field name="vat" position="replace"/>
|
||||
<field name="website" position="replace"/>
|
||||
<field name="category_id" position="replace"/>
|
||||
|
||||
<!-- Notas a la vista, con el alto que crece hasta 132px por SCSS.
|
||||
comment es HTML en el modelo; el widget de texto es el que da
|
||||
el renglón que crece del diseño en vez de un editor. -->
|
||||
<xpath expr="//group[@name='beyond_360']" position="before">
|
||||
<group class="beyond_cliente_notas">
|
||||
<field name="comment" string="Notas" nolabel="1" colspan="2"
|
||||
widget="text"
|
||||
placeholder="Escribe una nota sobre este cliente…"/>
|
||||
</group>
|
||||
</xpath>
|
||||
|
||||
<!-- Solo dos estadísticas, las del diseño. La caja de botones
|
||||
se sustituye entera porque media docena de módulos del core
|
||||
cuelgan los suyos ahí (órdenes de PdV, facturas, facturas de
|
||||
proveedor, tokens de pago, empleados, números de serie), y
|
||||
quitarlos uno por uno ataría esta vista a qué módulos estén
|
||||
instalados. Los dos de Beyond se declaran aquí y no se
|
||||
heredan de view_partner_form_beyond, que sigue sirviendo a
|
||||
Contactos nativo: es la única duplicación de la fase y es
|
||||
deliberada. -->
|
||||
<xpath expr="//div[@name='button_box']" position="replace">
|
||||
<div class="oe_button_box" name="button_box">
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<button name="action_view_beyond_orders" type="object"
|
||||
class="oe_stat_button" icon="fa-shopping-bag">
|
||||
<field name="beyond_visit_count" widget="statinfo" string="Visitas"/>
|
||||
</button>
|
||||
<button name="action_view_beyond_orders" type="object"
|
||||
class="oe_stat_button" icon="fa-money">
|
||||
<field name="beyond_total_spent" widget="statinfo" string="Gasto acumulado"/>
|
||||
</button>
|
||||
</div>
|
||||
</xpath>
|
||||
|
||||
<!-- El botón rojo solo tiene sentido sobre un registro guardado:
|
||||
no hay nada que anonimizar en uno nuevo. -->
|
||||
<xpath expr="//button[@name='action_beyond_anonymize']" position="attributes">
|
||||
<attribute name="invisible">not id</attribute>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_beyond_cliente_kanban" model="ir.ui.view">
|
||||
<field name="name">res.partner.kanban.beyond.cliente</field>
|
||||
<field name="model">res.partner</field>
|
||||
<field name="arch" type="xml">
|
||||
<kanban class="o_beyond_clientes_kanban">
|
||||
<field name="beyond_visit_count"/>
|
||||
<templates>
|
||||
<t t-name="card" class="beyond_cliente_tarjeta">
|
||||
<div class="beyond_cliente_cabeza">
|
||||
<div class="beyond_cliente_foto">
|
||||
<field name="image_128" widget="beyond_avatar_initials"/>
|
||||
</div>
|
||||
<div class="beyond_cliente_datos">
|
||||
<field name="name" class="beyond_cliente_nombre"/>
|
||||
<field name="phone" class="beyond_cliente_telefono"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="beyond_cliente_pie">
|
||||
<span class="beyond_pill">
|
||||
<field name="beyond_visit_count"/> visitas
|
||||
</span>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
</kanban>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_beyond_cliente_list" model="ir.ui.view">
|
||||
<field name="name">res.partner.list.beyond.cliente</field>
|
||||
<field name="model">res.partner</field>
|
||||
<field name="arch" type="xml">
|
||||
<list class="o_beyond_clientes_lista" create="true" delete="false">
|
||||
<field name="image_128" widget="beyond_avatar_initials"
|
||||
string="" width="56px" optional="show"/>
|
||||
<field name="name" string="Nombre"/>
|
||||
<field name="phone" string="Teléfono"/>
|
||||
<field name="beyond_visit_count" string="Visitas"/>
|
||||
<field name="city" string="Ciudad"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
|
||||
<record id="action_beyond_clientes_kanban" model="ir.actions.act_window.view">
|
||||
<field name="sequence" eval="1"/>
|
||||
<field name="view_mode">kanban</field>
|
||||
<field name="view_id" ref="view_beyond_cliente_kanban"/>
|
||||
<field name="act_window_id" ref="action_beyond_clientes"/>
|
||||
</record>
|
||||
<record id="action_beyond_clientes_list" model="ir.actions.act_window.view">
|
||||
<field name="sequence" eval="2"/>
|
||||
<field name="view_mode">list</field>
|
||||
<field name="view_id" ref="view_beyond_cliente_list"/>
|
||||
<field name="act_window_id" ref="action_beyond_clientes"/>
|
||||
</record>
|
||||
<record id="action_beyond_clientes_form" model="ir.actions.act_window.view">
|
||||
<field name="sequence" eval="3"/>
|
||||
<field name="view_mode">form</field>
|
||||
<field name="view_id" ref="view_beyond_cliente_form"/>
|
||||
<field name="act_window_id" ref="action_beyond_clientes"/>
|
||||
</record>
|
||||
|
||||
<menuitem id="menu_beyond_clientes" name="Clientes"
|
||||
parent="beyond_branch.menu_beyond_root"
|
||||
action="action_beyond_clientes"
|
||||
|
||||
Reference in new issue
Block a user