diff --git a/Assets/JS/Modelo347Email.js b/Assets/JS/Modelo347Email.js new file mode 100644 index 0000000..b711dda --- /dev/null +++ b/Assets/JS/Modelo347Email.js @@ -0,0 +1,326 @@ +/** + * This file is part of Modelo347 plugin for FacturaScripts + * Copyright (C) 2026 Carlos Garcia Gomez + * + * Selección de destinatarios de la carta del modelo 347: + * - doble lista incluidos/seleccionados, + * - filtro de búsqueda y envío por fetch sin recargar la pantalla. + * + * @author Jose Antonio Cuello Principal + */ +window.Modelo347 = window.Modelo347 || {}; + +Modelo347.Email = { + // ===== PUBLIC ===== + + /** + * Arranca el módulo si existe su contenedor en la página. + */ + init() { + this._container = document.getElementById('m347-email'); + if (!this._container) { + return; + } + + this._form = document.getElementById('m347-email-form'); + this._left = document.getElementById('m347-left'); + this._right = document.getElementById('m347-right'); + this._search = document.getElementById('m347-search'); + this._sendButton = document.getElementById('m347-send'); + this._items = JSON.parse(document.getElementById('m347-recipients').textContent).map(row => ({ + ...row, + marked: false, + searchFields: [row.cifnif, row.name, row.email].map(value => this._normalize(value)), + selected: false, + sent: false + })); + + this._bindEvents(); + this.render(); + }, + + /** + * Pinta las dos listas, los contadores y el estado del botón de envío. + */ + render() { + const terms = this._parseTerms(this._search.value); + const left = this._items.filter(item => !item.selected && this._matches(item, terms)); + const right = this._items.filter(item => item.selected); + + this._renderList(this._left, left); + this._renderList(this._right, right); + document.getElementById('m347-left-count').textContent = left.length; + document.getElementById('m347-right-count').textContent = right.length; + document.getElementById('m347-send-count').textContent = right.length; + this._sendButton.disabled = this._sending || right.length === 0; + }, + + // ===== PRIVATE ===== + + /** @type {HTMLElement|null} Contenedor principal del módulo. */ + _container: null, + + /** @type {HTMLFormElement|null} Formulario con los filtros y el token. */ + _form: null, + + /** @type {Array} Destinatarios con su estado (marcado, seleccionado y enviado). */ + _items: [], + + /** @type {HTMLElement|null} Lista de incluidos. */ + _left: null, + + /** @type {HTMLElement|null} Lista de seleccionados. */ + _right: null, + + /** @type {HTMLInputElement|null} Campo de búsqueda. */ + _search: null, + + /** @type {HTMLButtonElement|null} Botón de envío. */ + _sendButton: null, + + /** @type {boolean} Indica si hay un envío en curso. */ + _sending: false, + + /** + * Asocia los eventos de botones, listas y buscador. + */ + _bindEvents() { + document.getElementById('m347-add').addEventListener('click', () => this._move(true, false)); + document.getElementById('m347-add-all').addEventListener('click', () => this._move(true, true)); + document.getElementById('m347-remove').addEventListener('click', () => this._move(false, false)); + document.getElementById('m347-remove-all').addEventListener('click', () => this._move(false, true)); + document.getElementById('m347-search-clear').addEventListener('click', () => { + this._search.value = ''; + this.render(); + this._search.focus(); + }); + this._search.addEventListener('input', () => this.render()); + this._sendButton.addEventListener('click', () => this._send()); + + [this._left, this._right].forEach(list => { + list.addEventListener('click', event => this._onItemEvent(event, false)); + list.addEventListener('dblclick', event => this._onItemEvent(event, true)); + }); + }, + + /** + * Busca el destinatario por su código. + * + * @param {string} code + * @returns {Object|undefined} + */ + _findItem(code) { + return this._items.find(item => item.code === code); + }, + + /** + * Indica si el destinatario cumple todos los términos en alguno de sus campos. + * + * @param {Object} item + * @param {Array} terms + * @returns {boolean} + */ + _matches(item, terms) { + return terms.every(term => item.searchFields.some(field => { + switch (term.mode) { + case 'start': + return field.startsWith(term.value); + case 'end': + return field.endsWith(term.value); + default: + return field.includes(term.value); + } + })); + }, + + /** + * Mueve los marcados (o todos) entre listas. Hacia seleccionados solo mueve los visibles por el filtro. + * + * @param {boolean} toSelected + * @param {boolean} all + */ + _move(toSelected, all) { + const terms = this._parseTerms(this._search.value); + this._items.forEach(item => { + const source = toSelected ? !item.selected && this._matches(item, terms) : item.selected; + if (source && (all || item.marked)) { + item.selected = toSelected; + item.marked = false; + } + }); + this.render(); + }, + + /** + * Normaliza un texto para comparar sin mayúsculas ni acentos. + * + * @param {string} text + * @returns {string} + */ + _normalize(text) { + return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase(); + }, + + /** + * Clic: marca o desmarca el destinatario. Doble clic: lo pasa a la otra lista. + * + * @param {MouseEvent} event + * @param {boolean} isDouble + */ + _onItemEvent(event, isDouble) { + const element = event.target.closest('[data-code]'); + const item = element ? this._findItem(element.dataset.code) : undefined; + if (!item) { + return; + } + + if (false === isDouble) { + // sin repintar: si se reconstruye la lista entre los dos clics, el navegador no lanza el dblclick + item.marked = !item.marked; + this._setItemClasses(element, item); + return; + } + + item.selected = !item.selected; + item.marked = false; + this.render(); + }, + + /** + * Convierte el texto de búsqueda en términos: 'texto%' comienza por, '%texto' termina por + * y el resto contiene. Un % intermedio se trata como literal. + * + * @param {string} text + * @returns {Array} + */ + _parseTerms(text) { + return this._normalize(text).split(/\s+/).filter(word => word !== '').map(word => { + const starts = word.startsWith('%'); + const ends = word.length > 1 && word.endsWith('%'); + const value = word.substring(starts ? 1 : 0, ends ? word.length - 1 : word.length); + const mode = starts === ends ? 'contains' : (ends ? 'start' : 'end'); + return {mode: mode, value: value}; + }).filter(term => term.value !== ''); + }, + + /** + * Pinta los destinatarios en una lista. + * + * @param {HTMLElement} list + * @param {Array} items + */ + _renderList(list, items) { + list.replaceChildren(); + if (items.length === 0) { + const empty = document.createElement('div'); + empty.className = 'list-group-item text-muted text-center'; + empty.textContent = this._container.dataset.empty; + list.appendChild(empty); + return; + } + + items.forEach(item => { + const element = document.createElement('div'); + element.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center'; + this._setItemClasses(element, item); + element.dataset.code = item.code; + element.style.cursor = 'pointer'; + + const info = document.createElement('div'); + const title = document.createElement('div'); + title.textContent = item.cifnif + ' · ' + item.name; + const email = document.createElement('small'); + email.textContent = item.email; + info.append(title, email); + + const side = document.createElement('div'); + side.className = 'text-end text-nowrap ms-2'; + if (item.sent) { + const badge = document.createElement('span'); + badge.className = 'badge bg-success me-2'; + badge.textContent = this._container.dataset.sent; + side.appendChild(badge); + } + side.appendChild(document.createTextNode(item.total)); + + element.append(info, side); + list.appendChild(element); + }); + }, + + /** + * Envía los seleccionados. Al terminar los devuelve a incluidos marcados como enviados. + */ + async _send() { + const codes = this._items.filter(item => item.selected).map(item => item.code); + if (codes.length === 0 || this._sending) { + return; + } + + const data = new FormData(this._form); + data.append('action', 'send-selected'); + codes.forEach(code => data.append('codes[]', code)); + + this._setLocked(true); + try { + const response = await fetch(this._container.dataset.url, {method: 'POST', body: data}); + const result = await response.json(); + if (result.token) { + this._form.querySelector('[name="multireqtoken"]').value = result.token; + } + if (result.ok) { + result.codes.forEach(code => { + const item = this._findItem(code); + if (item) { + item.selected = false; + item.sent = true; + } + }); + } + this._showResult(result.ok, result.message); + } catch (error) { + this._showResult(false, error.message); + } finally { + this._setLocked(false); + } + }, + + /** + * Aplica al elemento las clases de su estado: marcado o enviado. + * + * @param {HTMLElement} element + * @param {Object} item + */ + _setItemClasses(element, item) { + element.classList.toggle('active', item.marked); + element.classList.toggle('list-group-item-success', item.sent); + }, + + /** + * Bloquea o desbloquea la pantalla durante el envío: listas, buscador, botones y "Volver". + * + * @param {boolean} locked + */ + _setLocked(locked) { + this._sending = locked; + this._container.inert = locked; + this._form.inert = locked; + this._container.classList.toggle('opacity-50', locked); + document.getElementById('m347-send-spinner').classList.toggle('d-none', !locked); + this.render(); + }, + + /** + * Muestra el resultado del envío. + * + * @param {boolean} ok + * @param {string} message + */ + _showResult(ok, message) { + const result = document.getElementById('m347-result'); + result.className = 'alert ' + (ok ? 'alert-success' : 'alert-danger'); + result.textContent = message; + } +}; + +document.addEventListener('DOMContentLoaded', () => Modelo347.Email.init()); diff --git a/Controller/Modelo347.php b/Controller/Modelo347.php index 40dc077..a7cdc0f 100644 --- a/Controller/Modelo347.php +++ b/Controller/Modelo347.php @@ -134,19 +134,24 @@ public function privateCore(&$response, $user, $permissions) $action = $this->request->request->get('action', ''); $this->defaultAction(); - switch ($action) { - case 'download-excel': - $this->downloadExcelAction(); - break; - - case 'download-txt': - $this->downloadTxtAction(); - break; + $this->execAction($action); + } - case 'send-emails': - $this->sendEmailsAction(); - break; - } + /** + * Calcula los clientes y proveedores a declarar con los filtros cargados y guarda sus datos y totales. + * El cálculo está en Lib/Modelo347, compartido con el endpoint de la API. + * + * @return Modelo347Lib cálculo ya ejecutado, para consultar sus avisos. + */ + protected function calculate(): Modelo347Lib + { + $model347 = new Modelo347Lib($this->codejercicio, $this->amount, (string)$this->examine, (string)$this->grouping, $this->excludeIrpf); + $model347->calculate(); + $this->customersData = $model347->customersData; + $this->customersTotals = $model347->customersTotals; + $this->suppliersData = $model347->suppliersData; + $this->suppliersTotals = $model347->suppliersTotals; + return $model347; } /** @@ -167,36 +172,8 @@ protected function checkData(Modelo347Lib $model347): void */ protected function defaultAction(): void { - // buscamos el primer ejercicio abierto, para tenerlo como predeterminado - $codejercicio = null; - $exerciseModel = new Ejercicio(); - foreach ($exerciseModel->all([], ['fechainicio' => 'DESC'], 0, 0) as $exe) { - if ($exe->isOpened()) { - $codejercicio = $exe->codejercicio; - break; - } - } - - $this->amount = (float)$this->request->request->get('amount', $this->amount); - $this->codejercicio = $this->request->request->get('codejercicio', $codejercicio); - $this->examine = $this->request->request->get('examine', $this->examine); - $this->excludeIrpf = (bool)$this->request->request->get('excludeirpf', $this->excludeIrpf); - $this->grouping = $this->request->request->get('grouping', $this->grouping); - $this->justificante = preg_replace('/[^0-9]/', '', $this->request->request->get('justificante', '')); - $this->declarationType = $this->request->request->get('declarationtype', ''); - if (!in_array($this->declarationType, ['C', 'S'])) { - $this->declarationType = ''; - } - $this->justificanteAnterior = preg_replace('/[^0-9]/', '', $this->request->request->get('justificanteanterior', '')); - - // el cálculo está en Lib/Modelo347, compartido con el endpoint de la API - $model347 = new Modelo347Lib($this->codejercicio, $this->amount, (string)$this->examine, (string)$this->grouping, $this->excludeIrpf); - $model347->calculate(); - $this->customersData = $model347->customersData; - $this->customersTotals = $model347->customersTotals; - $this->suppliersData = $model347->suppliersData; - $this->suppliersTotals = $model347->suppliersTotals; - + $this->loadFilters(); + $model347 = $this->calculate(); $this->checkData($model347); } @@ -266,6 +243,56 @@ protected function downloadTxtAction(): void ->setContent($content); } + /** + * Ejecuta la acción solicitada tras cargar los datos. + * + * @param string $action + */ + protected function execAction(string $action): void + { + switch ($action) { + case 'download-excel': + $this->downloadExcelAction(); + break; + + case 'download-txt': + $this->downloadTxtAction(); + break; + + case 'send-emails': + $this->sendEmailsAction(); + break; + } + } + + /** + * Lee de la petición los filtros de cálculo y de la declaración. + * Si no se indica ejercicio, usa el primer ejercicio abierto. + */ + protected function loadFilters(): void + { + $codejercicio = null; + $exerciseModel = new Ejercicio(); + foreach ($exerciseModel->all([], ['fechainicio' => 'DESC'], 0, 0) as $exe) { + if ($exe->isOpened()) { + $codejercicio = $exe->codejercicio; + break; + } + } + + $this->amount = (float)$this->request->request->get('amount', $this->amount); + $this->codejercicio = $this->request->request->get('codejercicio', $codejercicio); + $this->examine = $this->request->request->get('examine', $this->examine); + $this->excludeIrpf = (bool)$this->request->request->get('excludeirpf', $this->excludeIrpf); + $this->grouping = $this->request->request->get('grouping', $this->grouping); + $this->justificante = preg_replace('/[^0-9]/', '', $this->request->request->get('justificante', '')); + $this->declarationType = $this->request->request->get('declarationtype', ''); + if (!in_array($this->declarationType, ['C', 'S'])) { + $this->declarationType = ''; + } + $this->justificanteAnterior = preg_replace('/[^0-9]/', '', $this->request->request->get('justificanteanterior', '')); + } + /** * Encola los emails del Modelo 347 a los clientes, proveedores o ambos y muestra al usuario cuántos * se han encolado, quiénes no tienen email y si había un envío anterior pendiente. Requiere permiso @@ -305,6 +332,10 @@ protected function sendEmailsAction(): void } $result = Modelo347Email::queue($exercise, $this->amount, $data, $type); + if ($result['status'] === 'disabled') { + // la Lib ya avisa de que la notificación no existe o está desactivada + continue; + } if ($result['status'] !== 'queued') { Tools::log()->warning('347-emails-pending', ['%type%' => Tools::trans($type)]); continue; diff --git a/Controller/Modelo347Email.php b/Controller/Modelo347Email.php new file mode 100644 index 0000000..f5939f8 --- /dev/null +++ b/Controller/Modelo347Email.php @@ -0,0 +1,228 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +namespace FacturaScripts\Plugins\Modelo347\Controller; + +use FacturaScripts\Core\DataSrc\Ejercicios; +use FacturaScripts\Core\Tools; +use FacturaScripts\Dinamic\Lib\Email\NewMail; +use FacturaScripts\Dinamic\Lib\Modelo347Email as Modelo347EmailLib; +use FacturaScripts\Dinamic\Model\Ejercicio; +use FacturaScripts\Dinamic\Model\EmailNotification; + +/** + * Selección de los clientes o proveedores del modelo 347 a los que enviar la carta informativa por email. + * Recibe los filtros de Modelo347 y el tipo (customers o suppliers) en 'activetab'. El email de cada tercero + * se busca con Lib/Modelo347Email y se encola un evento por destinatario, como en el envío completo. + * + * @author Jose Antonio Cuello Principal + */ +class Modelo347Email extends Modelo347 +{ + /** @var array Destinatarios con email del tipo para la vista: code, cifnif, name, email y total. */ + public $recipients = []; + + /** @var string Tipo de destinatarios: customers o suppliers. */ + public $type = 'customers'; + + /** @var EmailNotification|null Notificación de la carta del tipo, si existe. */ + private $notification; + + /** + * Devuelve el cuerpo de la notificación en HTML, con el importe y el año sustituidos + * y el resto de etiquetas resaltadas. + */ + public function getNotificationBody(): string + { + return $this->notification ? $this->previewText((string)$this->notification->body) : ''; + } + + /** + * Devuelve el asunto de la notificación en HTML, con el importe y el año sustituidos + * y el resto de etiquetas resaltadas. + */ + public function getNotificationSubject(): string + { + return $this->notification ? $this->previewText(Tools::fixHtml((string)$this->notification->subject)) : ''; + } + + public function getPageData(): array + { + $data = parent::getPageData(); + $data['showonmenu'] = false; + $data['title'] = '347-select-recipients'; + $data['icon'] = 'fa-solid fa-envelope'; + return $data; + } + + /** @var array Destinatarios con email preparados por Lib/Modelo347Email::recipients(), con sus importes. */ + private $recipientsData = []; + + /** + * Carga los filtros y los destinatarios del tipo indicado, solo si el usuario puede modificar. + */ + protected function defaultAction(): void + { + $this->type = $this->activetab === 'suppliers' ? 'suppliers' : 'customers'; + $this->activetab = $this->type; + $this->loadFilters(); + + if (false === $this->permissions->allowUpdate) { + Tools::log()->warning('not-allowed-modify'); + return; + } + + $this->loadRecipients(); + $this->loadNotification(); + } + + /** + * Ejecuta la acción solicitada. Sustituye las acciones de Modelo347. + * + * @param string $action + */ + protected function execAction(string $action): void + { + if ($action === 'send-selected') { + $this->sendSelectedAction(); + } + } + + /** + * Carga la notificación de la carta del tipo y avisa si no existe o está desactivada. + */ + protected function loadNotification(): void + { + $name = Modelo347EmailLib::notificationName($this->type); + $notification = new EmailNotification(); + if (false === $notification->load($name)) { + Tools::log()->warning('email-notification-not-exists', ['%name%' => $name]); + return; + } + + if (false === $notification->enabled) { + Tools::log()->warning('email-notification-disabled', ['%name%' => $name]); + } + $this->notification = $notification; + } + + /** + * Calcula el modelo y prepara la lista de destinatarios con email del tipo, ordenada por nombre. + * El email se busca en la ficha y en las direcciones del tercero (Lib/Modelo347Email::findEmail()). + */ + protected function loadRecipients(): void + { + $this->calculate(); + $rows = $this->type === 'customers' ? $this->customersData : $this->suppliersData; + $this->recipientsData = Modelo347EmailLib::recipients($rows, $this->type)['recipients']; + + $this->recipients = []; + foreach ($this->recipientsData as $recipient) { + $this->recipients[] = [ + 'code' => $recipient['code'], + 'cifnif' => (string)$recipient['cifnif'], + 'name' => Tools::fixHtml((string)$recipient['name']), + 'email' => $recipient['email'], + 'total' => Tools::money($recipient['total']), + ]; + } + + usort($this->recipients, fn(array $a, array $b) => strnatcasecmp($a['name'], $b['name'])); + } + + /** + * Encola el envío de la carta a los destinatarios seleccionados y responde en JSON + * con los códigos enviados, el número de emails encolados y un token nuevo. + */ + protected function sendSelectedAction(): void + { + $this->setTemplate(false); + + $result = ['ok' => false, 'codes' => [], 'queued' => 0, 'message' => '']; + if (false === $this->permissions->allowUpdate) { + $result['message'] = Tools::trans('not-allowed-modify'); + } elseif (false === $this->validateFormToken()) { + $result['message'] = Tools::trans('invalid-request'); + } else { + $result = $this->queueSelected($this->request->request->getArray('codes')); + } + + $result['token'] = $this->multiRequestProtection->newToken(); + $this->response->json($result); + } + + /** + * Escapa el texto, sustituye el importe y el año y resalta el resto de etiquetas {campo}. + * + * @param string $text + * @return string + */ + private function previewText(string $text): string + { + $html = htmlspecialchars($text, ENT_QUOTES); + $html = str_replace( + ['{amount}', '{year}'], + [Tools::money($this->amount), (string)Ejercicios::get($this->codejercicio)->year()], + $html + ); + return preg_replace('/\{(\w+)}/', '{$1}', $html); + } + + /** + * Encola un email por cada destinatario seleccionado, con los importes recalculados en el servidor. + * Cada tercero recibe su propio email aunque comparta dirección con otro, porque sus importes son + * distintos. + * + * @param array $codes códigos de los clientes o proveedores seleccionados. + * @return array ['ok', 'codes' => códigos encolados, 'queued', 'message'] + */ + private function queueSelected(array $codes): array + { + $codes = array_map('strval', $codes); + $selected = array_values(array_filter( + $this->recipientsData, + fn(array $recipient) => in_array($recipient['code'], $codes, true) + )); + if (empty($selected)) { + return ['ok' => false, 'codes' => [], 'queued' => 0, 'message' => Tools::trans('347-no-selected')]; + } + + if (false === NewMail::create()->canSendMail()) { + return ['ok' => false, 'codes' => [], 'queued' => 0, 'message' => Tools::trans('email-not-configured')]; + } + + $exercise = new Ejercicio(); + if (false === $exercise->load($this->codejercicio)) { + return ['ok' => false, 'codes' => [], 'queued' => 0, 'message' => Tools::trans('exercise-not-found')]; + } + + if (false === Modelo347EmailLib::isNotificationEnabled($this->type)) { + $message = Tools::trans('email-notification-disabled', ['%name%' => Modelo347EmailLib::notificationName($this->type)]); + return ['ok' => false, 'codes' => [], 'queued' => 0, 'message' => $message]; + } + + $queued = Modelo347EmailLib::queueRecipients($exercise, $this->amount, $selected, $this->type); + return [ + 'ok' => $queued > 0, + 'codes' => array_column($selected, 'code'), + 'queued' => $queued, + 'message' => Tools::trans('347-emails-queued-count', ['%count%' => $queued]), + ]; + } +} diff --git a/Init.php b/Init.php index 40949c9..ebd2bcf 100644 --- a/Init.php +++ b/Init.php @@ -24,7 +24,9 @@ use FacturaScripts\Core\Lib\AjaxForms\PurchasesHeaderHTML; use FacturaScripts\Core\Lib\AjaxForms\SalesHeaderHTML; use FacturaScripts\Core\Template\InitClass; +use FacturaScripts\Core\Tools; use FacturaScripts\Core\WorkQueue; +use FacturaScripts\Dinamic\Model\EmailNotification; use FacturaScripts\Dinamic\Model\FacturaCliente; use FacturaScripts\Dinamic\Model\FacturaProveedor; @@ -65,9 +67,46 @@ public function uninstall(): void { } + /** + * Crea las columnas del plugin y las notificaciones por email. + */ public function update(): void { new FacturaCliente(); new FacturaProveedor(); + + $this->createEmailNotifications(); + } + + /** + * Crea las notificaciones de la carta del modelo 347 para clientes y proveedores. + * Si ya existen, solo reescribe el asunto o el cuerpo vacíos o iguales a su clave de traducción. + */ + private function createEmailNotifications(): void + { + foreach (['modelo347-customers', 'modelo347-suppliers'] as $name) { + $subjectKey = $name . '-subject'; + $bodyKey = $name . '-body'; + + $notification = new EmailNotification(); + if (false === $notification->load($name)) { + $notification->name = $name; + $notification->enabled = true; + } + + $changed = false; + if (empty($notification->subject) || $notification->subject === $subjectKey) { + $notification->subject = Tools::trans($subjectKey); + $changed = true; + } + if (empty($notification->body) || $notification->body === $bodyKey) { + $notification->body = Tools::trans($bodyKey); + $changed = true; + } + + if ($changed) { + $notification->save(); + } + } } } diff --git a/Lib/Modelo347Email.php b/Lib/Modelo347Email.php index 4c92b77..1b8ce31 100644 --- a/Lib/Modelo347Email.php +++ b/Lib/Modelo347Email.php @@ -21,17 +21,21 @@ use FacturaScripts\Core\Kernel; use FacturaScripts\Core\Model\WorkEvent; +use FacturaScripts\Core\Tools; use FacturaScripts\Core\Validator; use FacturaScripts\Core\Where; use FacturaScripts\Core\WorkQueue; use FacturaScripts\Dinamic\Model\Cliente; use FacturaScripts\Dinamic\Model\Contacto; use FacturaScripts\Dinamic\Model\Ejercicio; +use FacturaScripts\Dinamic\Model\EmailNotification; use FacturaScripts\Dinamic\Model\Proveedor; /** * Prepara y encola los emails del Modelo 347: busca el email de cada tercero declarado y crea un evento - * de la cola de trabajos por destinatario, que envía Worker/Modelo347EmailWorker. + * de la cola de trabajos por destinatario, que envía Worker/Modelo347EmailWorker con la notificación por + * email del tipo (modelo347-customers o modelo347-suppliers), cuyo asunto y cuerpo puede personalizar el + * usuario. * * Un evento por destinatario evita que, si el proceso se corta a mitad, se repita el envío a todos los * que ya lo habían recibido. Antes de encolar se comprueba que no quede pendiente un envío anterior del @@ -47,6 +51,12 @@ class Modelo347Email /** Evento de la cola para los emails a proveedores. */ const EVENT_SUPPLIERS = 'Modelo347.SendSuppliersEmails'; + /** Notificación por email de la carta a clientes. */ + const NOTIFICATION_CUSTOMERS = 'modelo347-customers'; + + /** Notificación por email de la carta a proveedores. */ + const NOTIFICATION_SUPPLIERS = 'modelo347-suppliers'; + /** Tipo de tercero: clientes. */ const TYPE_CUSTOMERS = 'customers'; @@ -112,19 +122,60 @@ public static function hasPending(string $codejercicio, string $type): bool } /** - * Encola un email por destinatario para un tipo de tercero. No encola nada si ya hay un envío - * pendiente del mismo ejercicio y tipo, o si otro proceso está encolando a la vez. + * Indica si la notificación por email de un tipo de tercero existe y está activada. Si no, deja un + * aviso en el log. + * + * @param string $type 'customers' o 'suppliers'. + * @return bool + */ + public static function isNotificationEnabled(string $type): bool + { + $name = self::notificationName($type); + $notification = new EmailNotification(); + if (false === $notification->load($name)) { + Tools::log()->warning('email-notification-not-exists', ['%name%' => $name]); + return false; + } + + if (false === (bool)$notification->enabled) { + Tools::log()->warning('email-notification-disabled', ['%name%' => $name]); + return false; + } + + return true; + } + + /** + * Devuelve el nombre de la notificación por email que corresponde a un tipo de tercero. + * + * @param string $type 'customers' o 'suppliers'. + * @return string + */ + public static function notificationName(string $type): string + { + return $type === self::TYPE_SUPPLIERS ? self::NOTIFICATION_SUPPLIERS : self::NOTIFICATION_CUSTOMERS; + } + + /** + * Encola un email por destinatario para un tipo de tercero. No encola nada si la notificación del + * tipo no existe o está desactivada, si ya hay un envío pendiente del mismo ejercicio y tipo, o si + * otro proceso está encolando a la vez. * * @param Ejercicio $exercise ejercicio declarado. * @param float $amount importe mínimo del modelo, que se menciona en el texto del email. * @param array $data filas del modelo (customersData o suppliersData). * @param string $type 'customers' o 'suppliers'. - * @return array ['status' => 'queued'|'pending'|'locked', 'queued' => int, 'noEmail' => filas sin email] + * @return array ['status' => 'queued'|'pending'|'locked'|'disabled', 'queued' => int, 'noEmail' => filas sin email] */ public static function queue(Ejercicio $exercise, float $amount, array $data, string $type): array { $result = ['status' => 'queued', 'queued' => 0, 'noEmail' => []]; + if (false === self::isNotificationEnabled($type)) { + $result['status'] = 'disabled'; + return $result; + } + // bloqueamos para que dos peticiones simultáneas no encolen el mismo envío $lockName = 'modelo347-emails-' . $exercise->codejercicio . '-' . $type; if (false === Kernel::lock($lockName)) { @@ -140,20 +191,37 @@ public static function queue(Ejercicio $exercise, float $amount, array $data, st $recipients = self::recipients($data, $type); $result['noEmail'] = $recipients['noEmail']; + $result['queued'] = self::queueRecipients($exercise, $amount, $recipients['recipients'], $type); + Kernel::unlock($lockName); + return $result; + } + + /** + * Encola un email por cada destinatario ya preparado con recipients(), sin más comprobaciones. + * Lo usan queue() y el envío selectivo de Controller/Modelo347Email. + * + * @param Ejercicio $exercise ejercicio declarado. + * @param float $amount importe mínimo del modelo, que se menciona en el texto del email. + * @param array $recipients destinatarios con email (clave 'recipients' de recipients()). + * @param string $type 'customers' o 'suppliers'. + * @return int número de emails encolados. + */ + public static function queueRecipients(Ejercicio $exercise, float $amount, array $recipients, string $type): int + { $params = [ 'amount' => $amount, 'idempresa' => $exercise->idempresa, 'year' => self::year($exercise), ]; - foreach ($recipients['recipients'] as $recipient) { + + $queued = 0; + foreach ($recipients as $recipient) { if (WorkQueue::send(self::eventName($type), $exercise->codejercicio, array_merge($params, $recipient))) { - $result['queued']++; + $queued++; } } - - Kernel::unlock($lockName); - return $result; + return $queued; } /** diff --git a/README.md b/README.md index d06f09e..1f6df3f 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ El plugin sigue la misma estructura que el resto de modelos fiscales: `Lib/Model ## Envío de emails El botón «Enviar Email» de la pantalla (requiere permiso de modificación y el email configurado) encola un email por cliente o proveedor con sus importes trimestrales; `Lib/Modelo347Email` prepara los destinatarios y `Worker/Modelo347EmailWorker` los envía en segundo plano. El email se toma de la ficha y, si no tiene, de la dirección predeterminada o de cualquier otra dirección del tercero. Dos terceros con el mismo email reciben cada uno el suyo. El año es el de la fecha de inicio del ejercicio, el remitente es la empresa del ejercicio y no se puede volver a enviar mientras quede un envío pendiente del mismo ejercicio y tipo. +El asunto y el texto del email salen de las notificaciones por email `modelo347-customers` y `modelo347-suppliers`, que el plugin crea al instalarse y que el usuario puede personalizar con las etiquetas `{name}`, `{cifnif}`, `{email}`, `{year}`, `{amount}`, `{t1}`..`{t4}`, `{total}` y `{deadline}`. Si la notificación no existe o está desactivada no se encola nada. + +El botón «Seleccionar» abre `Controller/Modelo347Email`, donde se eligen en dos columnas con buscador los clientes o proveedores concretos a los que enviar el email, con una vista previa de la notificación. + ## Issues / Feedback https://facturascripts.com/contacto diff --git a/Test/main/Modelo347EmailTest.php b/Test/main/Modelo347EmailTest.php index e5ca6bb..cf7370a 100644 --- a/Test/main/Modelo347EmailTest.php +++ b/Test/main/Modelo347EmailTest.php @@ -26,6 +26,7 @@ use FacturaScripts\Dinamic\Lib\Modelo347Email; use FacturaScripts\Dinamic\Model\Cliente; use FacturaScripts\Dinamic\Model\Ejercicio; +use FacturaScripts\Dinamic\Model\EmailNotification; use FacturaScripts\Dinamic\Model\Proveedor; use FacturaScripts\Test\Traits\DefaultSettingsTrait; use FacturaScripts\Test\Traits\LogErrorsTrait; @@ -124,6 +125,44 @@ public function testQueue(): void $this->assertTrue($supplier2->delete()); } + /** + * Comprueba que no se encola nada si la notificación por email del tipo está desactivada y que, + * al volver a activarla, se encola con normalidad. + */ + public function testQueueNotificationDisabled(): void + { + $this->deleteTestEvents(); + + // la notificación la crea Init::update() al instalar el plugin + $notification = new EmailNotification(); + $this->assertTrue($notification->load(Modelo347Email::NOTIFICATION_CUSTOMERS), 'notification-not-found'); + $notification->enabled = false; + $this->assertTrue($notification->save(), 'notification-cant-save'); + + $customer = $this->getCustomer('cliente@example.com'); + $data = [$customer->codcliente => $this->getRow('cliente', $customer->nombre, 4000)]; + + $exercise = new Ejercicio(); + $exercise->codejercicio = self::TEST_EXERCISE; + $exercise->fechainicio = '01-01-2025'; + $exercise->idempresa = (int)Tools::settings('default', 'idempresa'); + + $result = Modelo347Email::queue($exercise, 3005.06, $data, Modelo347Email::TYPE_CUSTOMERS); + $this->assertEquals('disabled', $result['status']); + $this->assertEquals(0, $result['queued']); + $this->assertCount(0, WorkEvent::all([Where::eq('value', self::TEST_EXERCISE)])); + + // reactivamos la notificación: ahora sí se encola + $notification->enabled = true; + $this->assertTrue($notification->save(), 'notification-cant-save'); + $result2 = Modelo347Email::queue($exercise, 3005.06, $data, Modelo347Email::TYPE_CUSTOMERS); + $this->assertEquals('queued', $result2['status']); + $this->assertEquals(1, $result2['queued']); + + $this->deleteTestEvents(); + $this->assertTrue($customer->delete()); + } + /** * Comprueba que dos terceros con el mismo email reciben cada uno su email y que los que no tienen * email se devuelven aparte. diff --git a/Translation/es_ES.json b/Translation/es_ES.json index 94fdbe8..145a249 100644 --- a/Translation/es_ES.json +++ b/Translation/es_ES.json @@ -25,5 +25,19 @@ "exclude-347": "Excluir del 347", "exclude-irpf": "Excluir IRPF", "model-347": "Modelo 347", - "model-347-p": "El Modelo 347 es una declaración anual informativa de operaciones con terceras personas. Los empresarios y profesionales están obligados a la presentación del Modelo 347 siempre que hayan realizado operaciones con terceros por importe superior a 3.005,06 € durante el año natural (se puede cambiar la cantidad), computando de forma separada las entregas y las adquisiciones de bienes y servicios." -} \ No newline at end of file + "model-347-p": "El Modelo 347 es una declaración anual informativa de operaciones con terceras personas. Los empresarios y profesionales están obligados a la presentación del Modelo 347 siempre que hayan realizado operaciones con terceros por importe superior a 3.005,06 € durante el año natural (se puede cambiar la cantidad), computando de forma separada las entregas y las adquisiciones de bienes y servicios.", + "modelo347-customers-body": "DECLARACIÓN ANUAL DE OPERACIONES CON TERCERAS PERSONAS.\n\nMuy Sres. Nuestros:\nEl próximo mes de febrero presentaremos relación de todos nuestros clientes cuya facturación haya superado la cantidad de {amount} durante el año {year}.\nHallándose Vds. incluidos en la relación que hacemos referencia, les informamos que el importe a declarar por este concepto es:\n\nDNI/NIF: {cifnif}\nNOMBRE/RAZÓN SOCIAL: {name}\n\nIMPORTE TRIMESTRAL OPERACIONES\nPrimer trimestre: {t1}\nSegundo trimestre: {t2}\nTercer trimestre: {t3}\nCuarto trimestre: {t4}\nTotal: {total}\n\nDe no recibir disconformidad por su parte antes del 20 de febrero, consideraremos que nuestra cifra es correcta.\nSin otro particular, les saludamos cordialmente.", + "modelo347-customers-subject": "Modelo 347 - Ejercicio {year}", + "modelo347-suppliers-body": "DECLARACIÓN ANUAL DE OPERACIONES CON TERCERAS PERSONAS.\n\nMuy Sres. Nuestros:\nEl próximo mes de febrero presentaremos relación de todos nuestros proveedores cuyas compras realizadas por nuestra parte hayan superado la cantidad de {amount} durante el año {year}.\nHallándose Vds. incluidos en la relación que hacemos referencia, les informamos que el importe a declarar por este concepto es:\n\nDNI/NIF: {cifnif}\nNOMBRE/RAZÓN SOCIAL: {name}\n\nIMPORTE TRIMESTRAL OPERACIONES\nPrimer trimestre: {t1}\nSegundo trimestre: {t2}\nTercer trimestre: {t3}\nCuarto trimestre: {t4}\nTotal: {total}\n\nDe no recibir disconformidad por su parte antes del 20 de febrero, consideraremos que nuestra cifra es correcta.\nSin otro particular, les saludamos cordialmente.", + "modelo347-suppliers-subject": "Modelo 347 - Ejercicio {year}", + "347-add-all": "Añadir todos los visibles", + "347-emails-queued-count": "Se han encolado %count% emails para su envío.", + "347-included": "Incluidos", + "347-letter-preview": "Vista previa de la carta", + "347-no-selected": "No hay destinatarios seleccionados con email.", + "347-remove-all": "Quitar todos", + "347-return": "Volver", + "347-search-help": "Separe varios términos con espacios. Use % para indicar comienza por (texto%) o termina por (%texto).", + "347-select-recipients": "Destinatarios del modelo 347", + "347-selected": "Seleccionados" +} diff --git a/View/Modelo347.html.twig b/View/Modelo347.html.twig index 10bca61..53fc37a 100644 --- a/View/Modelo347.html.twig +++ b/View/Modelo347.html.twig @@ -154,6 +154,9 @@ {# Buttons #}
{% if fsc.permissions.allowUpdate %} + +
+ + +{% endblock %} + +{% block body %} + {% if fsc.permissions.allowUpdate %} +
+ + {{ _self.notificationCard(fsc) }} + +
+
+ {{ _self.listCard('m347-left', trans('347-included'), true) }} +
+
+ + + + +
+
+ {{ _self.listCard('m347-right', trans('347-selected'), false) }} +
+ +
+
+
+
+ {% endif %} +{% endblock %} + +{% macro listCard(id, title, withSearch) %} +
+
+ {{ title }} + 0 +
+ {% if withSearch %} +
+
+ + + +
+ {{ trans('347-search-help') }} +
+ {% endif %} +
+
+
+
+{% endmacro %} + +{% macro notificationCard(fsc) %} +
+ +
+

{{ trans('subject') }}: {{ fsc.getNotificationSubject() | raw }}

+
{{ fsc.getNotificationBody() | raw }}
+
+
+{% endmacro %} diff --git a/Worker/Modelo347EmailWorker.php b/Worker/Modelo347EmailWorker.php index aa9f6aa..35c99e4 100644 --- a/Worker/Modelo347EmailWorker.php +++ b/Worker/Modelo347EmailWorker.php @@ -23,18 +23,18 @@ use FacturaScripts\Core\Template\WorkerClass; use FacturaScripts\Core\Tools; use FacturaScripts\Core\Validator; +use FacturaScripts\Dinamic\Lib\Email\MailNotifier; use FacturaScripts\Dinamic\Lib\Email\NewMail; -use FacturaScripts\Dinamic\Lib\Email\TableBlock; -use FacturaScripts\Dinamic\Lib\Email\TextBlock; -use FacturaScripts\Dinamic\Lib\Email\TitleBlock; use FacturaScripts\Dinamic\Lib\Modelo347Email; use FacturaScripts\Dinamic\Model\Ejercicio; +use FacturaScripts\Dinamic\Model\EmailNotification; use FacturaScripts\Dinamic\Model\Empresa; /** * Envía el email del Modelo 347 a un cliente o proveedor con sus importes trimestrales. Atiende los * eventos Modelo347.SendCustomersEmails y Modelo347.SendSuppliersEmails, que encola Lib/Modelo347Email - * con un destinatario por evento. El remitente es la empresa del ejercicio. + * con un destinatario por evento. El asunto y el cuerpo salen de las notificaciones por email + * modelo347-customers y modelo347-suppliers. El remitente es la empresa del ejercicio. * * También procesa los eventos de versiones anteriores, que llevaban todos los destinatarios en el * parámetro 'data'. @@ -70,7 +70,8 @@ public function run(WorkEvent $event): bool } /** - * Envía el email del Modelo 347 a un destinatario. + * Envía el email del Modelo 347 a un destinatario con la notificación por email del tipo. Los + * importes se formatean como moneda antes de sustituir las etiquetas {amount}, {t1}..{t4} y {total}. * * @param array $params email, name, cifnif, t1-t4, total, amount, year e idempresa. * @param string $type 'customers' o 'suppliers'. @@ -87,40 +88,36 @@ protected function sendEmail(array $params, string $type): bool return false; } - $i18n = Tools::lang(); - $year = (string)($params['year'] ?? ''); - $amount = Tools::money((float)($params['amount'] ?? 0)); - - $contactInfo = $i18n->trans('347-email-cifnif-line', ['%cifnif%' => $params['cifnif'] ?? '']) - . "\n" - . $i18n->trans('347-email-name-line', ['%name%' => $params['name'] ?? '']); + // la notificación guarda el asunto y el cuerpo que puede personalizar el usuario + $notification = new EmailNotification(); + if (false === $notification->load(Modelo347Email::notificationName($type))) { + Tools::log()->warning('email-notification-not-exists', ['%name%' => Modelo347Email::notificationName($type)]); + return false; + } + if (false === (bool)$notification->enabled) { + Tools::log()->warning('email-notification-disabled', ['%name%' => Modelo347Email::notificationName($type)]); + return false; + } - $header = [$i18n->trans('concept'), $i18n->trans('amount')]; - $rows = [ - [$i18n->trans('first-trimester'), Tools::money((float)($params['t1'] ?? 0))], - [$i18n->trans('second-trimester'), Tools::money((float)($params['t2'] ?? 0))], - [$i18n->trans('third-trimester'), Tools::money((float)($params['t3'] ?? 0))], - [$i18n->trans('fourth-trimester'), Tools::money((float)($params['t4'] ?? 0))], - [$i18n->trans('total'), Tools::money((float)($params['total'] ?? 0))], + $year = (string)($params['year'] ?? ''); + $values = [ + 'amount' => Tools::money((float)($params['amount'] ?? 0)), + 'cifnif' => $params['cifnif'] ?? '', + 'email' => $email, + 'name' => $params['name'] ?? '', + 't1' => Tools::money((float)($params['t1'] ?? 0)), + 't2' => Tools::money((float)($params['t2'] ?? 0)), + 't3' => Tools::money((float)($params['t3'] ?? 0)), + 't4' => Tools::money((float)($params['t4'] ?? 0)), + 'total' => Tools::money((float)($params['total'] ?? 0)), + 'year' => $year, + // plazo de disconformidad: 20 de febrero del año siguiente al declarado + 'deadline' => is_numeric($year) ? Tools::date(((int)$year + 1) . '-02-20') : '', ]; - // el texto de introducción cambia según sea cliente o proveedor - $introKey = $type === Modelo347Email::TYPE_SUPPLIERS ? '347-email-intro-suppliers' : '347-email-intro'; - - // plazo de disconformidad: 20 de febrero del año siguiente al declarado - $deadline = is_numeric($year) ? Tools::date(((int)$year + 1) . '-02-20') : ''; - - $mail = NewMail::create() - ->to($email, $params['name'] ?? '') - ->subject($i18n->trans('347-email-subject', ['%year%' => $year])) - ->addMainBlock(new TitleBlock($i18n->trans('347-email-title'), 'h3')) - ->addMainBlock(new TextBlock($i18n->trans('347-email-greeting'))) - ->addMainBlock(new TextBlock($i18n->trans($introKey, ['%year%' => $year, '%amount%' => $amount]))) - ->addMainBlock(new TextBlock($i18n->trans('347-email-included'))) - ->addMainBlock(new TextBlock($contactInfo)) - ->addMainBlock(new TextBlock($i18n->trans('347-email-amounts-title'))) - ->addMainBlock(new TableBlock($header, $rows)) - ->addMainBlock(new TextBlock($i18n->trans('347-email-footer', ['%date%' => $deadline]))); + $mail = NewMail::create()->to($email, $values['name']); + $mail->title = MailNotifier::getText((string)$notification->subject, $values); + $mail->text = MailNotifier::getText((string)$notification->body, $values); // el remitente es la empresa del ejercicio, no la predeterminada $company = new Empresa(); @@ -134,7 +131,7 @@ protected function sendEmail(array $params, string $type): bool } Tools::log()->warning('347-email-not-sent', [ - '%name%' => $params['name'] ?? '', + '%name%' => $values['name'], '%email%' => $email, ]); return false;