/** Part of Beyond. Collina Systems proprietary module. */ import { Component, onWillUnmount, useExternalListener, useRef, useState } from "@odoo/owl"; import { Dialog } from "@web/core/dialog/dialog"; import { registry } from "@web/core/registry"; // useExternalListener viene de OWL, NO de @web/core/utils/hooks: importarlo // de ahí devuelve undefined y el diálogo de la cámara revienta al renderizar, // sin decir por qué. Lo cazaron las unitarias en navegador. import { useService } 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; // «Listo» es tener FOTOGRAMA, no que la cámara haya respondido. // getUserMedia resuelve antes de que el vídeo tenga dimensiones, y // con el botón habilitado en ese hueco, tocarlo no hacía nada: el // lienzo se dibujaba de un vídeo de 0×0 y la función salía sin // decir por qué. if (!this.video.el.videoWidth) { await new Promise((listo) => { this.video.el.addEventListener("loadedmetadata", listo, { once: true }); }); } } if (this.destruido) { this.detener(); return; } 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; } // Si el vídeo aún no reporta dimensiones, las de la pista sirven: // más vale una foto que un botón que no hace nada. const ajustes = this.stream?.getVideoTracks()[0]?.getSettings() || {}; const ancho = video.videoWidth || ajustes.width; const alto = video.videoHeight || ajustes.height; if (!ancho || !alto) { this.notification.add( _t("La cámara todavía no entrega imagen. Inténtalo de nuevo."), { type: "warning" } ); 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. * * The second tap has to actually close it. `abierto = fijado || abierto` * looked harmless and was not: once open, the right-hand side kept it * open for ever and the menu could only be dismissed by moving a mouse * the tablet does not have. */ alternarMenu() { this.menu.fijado = !this.menu.fijado; this.menu.abierto = this.menu.fijado; } cerrarMenu() { this.menu.fijado = false; this.menu.abierto = false; } /** * EL ÚNICO punto por el que la imagen entra al registro. * * Las tres rutas —cámara, archivo y eliminar— terminan aquí, y esa es la * lección de un defecto real: la subida pintaba la imagen sin escribirla, * así que al guardar no quedaba nada, mientras la cámara sí funcionaba. * Dos caminos distintos hacia el mismo dato es una invitación a que uno de * los dos se rompa en silencio. */ escribirImagen(datos) { this.state.isValid = true; return this.props.record.update({ [this.props.name]: datos }); } /** * La subida pasa por el pipeline nativo (que redimensiona y convierte) y * ese termina escribiendo con record.update, el mismo punto. Lo que se * agrega es cerrar el menú DESPUÉS, nunca antes: cerrarlo al pulsar * desmontaba el FileUploader que acababa de abrir el selector del sistema. */ async onFileUploaded(info) { await super.onFileUploaded(info); this.cerrarMenu(); } 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.escribirImagen(datos), }); } eliminar() { this.cerrarMenu(); this.state.isValid = true; this.escribirImagen(false); } } export const beyondImageCamera = { ...imageField, component: BeyondImageCamera, displayName: _t("Foto con cámara"), }; registry.category("fields").add("beyond_image_camera", beyondImageCamera);