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:
Jorem JuárezandClaude Opus 5 committed 2026-08-26 10:35:54 -06:00
1 parent efa42e511a
commit a9cd2ee3a9
14 files changed
+1305 -2

No files matched your search

@@ -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>