feat(i18n): add bilingual support (Català / Castellano)
Run Tests on Branches / Detect Changes (push) Successful in 11s
Run Tests on Branches / Backend Tests (push) Has been skipped
Run Tests on Branches / Frontend Tests (push) Successful in 1m44s
Run Tests on Branches / Frontend Mobile Tests (push) Has been skipped
Run Tests on Branches / Parapharmacy API Tests (push) Has been skipped
Run Tests on Branches / Detect Changes (push) Successful in 11s
Run Tests on Branches / Backend Tests (push) Has been skipped
Run Tests on Branches / Frontend Tests (push) Successful in 1m44s
Run Tests on Branches / Frontend Mobile Tests (push) Has been skipped
Run Tests on Branches / Parapharmacy API Tests (push) Has been skipped
Add lightweight i18n system using React Context + useTranslation hook.
No external dependencies. Language persisted in localStorage('ff-lang').
New files:
- src/i18n/locales/ca.js (~410 translation keys)
- src/i18n/locales/es.js (~410 translation keys)
- src/i18n/LanguageContext.jsx (Provider + t() function)
- src/i18n/useTranslation.js (hook)
- src/i18n/index.js (barrel export)
Modified 22 files:
- main.jsx: wrap App with LanguageProvider
- App.test.jsx: add LanguageProvider wrapper for tests
- 13 user components: BottomNav, HomeView, LoginModal, SearchView,
ProfileView, AlertsView, ScannerView, PharmacyList, MedicineResults,
ProductResults, SavedNotifications, ErrorBoundary, SearchBar
- 6 admin components: AdminView, LoginForm, PharmacyManagement,
MedicineManagement, PharmacyMedicineLink, PharmacyProductLink
ProfileView includes language selector (globe icon + modal CA/ES)
placed next to the Theme selector.
No routes changed. No API calls affected. No navigation changes.
This commit is contained in:
@@ -1,13 +1,15 @@
|
||||
import { IconHome, IconSearch, IconScan, IconBell, IconUser } from './icons';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './BottomNav.css';
|
||||
|
||||
function BottomNav({ activeTab, onChange, isLoggedIn, badgeCount }) {
|
||||
const { t } = useTranslation();
|
||||
const tabs = [
|
||||
{ id: 'home', label: 'Inicio', Icon: IconHome },
|
||||
{ id: 'search', label: 'Buscar', Icon: IconSearch },
|
||||
{ id: 'scan', label: 'Escanear', Icon: IconScan, elevated: true },
|
||||
{ id: 'alerts', label: 'Avisos', Icon: IconBell, badge: badgeCount > 0, badgeCount },
|
||||
{ id: 'profile', label: 'Usuario', Icon: IconUser },
|
||||
{ id: 'home', label: t('nav.home'), Icon: IconHome },
|
||||
{ id: 'search', label: t('nav.search'), Icon: IconSearch },
|
||||
{ id: 'scan', label: t('nav.scan'), Icon: IconScan, elevated: true },
|
||||
{ id: 'alerts', label: t('nav.alerts'), Icon: IconBell, badge: badgeCount > 0, badgeCount },
|
||||
{ id: 'profile', label: t('nav.profile'), Icon: IconUser },
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import React from 'react';
|
||||
import { LanguageContext } from '../i18n/LanguageContext';
|
||||
|
||||
export default class ErrorBoundary extends React.Component {
|
||||
static contextType = LanguageContext;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
@@ -25,6 +28,7 @@ export default class ErrorBoundary extends React.Component {
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
const t = this.context?.t || ((k) => k);
|
||||
return (
|
||||
<div style={{
|
||||
padding: '2rem',
|
||||
@@ -32,8 +36,8 @@ export default class ErrorBoundary extends React.Component {
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
color: '#333',
|
||||
}}>
|
||||
<h2>Algo salió mal</h2>
|
||||
<p style={{ color: '#666' }}>Ha ocurrido un error inesperado. Por favor, recarga la página.</p>
|
||||
<h2>{t('error.title')}</h2>
|
||||
<p style={{ color: '#666' }}>{t('error.description')}</p>
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
style={{
|
||||
@@ -47,7 +51,7 @@ export default class ErrorBoundary extends React.Component {
|
||||
fontSize: '1rem',
|
||||
}}
|
||||
>
|
||||
Recargar
|
||||
{t('error.reload')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './LoginModal.css';
|
||||
|
||||
function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
const { t } = useTranslation();
|
||||
const [mode, setMode] = useState(initialMode === 'register' ? 'register' : 'login');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
@@ -25,7 +27,7 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
const u = username.trim();
|
||||
if (!u || !password) return;
|
||||
if (mode === 'register' && password.length < 8) {
|
||||
setError('La contraseña debe tener al menos 8 caracteres');
|
||||
setError(t('login.passwordError'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@@ -40,12 +42,12 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(data.error || (mode === 'register' ? 'No se pudo crear la cuenta' : 'Inicio de sesión fallido'));
|
||||
setError(data.error || (mode === 'register' ? t('login.registerError') : t('login.loginError')));
|
||||
} else {
|
||||
onLogin(data.user);
|
||||
}
|
||||
} catch {
|
||||
setError('Error de red — inténtalo de nuevo');
|
||||
setError(t('login.networkError'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -71,7 +73,7 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
onClick={() => setMode('login')}
|
||||
disabled={loading}
|
||||
>
|
||||
Iniciar sesión
|
||||
{t('login.login')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -81,20 +83,20 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
onClick={() => setMode('register')}
|
||||
disabled={loading}
|
||||
>
|
||||
Crear cuenta
|
||||
{t('login.register')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<h2 id="modal-title">{isRegister ? 'Crea tu cuenta' : 'Bienvenido de nuevo'}</h2>
|
||||
<h2 id="modal-title">{isRegister ? t('login.createAccount') : t('login.welcomeBack')}</h2>
|
||||
<p className="modal-sub">
|
||||
{isRegister
|
||||
? 'Guarda tu dirección y recibe notificaciones cuando lleguen medicamentos.'
|
||||
: 'Inicia sesión para gestionar tu perfil y notificaciones.'}
|
||||
? t('login.registerDescription')
|
||||
: t('login.loginDescription')}
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<div className="modal-field">
|
||||
<label htmlFor="modal-username">Usuario</label>
|
||||
<label htmlFor="modal-username">{t('login.username')}</label>
|
||||
<input
|
||||
id="modal-username"
|
||||
type="text"
|
||||
@@ -107,11 +109,11 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
maxLength={isRegister ? 32 : undefined}
|
||||
/>
|
||||
{isRegister && (
|
||||
<p className="modal-hint">3–32 caracteres: letras, dígitos o guión bajo.</p>
|
||||
<p className="modal-hint">{t('login.usernameHint')}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-field">
|
||||
<label htmlFor="modal-password">Contraseña</label>
|
||||
<label htmlFor="modal-password">{t('login.password')}</label>
|
||||
<input
|
||||
id="modal-password"
|
||||
type="password"
|
||||
@@ -122,7 +124,7 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
minLength={isRegister ? 8 : undefined}
|
||||
/>
|
||||
{isRegister && (
|
||||
<p className="modal-hint">Al menos 8 caracteres.</p>
|
||||
<p className="modal-hint">{t('login.passwordHint')}</p>
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="modal-error">{error}</p>}
|
||||
@@ -133,7 +135,7 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancelar
|
||||
{t('login.cancel')}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
@@ -141,8 +143,8 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
|
||||
disabled={loading || !username.trim() || !password}
|
||||
>
|
||||
{loading
|
||||
? (isRegister ? 'Creando…' : 'Iniciando sesión…')
|
||||
: (isRegister ? 'Crear cuenta' : 'Iniciar sesión')}
|
||||
? (isRegister ? t('login.creating') : t('login.loggingIn'))
|
||||
: (isRegister ? t('login.createAccountBtn') : t('login.loginBtn'))}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './MedicineResults.css';
|
||||
import {
|
||||
pushSupported,
|
||||
@@ -8,10 +9,11 @@ import {
|
||||
} from '../utils/notifications.js';
|
||||
|
||||
function MedicineResults({ medicines, onSelect, query, currentUser, onLoginRequest }) {
|
||||
const { t } = useTranslation();
|
||||
if (medicines.length === 0 && query.length >= 2) {
|
||||
return (
|
||||
<div className="no-results">
|
||||
<p>No se encontraron medicamentos para "{query}"</p>
|
||||
<p>{t('medicine.noResults')} "{query}"</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -32,6 +34,7 @@ function MedicineResults({ medicines, onSelect, query, currentUser, onLoginReque
|
||||
}
|
||||
|
||||
function MedicineCard({ medicine, onSelect, currentUser, onLoginRequest }) {
|
||||
const { t } = useTranslation();
|
||||
const nregistro = medicine.nregistro || medicine.id;
|
||||
const [subscribed, setSubscribed] = useState(() => isSubscribedLocally(nregistro));
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -49,7 +52,7 @@ function MedicineCard({ medicine, onSelect, currentUser, onLoginRequest }) {
|
||||
return;
|
||||
}
|
||||
if (!supported) {
|
||||
setError('Las notificaciones requieren iOS 16.4+ y este sitio instalado como app (Compartir → Añadir a Pantalla de Inicio).');
|
||||
setError(t('pharmacy.notificationsRequired'));
|
||||
return;
|
||||
}
|
||||
if (busy) return;
|
||||
@@ -65,7 +68,7 @@ function MedicineCard({ medicine, onSelect, currentUser, onLoginRequest }) {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[notify] toggle failed:', err);
|
||||
setError(err.message || 'No se pudo actualizar la suscripción');
|
||||
setError(err.message || t('medicine.subscriptionError'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -83,29 +86,29 @@ function MedicineCard({ medicine, onSelect, currentUser, onLoginRequest }) {
|
||||
aria-pressed={subscribed && !!currentUser}
|
||||
aria-label={
|
||||
!currentUser
|
||||
? 'Inicia sesión para activar notificaciones'
|
||||
? t('medicine.loginForNotifications')
|
||||
: subscribed
|
||||
? 'Desactivar notificaciones para este medicamento'
|
||||
: 'Notificarme cuando esté disponible'
|
||||
? t('medicine.disableNotifications')
|
||||
: t('medicine.enableNotifications')
|
||||
}
|
||||
title={
|
||||
!currentUser
|
||||
? 'Inicia sesión para activar notificaciones'
|
||||
? t('medicine.loginForNotifications')
|
||||
: subscribed
|
||||
? 'Notificaciones activadas — clic para desactivar'
|
||||
: 'Notificarme cuando este medicamento esté en una farmacia'
|
||||
? t('medicine.notificationsActivated')
|
||||
: t('medicine.notifyWhenAvailable')
|
||||
}
|
||||
>
|
||||
{subscribed && currentUser ? '🔔' : '🔕'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="medicine-card-body">
|
||||
<p><strong>Principio Activo:</strong> {medicine.active_ingredient}</p>
|
||||
<p><strong>Dosis:</strong> {medicine.dosage} • <strong>Forma:</strong> {medicine.form}</p>
|
||||
<p><strong>{t('medicine.principioActivo')}</strong> {medicine.active_ingredient}</p>
|
||||
<p><strong>{t('medicine.dosis')}</strong> {medicine.dosage} • <strong>{t('medicine.forma')}</strong> {medicine.form}</p>
|
||||
{error && <p className="notify-error" onClick={e => e.stopPropagation()}>{error}</p>}
|
||||
</div>
|
||||
<div className="medicine-card-footer">
|
||||
<span className="view-pharmacies">Ver farmacias →</span>
|
||||
<span className="view-pharmacies">{t('medicine.viewPharmacies')}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './PharmacyList.css';
|
||||
import { haversineKm, formatDistance } from '../utils/geo';
|
||||
import { getOpenStatus } from '../utils/hours';
|
||||
@@ -10,10 +11,11 @@ import {
|
||||
} from '../utils/notifications.js';
|
||||
|
||||
function PharmacyList({ pharmacies, loading, userPosition, medicine, currentUser, onLoginRequest }) {
|
||||
const { t } = useTranslation();
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="loading-pharmacies">
|
||||
<p>Cargando farmacias...</p>
|
||||
<p>{t('pharmacy.loading')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,7 +23,7 @@ function PharmacyList({ pharmacies, loading, userPosition, medicine, currentUser
|
||||
if (pharmacies.length === 0) {
|
||||
return (
|
||||
<div className="no-pharmacies">
|
||||
<p>No se encontraron farmacias con este medicamento</p>
|
||||
<p>{t('pharmacy.notFound')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -29,7 +31,7 @@ function PharmacyList({ pharmacies, loading, userPosition, medicine, currentUser
|
||||
return (
|
||||
<div className="pharmacy-list">
|
||||
<h3 className="pharmacy-list-title">
|
||||
Disponible en {pharmacies.length} {pharmacies.length === 1 ? 'farmacia' : 'farmacias'}
|
||||
{t('pharmacy.availableAt')} {pharmacies.length} {pharmacies.length === 1 ? t('pharmacy.pharmacy') : t('pharmacy.pharmacies')}
|
||||
</h3>
|
||||
<div className="pharmacy-grid">
|
||||
{pharmacies.map((pharmacy) => {
|
||||
@@ -55,6 +57,7 @@ function PharmacyList({ pharmacies, loading, userPosition, medicine, currentUser
|
||||
}
|
||||
|
||||
function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequest, userPosition }) {
|
||||
const { t } = useTranslation();
|
||||
const nregistro = medicine?.nregistro || medicine?.id;
|
||||
const supported = pushSupported();
|
||||
const outOfStock = pharmacy.stock !== undefined && pharmacy.stock <= 0;
|
||||
@@ -77,7 +80,7 @@ function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequ
|
||||
return;
|
||||
}
|
||||
if (!supported) {
|
||||
setError('Las notificaciones requieren iOS 16.4+ y este sitio instalado como app (Compartir → Añadir a Pantalla de Inicio).');
|
||||
setError(t('pharmacy.notificationsRequired'));
|
||||
return;
|
||||
}
|
||||
if (busy) return;
|
||||
@@ -93,7 +96,7 @@ function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequ
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[notify] pharmacy toggle failed:', err);
|
||||
setError(err.message || 'No se pudo actualizar la suscripción');
|
||||
setError(err.message || t('medicine.subscriptionError'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -118,17 +121,17 @@ function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequ
|
||||
aria-pressed={subscribed && !!currentUser}
|
||||
aria-label={
|
||||
!currentUser
|
||||
? 'Inicia sesión para activar notificaciones'
|
||||
? t('pharmacy.loginForNotifications')
|
||||
: subscribed
|
||||
? 'Desactivar notificaciones para esta farmacia'
|
||||
: 'Notificarme cuando llegue a esta farmacia'
|
||||
? t('pharmacy.disableNotificationsPharmacy')
|
||||
: t('pharmacy.notifyWhenArrives')
|
||||
}
|
||||
title={
|
||||
!currentUser
|
||||
? 'Inicia sesión para activar notificaciones'
|
||||
? t('pharmacy.loginForNotifications')
|
||||
: subscribed
|
||||
? 'Notificaciones activadas para esta farmacia — clic para desactivar'
|
||||
: 'Notificarme cuando llegue a esta farmacia'
|
||||
? t('pharmacy.notificationsActivatedPharmacy')
|
||||
: t('pharmacy.notifyWhenArrives')
|
||||
}
|
||||
>
|
||||
{subscribed && currentUser ? '🔔' : '🔕'}
|
||||
@@ -161,7 +164,7 @@ function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequ
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<polygon points="3 11 22 2 13 21 11 13 3 11" />
|
||||
</svg>
|
||||
Cómo llegar
|
||||
{t('pharmacy.howToGet')}
|
||||
</a>
|
||||
)}
|
||||
<div className="pharmacy-pricing">
|
||||
@@ -170,7 +173,7 @@ function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequ
|
||||
)}
|
||||
{pharmacy.stock !== undefined && (
|
||||
<span className={`stock ${pharmacy.stock > 20 ? 'in-stock' : pharmacy.stock > 0 ? 'low-stock' : 'out-of-stock'}`}>
|
||||
{pharmacy.stock > 20 ? '✓ En Stock' : pharmacy.stock > 0 ? `⚠ Stock Bajo (${pharmacy.stock})` : '✗ Sin Stock'}
|
||||
{pharmacy.stock > 20 ? t('pharmacy.inStock') : pharmacy.stock > 0 ? `${t('pharmacy.lowStock')} (${pharmacy.stock})` : t('pharmacy.outOfStock')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './ProductResults.css';
|
||||
|
||||
const categoryLabels = {
|
||||
otc: 'Sin Receta',
|
||||
parapharmacy: 'Parafarmacia',
|
||||
dermocosmética: 'Dermocosmética',
|
||||
'Fórmulas lácteas': 'Fórmulas lácteas',
|
||||
vitaminas: 'Vitaminas',
|
||||
analgésicos: 'Analgésicos'
|
||||
otc: 'product.sinReceta',
|
||||
parapharmacy: 'product.parapharmacy',
|
||||
dermocosmética: 'product.dermocosmetica',
|
||||
'Fórmulas lácteas': 'product.formulasLacteas',
|
||||
vitaminas: 'product.vitamins',
|
||||
analgésicos: 'product.analgesics'
|
||||
};
|
||||
|
||||
const sourceColors = {
|
||||
@@ -27,10 +28,11 @@ const sourceLabels = {
|
||||
};
|
||||
|
||||
function ProductResults({ products, onSelect }) {
|
||||
const { t } = useTranslation();
|
||||
if (!products || products.length === 0) {
|
||||
return (
|
||||
<div className="no-results">
|
||||
<p>No se encontraron productos</p>
|
||||
<p>{t('product.noResults')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -49,6 +51,7 @@ function ProductResults({ products, onSelect }) {
|
||||
}
|
||||
|
||||
function ProductCard({ product, onSelect }) {
|
||||
const { t } = useTranslation();
|
||||
const nutriScore = product.nutriscore;
|
||||
const nutriScoreColors = {
|
||||
a: '#16a34a',
|
||||
@@ -83,7 +86,7 @@ function ProductCard({ product, onSelect }) {
|
||||
{sourceLabels[product.source]}
|
||||
</span>
|
||||
<span className="category-badge">
|
||||
{categoryLabels[product.category] || product.category}
|
||||
{categoryLabels[product.category] ? t(categoryLabels[product.category]) : product.category}
|
||||
</span>
|
||||
{product.source === 'openfoodfacts' && nutriScore && (
|
||||
<span
|
||||
@@ -101,21 +104,21 @@ function ProductCard({ product, onSelect }) {
|
||||
|
||||
<div className="product-card-body">
|
||||
{product.brand && (
|
||||
<p><strong>Marca:</strong> {product.brand}</p>
|
||||
<p><strong>{t('product.brand')}</strong> {product.brand}</p>
|
||||
)}
|
||||
{product.price != null && (
|
||||
<p className="product-price"><strong>Precio:</strong> {product.price} €</p>
|
||||
<p className="product-price"><strong>{t('product.price')}</strong> {product.price} €</p>
|
||||
)}
|
||||
{product.source === 'cima' && product.active_ingredient && (
|
||||
<p><strong>Principio Activo:</strong> {product.active_ingredient}</p>
|
||||
<p><strong>{t('product.activeIngredient')}</strong> {product.active_ingredient}</p>
|
||||
)}
|
||||
{product.source === 'cima' && product.dosage && (
|
||||
<p><strong>Dosis:</strong> {product.dosage}</p>
|
||||
<p><strong>{t('product.dosage')}</strong> {product.dosage}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="product-card-footer">
|
||||
<span className="view-details">Ver detalles →</span>
|
||||
<span className="view-details">{t('product.viewDetails')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './SavedNotifications.css';
|
||||
|
||||
function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
const { t } = useTranslation();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [items, setItems] = useState([]);
|
||||
@@ -21,7 +23,7 @@ function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
].sort((a, b) => (b.created_at || '').localeCompare(a.created_at || ''));
|
||||
setItems(merged);
|
||||
} catch (err) {
|
||||
if (!cancelled) setError(err.message || 'No se pudieron cargar las notificaciones guardadas');
|
||||
if (!cancelled) setError(err.message || t('savedNotifications.loadError'));
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
@@ -43,7 +45,7 @@ function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
setItems(prev => prev.filter(i => !(i.scope === item.scope && i.id === item.id)));
|
||||
onNotificationChange?.();
|
||||
} catch (err) {
|
||||
setError(err.message || 'No se pudo eliminar la notificación');
|
||||
setError(err.message || t('savedNotifications.deleteError'));
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
@@ -53,15 +55,15 @@ function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
<div className="saved-notifications-backdrop" onClick={onClose}>
|
||||
<div className="saved-notifications-modal" onClick={e => e.stopPropagation()}>
|
||||
<div className="saved-notifications-header">
|
||||
<h2>🔔 Notificaciones Guardadas</h2>
|
||||
<button className="saved-notifications-close" onClick={onClose} aria-label="Cerrar">×</button>
|
||||
<h2>{t('savedNotifications.title')}</h2>
|
||||
<button className="saved-notifications-close" onClick={onClose} aria-label={t('savedNotifications.close')}>×</button>
|
||||
</div>
|
||||
<div className="saved-notifications-body">
|
||||
{loading && <p className="saved-notifications-status">Cargando…</p>}
|
||||
{loading && <p className="saved-notifications-status">{t('savedNotifications.loading')}</p>}
|
||||
{!loading && error && <p className="saved-notifications-error">{error}</p>}
|
||||
{!loading && !error && items.length === 0 && (
|
||||
<p className="saved-notifications-empty">
|
||||
Aún no hay notificaciones guardadas. Toca la campana 🔕 en una farmacia sin stock para recibir notificaciones cuando se reponga.
|
||||
{t('savedNotifications.empty')}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && items.length > 0 && (
|
||||
@@ -78,7 +80,7 @@ function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
{item.scope === 'pharmacy' ? (
|
||||
<>
|
||||
<span className="saved-notifications-chip saved-notifications-chip--pharmacy">
|
||||
🏥 {item.pharmacy_name || `Farmacia #${item.pharmacy_id}`}
|
||||
🏥 {item.pharmacy_name || `${t('savedNotifications.anyPharmacy')} #${item.pharmacy_id}`}
|
||||
</span>
|
||||
{item.pharmacy_address && (
|
||||
<span className="saved-notifications-address">{item.pharmacy_address}</span>
|
||||
@@ -86,7 +88,7 @@ function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
</>
|
||||
) : (
|
||||
<span className="saved-notifications-chip">
|
||||
Cualquier farmacia
|
||||
{t('savedNotifications.anyPharmacy')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -96,9 +98,9 @@ function SavedNotifications({ onClose, onNotificationChange }) {
|
||||
className="saved-notifications-remove"
|
||||
onClick={() => handleDelete(item)}
|
||||
disabled={busyId === key}
|
||||
aria-label="Eliminar notificación"
|
||||
aria-label={t('savedNotifications.delete')}
|
||||
>
|
||||
{busyId === key ? '…' : 'Eliminar'}
|
||||
{busyId === key ? '…' : t('savedNotifications.delete')}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import './SearchBar.css';
|
||||
|
||||
function SearchBar({ value, onChange, placeholder }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="search-bar-container">
|
||||
<div className="search-bar">
|
||||
@@ -22,7 +24,7 @@ function SearchBar({ value, onChange, placeholder }) {
|
||||
<button
|
||||
className="clear-button"
|
||||
onClick={() => onChange('')}
|
||||
aria-label="Limpiar búsqueda"
|
||||
aria-label={t('search.clear')}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import './LoginForm.css';
|
||||
|
||||
function LoginForm({ onLogin }) {
|
||||
const { t } = useTranslation();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
@@ -25,14 +27,14 @@ function LoginForm({ onLogin }) {
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || 'Inicio de sesión fallido');
|
||||
throw new Error(data.error || t('admin.login.failed'));
|
||||
}
|
||||
|
||||
// Success - notify parent component
|
||||
onLogin(data.user);
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
setError(error.message || 'Usuario o contraseña inválidos');
|
||||
setError(error.message || t('admin.login.invalidCredentials'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -42,8 +44,8 @@ function LoginForm({ onLogin }) {
|
||||
<div className="login-container">
|
||||
<div className="login-box">
|
||||
<div className="login-header">
|
||||
<h2>🔐 Acceso Administración</h2>
|
||||
<p>Introduce tus credenciales para acceder al panel de administración</p>
|
||||
<h2>{t('admin.login.title')}</h2>
|
||||
<p>{t('admin.login.description')}</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="login-form">
|
||||
@@ -54,13 +56,13 @@ function LoginForm({ onLogin }) {
|
||||
)}
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="username">Usuario</label>
|
||||
<label htmlFor="username">{t('admin.login.username')}</label>
|
||||
<input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Introduce usuario"
|
||||
placeholder={t('admin.login.usernamePlaceholder')}
|
||||
required
|
||||
autoFocus
|
||||
disabled={loading}
|
||||
@@ -68,13 +70,13 @@ function LoginForm({ onLogin }) {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="password">Contraseña</label>
|
||||
<label htmlFor="password">{t('admin.login.password')}</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Introduce contraseña"
|
||||
placeholder={t('admin.login.passwordPlaceholder')}
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
@@ -85,16 +87,16 @@ function LoginForm({ onLogin }) {
|
||||
className="login-button"
|
||||
disabled={loading || !username || !password}
|
||||
>
|
||||
{loading ? 'Iniciando sesión...' : 'Iniciar sesión'}
|
||||
{loading ? t('admin.login.loggingIn') : t('admin.login.loginBtn')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="login-footer">
|
||||
<p className="help-text">
|
||||
Credenciales por defecto: <code>admin</code> / <code>admin123</code>
|
||||
{t('admin.login.defaultCredentials')} <code>admin</code> / <code>admin123</code>
|
||||
</p>
|
||||
<p className="warning-text">
|
||||
⚠️ ¡Cambia la contraseña por defecto tras el primer inicio de sesión!
|
||||
{t('admin.login.changePasswordWarning')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import './AdminComponents.css';
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 400;
|
||||
|
||||
function MedicineManagement() {
|
||||
const { t } = useTranslation();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [medicines, setMedicines] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -29,7 +31,7 @@ function MedicineManagement() {
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
console.error('Error searching medicines:', error);
|
||||
alert('Error al buscar medicamentos en la API CIMA');
|
||||
alert(t('admin.medicine.loadError'));
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
@@ -44,47 +46,47 @@ function MedicineManagement() {
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<div className="section-header">
|
||||
<h2>Buscar Medicamentos (API CIMA)</h2>
|
||||
<h2>{t('admin.medicine.title')}</h2>
|
||||
</div>
|
||||
|
||||
<div className="info-box">
|
||||
<p>ℹ️ Los medicamentos ahora se obtienen directamente de la <strong>API de CIMA</strong> (Agencia Española de Medicamentos y Productos Sanitarios).</p>
|
||||
<p>Busca medicamentos para vincularlos a farmacias en la pestaña "Link Medicine".</p>
|
||||
<p>ℹ️ {t('admin.medicine.description')} <strong>{t('admin.medicine.cimaApi')}</strong> {t('admin.medicine.cimaDescription')}</p>
|
||||
<p>{t('admin.medicine.linkDescription')}</p>
|
||||
</div>
|
||||
|
||||
<div className="admin-form">
|
||||
<div className="form-group">
|
||||
<label>Buscar medicamentos</label>
|
||||
<label>{t('admin.medicine.search')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Escribe el nombre de un medicamento..."
|
||||
placeholder={t('admin.medicine.searchPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && <div className="loading">Buscando en API CIMA...</div>}
|
||||
{loading && <div className="loading">{t('admin.medicine.searching')}</div>}
|
||||
|
||||
{!loading && medicines.length > 0 && (
|
||||
<div className="admin-list">
|
||||
<p className="info-text">Se encontraron {medicines.length} medicamentos</p>
|
||||
<p className="info-text">{t('admin.medicine.found')} {medicines.length} {t('admin.medicine.medications')}</p>
|
||||
{medicines.map((medicine) => (
|
||||
<div key={medicine.nregistro} className="admin-item">
|
||||
<div className="item-content">
|
||||
<h4>{medicine.name}</h4>
|
||||
{medicine.active_ingredient && (
|
||||
<p><strong>Principio Activo:</strong> {medicine.active_ingredient}</p>
|
||||
<p><strong>{t('admin.medicine.activeIngredient')}</strong> {medicine.active_ingredient}</p>
|
||||
)}
|
||||
<p>
|
||||
{medicine.dosage && <span><strong>Dosis:</strong> {medicine.dosage}</span>}
|
||||
{medicine.dosage && <span><strong>{t('admin.medicine.dosage')}</strong> {medicine.dosage}</span>}
|
||||
{medicine.dosage && medicine.form && ' • '}
|
||||
{medicine.form && <span><strong>Forma:</strong> {medicine.form}</span>}
|
||||
{medicine.form && <span><strong>{t('admin.medicine.form')}</strong> {medicine.form}</span>}
|
||||
</p>
|
||||
<p className="medicine-meta">
|
||||
<strong>Laboratorio:</strong> {medicine.laboratory} •
|
||||
<strong> Nº Registro:</strong> {medicine.nregistro} •
|
||||
{medicine.generic ? ' Genérico' : ' Marca'}
|
||||
<strong>{t('admin.medicine.laboratory')}</strong> {medicine.laboratory} •
|
||||
<strong> {t('admin.medicine.registrationNumber')}</strong> {medicine.nregistro} •
|
||||
{medicine.generic ? ` ${t('admin.medicine.generic')}` : ` ${t('admin.medicine.brand')}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -93,7 +95,7 @@ function MedicineManagement() {
|
||||
)}
|
||||
|
||||
{!loading && searchQuery.trim().length >= 2 && medicines.length === 0 && (
|
||||
<p className="empty-state">No se encontraron medicamentos con ese nombre.</p>
|
||||
<p className="empty-state">{t('admin.medicine.noResults')}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import './AdminComponents.css';
|
||||
import { DAY_KEYS, DAY_LABEL } from '../../utils/hours';
|
||||
import { useTranslation } from '../../i18n';
|
||||
|
||||
function emptyHoursDraft() {
|
||||
const draft = {};
|
||||
@@ -55,18 +56,20 @@ function haversineMeters(lat1, lon1, lat2, lon2) {
|
||||
return 2 * R * Math.asin(Math.sqrt(Math.min(1, a)));
|
||||
}
|
||||
|
||||
const REGION_PRESETS = [
|
||||
{ id: 'custom', label: 'Coordenadas personalizadas', lat: '', lon: '', radio: '' },
|
||||
{
|
||||
id: 'rubi',
|
||||
label: 'Ejemplo: Área de Rubí (1.5 km)',
|
||||
lat: '41.5631',
|
||||
lon: '2.0038',
|
||||
radio: '1500',
|
||||
},
|
||||
];
|
||||
function getRegionPresets(t) {
|
||||
return [
|
||||
{ id: 'custom', label: t('admin.pharmacy.customCoordinates'), lat: '', lon: '', radio: '' },
|
||||
{
|
||||
id: 'rubi',
|
||||
label: t('admin.pharmacy.areaExample'),
|
||||
lat: '41.5631',
|
||||
lon: '2.0038',
|
||||
radio: '1500',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async function geocodeErrorMessage(response) {
|
||||
async function geocodeErrorMessage(response, t) {
|
||||
const text = await response.text();
|
||||
let body = {};
|
||||
try {
|
||||
@@ -76,19 +79,21 @@ async function geocodeErrorMessage(response) {
|
||||
}
|
||||
if (typeof body.error === 'string' && body.error.trim()) return body.error;
|
||||
if (response.status === 401) {
|
||||
return 'Sesión expirada o no has iniciado sesión. Inicia sesión de nuevo en el panel Admin y reintenta.';
|
||||
return t('admin.pharmacy.sessionExpired');
|
||||
}
|
||||
if (response.status === 404) {
|
||||
const looksLikeHtml = /<!DOCTYPE|<html[\s>]/i.test(text || '');
|
||||
if (looksLikeHtml) {
|
||||
return 'La app no pudo conectar con la API (404). Usa http://localhost:3000 con frontend y backend activos.';
|
||||
return t('admin.pharmacy.apiNotFound');
|
||||
}
|
||||
return 'Servicio de geocodificación no encontrado. Actualiza el backend y reinícialo.';
|
||||
return t('admin.pharmacy.geocodingNotFound');
|
||||
}
|
||||
return `Búsqueda fallida (HTTP ${response.status}).`;
|
||||
return `${t('admin.pharmacy.searchFailed')} ${response.status}).`;
|
||||
}
|
||||
|
||||
function PharmacyManagement() {
|
||||
const { t } = useTranslation();
|
||||
const REGION_PRESETS = getRegionPresets(t);
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -132,7 +137,7 @@ function PharmacyManagement() {
|
||||
setPharmacies(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacies:', error);
|
||||
alert('Error al cargar farmacias');
|
||||
alert(t('admin.pharmacy.loadError'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -165,7 +170,7 @@ function PharmacyManagement() {
|
||||
e?.preventDefault();
|
||||
const q = cityQuery.trim();
|
||||
if (!q) {
|
||||
setCityLookupMessage({ type: 'err', text: 'Introduce una ciudad o lugar.' });
|
||||
setCityLookupMessage({ type: 'err', text: t('admin.pharmacy.enterCity') });
|
||||
return;
|
||||
}
|
||||
setCityLookupLoading(true);
|
||||
@@ -175,7 +180,7 @@ function PharmacyManagement() {
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(await geocodeErrorMessage(response));
|
||||
throw new Error(await geocodeErrorMessage(response, t));
|
||||
}
|
||||
const data = await response.json();
|
||||
setRegionLat(String(data.lat));
|
||||
@@ -253,7 +258,7 @@ function PharmacyManagement() {
|
||||
const lon = parseFloat(regionLon);
|
||||
const radio = parseFloat(regionRadio);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon) || !Number.isFinite(radio)) {
|
||||
throw new Error('Establece latitud, longitud y radio (usa Buscar ciudad o un preset).');
|
||||
throw new Error(t('admin.pharmacy.setCoordinates'));
|
||||
}
|
||||
const response = await fetch('/api/admin/pharmacies/import-external', {
|
||||
method: 'POST',
|
||||
@@ -307,7 +312,7 @@ function PharmacyManagement() {
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || 'Error al actualizar farmacia');
|
||||
throw new Error(error.error || t('admin.pharmacy.updateError'));
|
||||
}
|
||||
} else {
|
||||
const response = await fetch('/api/admin/pharmacies', {
|
||||
@@ -319,16 +324,16 @@ function PharmacyManagement() {
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || 'Error al crear farmacia');
|
||||
throw new Error(error.error || t('admin.pharmacy.createError'));
|
||||
}
|
||||
}
|
||||
|
||||
resetForm();
|
||||
fetchPharmacies();
|
||||
alert(editingPharmacy ? '¡Farmacia actualizada!' : '¡Farmacia añadida!');
|
||||
alert(editingPharmacy ? t('admin.pharmacy.updated') : t('admin.pharmacy.created'));
|
||||
} catch (error) {
|
||||
console.error('Error saving pharmacy:', error);
|
||||
alert(`Error al guardar farmacia: ${error.message}`);
|
||||
alert(`${t('admin.pharmacy.saveError')}: ${error.message}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -348,7 +353,7 @@ function PharmacyManagement() {
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('¿Estás seguro de que quieres eliminar esta farmacia?')) return;
|
||||
if (!confirm(t('admin.pharmacy.deleteConfirm'))) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/pharmacies/${id}`, {
|
||||
@@ -356,13 +361,13 @@ function PharmacyManagement() {
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al eliminar farmacia');
|
||||
if (!response.ok) throw new Error(t('admin.pharmacy.deleteError'));
|
||||
|
||||
fetchPharmacies();
|
||||
alert('¡Farmacia eliminada!');
|
||||
alert(t('admin.pharmacy.deleted'));
|
||||
} catch (error) {
|
||||
console.error('Error deleting pharmacy:', error);
|
||||
alert('Error al eliminar farmacia');
|
||||
alert(t('admin.pharmacy.deleteError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -391,7 +396,7 @@ function PharmacyManagement() {
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<div className="section-header">
|
||||
<h2>Gestionar Farmacias</h2>
|
||||
<h2>{t('admin.pharmacy.title')}</h2>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary"
|
||||
@@ -400,15 +405,15 @@ function PharmacyManagement() {
|
||||
setShowForm(true);
|
||||
}}
|
||||
>
|
||||
+ Añadir Nueva Farmacia
|
||||
{t('admin.pharmacy.addNew')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="pharmacy-tools-card">
|
||||
<h3>Ciudad, región e importación</h3>
|
||||
<h3>{t('admin.pharmacy.citySearch')}</h3>
|
||||
<p className="pharmacy-tools-hint">
|
||||
<strong>Buscar ciudad</strong> establece latitud, longitud y radio para el filtro de mapa y las importaciones.
|
||||
Elige una <strong>fuente de datos</strong>: <strong>OpenStreetMap</strong> es gratuita (sin clave);{' '}
|
||||
<strong>{t('admin.pharmacy.searchCity')}</strong> establece latitud, longitud y radio para el filtro de mapa y las importaciones.
|
||||
{t('admin.pharmacy.chooseOne')} <strong>fuente de datos</strong>: <strong>OpenStreetMap</strong> es gratuita (sin clave);{' '}
|
||||
<strong>URL de datos abiertos</strong> carga JSON alojado por ti. Geocodificación usa{' '}
|
||||
<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noreferrer">
|
||||
OpenStreetMap
|
||||
@@ -418,11 +423,11 @@ function PharmacyManagement() {
|
||||
|
||||
<form className="city-lookup-form" onSubmit={handleCityLookup}>
|
||||
<div className="form-group city-lookup-input-wrap">
|
||||
<label htmlFor="city-finder">Buscar ciudad</label>
|
||||
<label htmlFor="city-finder">{t('admin.pharmacy.searchCity')}</label>
|
||||
<input
|
||||
id="city-finder"
|
||||
type="search"
|
||||
placeholder="Ej: Rubí, Madrid, Valencia…"
|
||||
placeholder={t('admin.pharmacy.cityPlaceholder')}
|
||||
value={cityQuery}
|
||||
onChange={(e) => {
|
||||
setCityQuery(e.target.value);
|
||||
@@ -436,7 +441,7 @@ function PharmacyManagement() {
|
||||
className="btn-secondary city-lookup-submit"
|
||||
disabled={cityLookupLoading}
|
||||
>
|
||||
{cityLookupLoading ? 'Buscando…' : 'Buscar ciudad'}
|
||||
{cityLookupLoading ? t('admin.pharmacy.searching') : t('admin.pharmacy.searchCity')}
|
||||
</button>
|
||||
</form>
|
||||
{cityLookupMessage && (
|
||||
@@ -449,7 +454,7 @@ function PharmacyManagement() {
|
||||
)}
|
||||
|
||||
<div className="region-presets">
|
||||
<label htmlFor="region-preset">Preset de área</label>
|
||||
<label htmlFor="region-preset">{t('admin.pharmacy.areaPreset')}</label>
|
||||
<select
|
||||
id="region-preset"
|
||||
value={regionPreset}
|
||||
@@ -465,7 +470,7 @@ function PharmacyManagement() {
|
||||
|
||||
<div className="region-grid">
|
||||
<div className="form-group">
|
||||
<label htmlFor="region-lat">Latitud</label>
|
||||
<label htmlFor="region-lat">{t('admin.pharmacy.latitude')}</label>
|
||||
<input
|
||||
id="region-lat"
|
||||
type="text"
|
||||
@@ -476,7 +481,7 @@ function PharmacyManagement() {
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="region-lon">Longitud</label>
|
||||
<label htmlFor="region-lon">{t('admin.pharmacy.longitude')}</label>
|
||||
<input
|
||||
id="region-lon"
|
||||
type="text"
|
||||
@@ -487,7 +492,7 @@ function PharmacyManagement() {
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="region-radio">Radio (m)</label>
|
||||
<label htmlFor="region-radio">{t('admin.pharmacy.radius')} (m)</label>
|
||||
<input
|
||||
id="region-radio"
|
||||
type="text"
|
||||
@@ -501,7 +506,7 @@ function PharmacyManagement() {
|
||||
|
||||
<div className="import-mode-row">
|
||||
<div className="form-group import-mode-select-wrap">
|
||||
<label htmlFor="import-mode">Fuente de datos</label>
|
||||
<label htmlFor="import-mode">{t('admin.pharmacy.dataSource')}</label>
|
||||
<select
|
||||
id="import-mode"
|
||||
value={importMode}
|
||||
@@ -511,15 +516,15 @@ function PharmacyManagement() {
|
||||
}}
|
||||
>
|
||||
<option value="osm">OpenStreetMap (Overpass, gratuito)</option>
|
||||
<option value="webhook">n8n webhook (heredado)</option>
|
||||
<option value="openData">URL de datos abiertos JSON</option>
|
||||
<option value="webhook">{t('admin.pharmacy.webhookLegacy')}</option>
|
||||
<option value="openData">{t('admin.pharmacy.openDataJson')}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{importMode === 'openData' && (
|
||||
<div className="form-group open-data-url-row">
|
||||
<label htmlFor="open-data-url">URL JSON</label>
|
||||
<label htmlFor="open-data-url">{t('admin.pharmacy.jsonUrl')}</label>
|
||||
<input
|
||||
id="open-data-url"
|
||||
type="url"
|
||||
@@ -539,12 +544,12 @@ function PharmacyManagement() {
|
||||
disabled={importing}
|
||||
>
|
||||
{importing
|
||||
? 'Importando…'
|
||||
? t('admin.pharmacy.importing')
|
||||
: importMode === 'webhook'
|
||||
? 'Importar desde webhook'
|
||||
? t('admin.pharmacy.importWebhook')
|
||||
: importMode === 'openData'
|
||||
? 'Importar desde URL'
|
||||
: `Importar desde ${importMode === 'osm' ? 'Overpass' : 'OpenStreetMap'}`}
|
||||
? t('admin.pharmacy.importUrl')
|
||||
: `${t('admin.pharmacy.importFrom')} ${importMode === 'osm' ? 'Overpass' : 'OpenStreetMap'}`}
|
||||
</button>
|
||||
<label className="filter-region-toggle">
|
||||
<input
|
||||
@@ -552,7 +557,7 @@ function PharmacyManagement() {
|
||||
checked={filterByRegion}
|
||||
onChange={(e) => setFilterByRegion(e.target.checked)}
|
||||
/>
|
||||
Mostrar solo farmacias dentro del radio
|
||||
{t('admin.pharmacy.showWithinRadio')}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -568,10 +573,10 @@ function PharmacyManagement() {
|
||||
|
||||
{showForm && (
|
||||
<form className="admin-form" onSubmit={handleSubmit}>
|
||||
<h3>{editingPharmacy ? 'Editar Farmacia' : 'Añadir Nueva Farmacia'}</h3>
|
||||
<h3>{editingPharmacy ? t('admin.pharmacy.edit') : t('admin.pharmacy.add')}</h3>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Nombre *</label>
|
||||
<label>{t('admin.pharmacy.name')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.name}
|
||||
@@ -581,7 +586,7 @@ function PharmacyManagement() {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Dirección *</label>
|
||||
<label>{t('admin.pharmacy.address')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.address}
|
||||
@@ -591,7 +596,7 @@ function PharmacyManagement() {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Teléfono</label>
|
||||
<label>{t('admin.pharmacy.phone')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.phone}
|
||||
@@ -601,7 +606,7 @@ function PharmacyManagement() {
|
||||
|
||||
<div className="form-row">
|
||||
<div className="form-group">
|
||||
<label>Latitud</label>
|
||||
<label>{t('admin.pharmacy.latitude')}</label>
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
@@ -611,7 +616,7 @@ function PharmacyManagement() {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Longitud</label>
|
||||
<label>{t('admin.pharmacy.longitude')}</label>
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
@@ -622,8 +627,8 @@ function PharmacyManagement() {
|
||||
</div>
|
||||
|
||||
<fieldset className="hours-editor">
|
||||
<legend>Horario de apertura</legend>
|
||||
<p className="hours-editor-hint">Marca un día como <em>Cerrado</em> si la farmacia no abre ese día.</p>
|
||||
<legend>{t('admin.pharmacy.openingHours')}</legend>
|
||||
<p className="hours-editor-hint">{t('admin.pharmacy.dayClosed')}</p>
|
||||
{DAY_KEYS.map((day) => {
|
||||
const d = hoursDraft[day];
|
||||
return (
|
||||
@@ -635,14 +640,14 @@ function PharmacyManagement() {
|
||||
checked={d.closed}
|
||||
onChange={(e) => updateDay(day, { closed: e.target.checked })}
|
||||
/>
|
||||
Cerrado
|
||||
{t('admin.pharmacy.closed')}
|
||||
</label>
|
||||
<input
|
||||
type="time"
|
||||
value={d.open}
|
||||
disabled={d.closed}
|
||||
onChange={(e) => updateDay(day, { open: e.target.value })}
|
||||
aria-label={`${DAY_LABEL[day]} abre a las`}
|
||||
aria-label={`${DAY_LABEL[day]} ${t('admin.pharmacy.opensAt')}`}
|
||||
/>
|
||||
<span className="hours-sep">–</span>
|
||||
<input
|
||||
@@ -650,7 +655,7 @@ function PharmacyManagement() {
|
||||
value={d.close}
|
||||
disabled={d.closed}
|
||||
onChange={(e) => updateDay(day, { close: e.target.value })}
|
||||
aria-label={`${DAY_LABEL[day]} cierra a las`}
|
||||
aria-label={`${DAY_LABEL[day]} ${t('admin.pharmacy.closesAt')}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -659,28 +664,28 @@ function PharmacyManagement() {
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn-primary" disabled={saving}>
|
||||
{saving ? 'Guardando...' : editingPharmacy ? 'Actualizar' : 'Añadir'} Farmacia
|
||||
{saving ? t('admin.pharmacy.saving') : editingPharmacy ? `${t('admin.pharmacy.update')} Farmacia` : `${t('admin.pharmacy.create')} Farmacia`}
|
||||
</button>
|
||||
<button type="button" className="btn-secondary" onClick={resetForm} disabled={saving}>
|
||||
Cancelar
|
||||
{t('admin.pharmacy.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="loading">Cargando farmacias...</div>
|
||||
<div className="loading">{t('admin.pharmacy.loading')}</div>
|
||||
) : (
|
||||
<div className="admin-list">
|
||||
<p className="list-meta">
|
||||
Mostrando {displayedPharmacies.length} de {pharmacies.length} farmacias
|
||||
{filterByRegion && ' (dentro del radio)'}
|
||||
{t('admin.pharmacy.showing')} {displayedPharmacies.length} {t('admin.pharmacy.of')} {pharmacies.length} farmacias
|
||||
{filterByRegion && ` ${t('admin.pharmacy.withinRadio')}`}
|
||||
</p>
|
||||
{displayedPharmacies.length === 0 ? (
|
||||
<p className="empty-state">
|
||||
{pharmacies.length === 0
|
||||
? 'Aún no hay farmacias. Importa desde webhook o añade una manualmente.'
|
||||
: 'No hay farmacias en este radio con coordenadas. Amplía el radio, busca otra ciudad o desactiva el filtro de región.'}
|
||||
? t('admin.pharmacy.empty')
|
||||
: t('admin.pharmacy.noResults')}
|
||||
</p>
|
||||
) : (
|
||||
displayedPharmacies.map((pharmacy) => (
|
||||
@@ -697,10 +702,10 @@ function PharmacyManagement() {
|
||||
</div>
|
||||
<div className="item-actions">
|
||||
<button type="button" className="btn-edit" onClick={() => handleEdit(pharmacy)}>
|
||||
Editar
|
||||
{t('admin.pharmacy.editBtn')}
|
||||
</button>
|
||||
<button type="button" className="btn-delete" onClick={() => handleDelete(pharmacy.id)}>
|
||||
Eliminar
|
||||
{t('admin.pharmacy.deleteBtn')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import './AdminComponents.css';
|
||||
|
||||
const MAX_PHARMACY_RESULTS = 25;
|
||||
@@ -8,6 +9,7 @@ function normalize(s) {
|
||||
}
|
||||
|
||||
function PharmacyMedicineLink() {
|
||||
const { t } = useTranslation();
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [medicineSearch, setMedicineSearch] = useState('');
|
||||
const [medicineResults, setMedicineResults] = useState([]);
|
||||
@@ -111,7 +113,7 @@ function PharmacyMedicineLink() {
|
||||
e.preventDefault();
|
||||
|
||||
if (!selectedMedicine) {
|
||||
alert('Por favor, selecciona un medicamento primero');
|
||||
alert(t('admin.linkMedicine.selectMedicineFirst'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -131,16 +133,16 @@ function PharmacyMedicineLink() {
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al vincular medicamento a farmacia');
|
||||
if (!response.ok) throw new Error(t('admin.linkMedicine.linkError'));
|
||||
|
||||
resetForm();
|
||||
if (selectedPharmacy) {
|
||||
fetchPharmacyMedicines(selectedPharmacy.id);
|
||||
}
|
||||
alert('¡Medicamento vinculado a la farmacia correctamente!');
|
||||
alert(t('admin.linkMedicine.linkSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Error linking medicine:', error);
|
||||
alert('Error al vincular medicamento a farmacia');
|
||||
alert(t('admin.linkMedicine.linkError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -153,18 +155,18 @@ function PharmacyMedicineLink() {
|
||||
body: JSON.stringify({ price, stock })
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al actualizar');
|
||||
if (!response.ok) throw new Error(t('admin.linkMedicine.updateError'));
|
||||
|
||||
fetchPharmacyMedicines(selectedPharmacy.id);
|
||||
alert('¡Actualizado correctamente!');
|
||||
alert(t('admin.linkMedicine.updateSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Error updating:', error);
|
||||
alert('Error al actualizar');
|
||||
alert(t('admin.linkMedicine.updateError'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('¿Eliminar este medicamento de la farmacia?')) return;
|
||||
if (!confirm(t('admin.linkMedicine.deleteConfirm'))) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/pharmacy-medicines/${id}`, {
|
||||
@@ -172,13 +174,13 @@ function PharmacyMedicineLink() {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al eliminar');
|
||||
if (!response.ok) throw new Error(t('admin.linkMedicine.deleteError'));
|
||||
|
||||
fetchPharmacyMedicines(selectedPharmacy.id);
|
||||
alert('¡Medicamento eliminado de la farmacia!');
|
||||
alert(t('admin.linkMedicine.deleteSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Error deleting:', error);
|
||||
alert('Error al eliminar medicamento');
|
||||
alert(t('admin.linkMedicine.deleteError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -216,11 +218,11 @@ function PharmacyMedicineLink() {
|
||||
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2>Vincular Medicamento a Farmacia</h2>
|
||||
<h2>{t('admin.linkMedicine.title')}</h2>
|
||||
|
||||
<form className="admin-form" onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>Farmacia *</label>
|
||||
<label>{t('admin.linkMedicine.pharmacy')}</label>
|
||||
<input
|
||||
ref={pharmacyInputRef}
|
||||
type="text"
|
||||
@@ -235,7 +237,7 @@ function PharmacyMedicineLink() {
|
||||
}}
|
||||
onFocus={() => setPharmacyDropdownOpen(true)}
|
||||
onBlur={() => setTimeout(() => setPharmacyDropdownOpen(false), 150)}
|
||||
placeholder={pharmacies.length ? `Buscar entre ${pharmacies.length} farmacias por nombre o dirección…` : 'Cargando farmacias…'}
|
||||
placeholder={pharmacies.length ? `${t('admin.linkMedicine.searchPharmacy')} ${pharmacies.length} ${t('admin.linkMedicine.pharmacies')}` : t('admin.linkMedicine.loadingPharmacies')}
|
||||
autoComplete="off"
|
||||
required={!selectedPharmacy}
|
||||
/>
|
||||
@@ -243,7 +245,7 @@ function PharmacyMedicineLink() {
|
||||
<div className="medicine-search-results">
|
||||
{filteredPharmacies.length === 0 ? (
|
||||
<div className="search-result-item search-result-item--empty">
|
||||
<span>No hay farmacias que coincidan con "{pharmacyQuery}"</span>
|
||||
<span>{t('admin.linkMedicine.noPharmacies')} "{pharmacyQuery}"</span>
|
||||
</div>
|
||||
) : (
|
||||
filteredPharmacies.map((pharmacy) => (
|
||||
@@ -264,14 +266,14 @@ function PharmacyMedicineLink() {
|
||||
<p>✅ Selected: <strong>{selectedPharmacy.name}</strong></p>
|
||||
<p className="medicine-details">{selectedPharmacy.address}</p>
|
||||
<button type="button" className="btn-small" onClick={clearPharmacy}>
|
||||
Cambiar farmacia
|
||||
{t('admin.linkMedicine.changePharmacy')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Buscar Medicamento (API CIMA) *</label>
|
||||
<label>{t('admin.linkMedicine.medicine')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={medicineSearch}
|
||||
@@ -279,10 +281,10 @@ function PharmacyMedicineLink() {
|
||||
setMedicineSearch(e.target.value);
|
||||
setSelectedMedicine(null);
|
||||
}}
|
||||
placeholder="Escribe para buscar medicamentos en CIMA..."
|
||||
placeholder={t('admin.linkMedicine.searchMedicine')}
|
||||
required
|
||||
/>
|
||||
{searching && <p className="loading-text">Buscando...</p>}
|
||||
{searching && <p className="loading-text">{t('admin.linkMedicine.searching')}</p>}
|
||||
|
||||
{medicineResults.length > 0 && !selectedMedicine && (
|
||||
<div className="medicine-search-results">
|
||||
@@ -304,9 +306,9 @@ function PharmacyMedicineLink() {
|
||||
<div className="selected-medicine-info">
|
||||
<p>✅ Selected: <strong>{selectedMedicine.name}</strong></p>
|
||||
<p className="medicine-details">
|
||||
{selectedMedicine.active_ingredient && `Principio activo: ${selectedMedicine.active_ingredient} • `}
|
||||
{selectedMedicine.dosage && `Dosis: ${selectedMedicine.dosage} • `}
|
||||
Nº Registro: {selectedMedicine.nregistro}
|
||||
{selectedMedicine.active_ingredient && `${t('admin.linkMedicine.activeIngredient')} ${selectedMedicine.active_ingredient} • `}
|
||||
{selectedMedicine.dosage && `${t('admin.linkMedicine.dosage')} ${selectedMedicine.dosage} • `}
|
||||
{t('admin.linkMedicine.registrationNumber')} {selectedMedicine.nregistro}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
@@ -316,7 +318,7 @@ function PharmacyMedicineLink() {
|
||||
setMedicineSearch('');
|
||||
}}
|
||||
>
|
||||
Cambiar medicamento
|
||||
{t('admin.linkMedicine.changeMedicine')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -324,7 +326,7 @@ function PharmacyMedicineLink() {
|
||||
|
||||
<div className="form-row">
|
||||
<div className="form-group">
|
||||
<label>Precio (€)</label>
|
||||
<label>{t('admin.linkMedicine.price')}</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
@@ -335,7 +337,7 @@ function PharmacyMedicineLink() {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Stock</label>
|
||||
<label>{t('admin.linkMedicine.stock')}</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.stock}
|
||||
@@ -347,21 +349,21 @@ function PharmacyMedicineLink() {
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn-primary">
|
||||
Vincular Medicamento
|
||||
{t('admin.linkMedicine.linkBtn')}
|
||||
</button>
|
||||
<button type="button" className="btn-secondary" onClick={resetForm}>
|
||||
Reiniciar
|
||||
{t('admin.linkMedicine.reset')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{selectedPharmacy && (
|
||||
<div className="pharmacy-medicines-section">
|
||||
<h3>Medicamentos en {selectedPharmacy.name}</h3>
|
||||
<h3>{t('admin.linkMedicine.medicationsIn')} {selectedPharmacy.name}</h3>
|
||||
{loading ? (
|
||||
<div className="loading">Cargando...</div>
|
||||
<div className="loading">{t('admin.linkMedicine.loading')}</div>
|
||||
) : pharmacyMedicines.length === 0 ? (
|
||||
<p className="empty-state">Aún no hay medicamentos vinculados a esta farmacia.</p>
|
||||
<p className="empty-state">{t('admin.linkMedicine.empty')}</p>
|
||||
) : (
|
||||
<div className="admin-list">
|
||||
{pharmacyMedicines.map((pm) => (
|
||||
@@ -369,7 +371,7 @@ function PharmacyMedicineLink() {
|
||||
<div className="item-content">
|
||||
<h4>{pm.medicine_name}</h4>
|
||||
<p>
|
||||
<strong>Precio:</strong> {pm.price ? `€${parseFloat(pm.price).toFixed(2)}` : 'No definido'} •
|
||||
<strong>{t('admin.linkMedicine.priceLabel')}</strong> {pm.price ? `€${parseFloat(pm.price).toFixed(2)}` : t('admin.linkMedicine.undefined')} •
|
||||
<strong> Stock:</strong> {pm.stock || 0}
|
||||
</p>
|
||||
</div>
|
||||
@@ -377,17 +379,17 @@ function PharmacyMedicineLink() {
|
||||
<button
|
||||
className="btn-edit"
|
||||
onClick={() => {
|
||||
const newPrice = prompt('Introduce nuevo precio:', pm.price || '');
|
||||
const newStock = prompt('Introduce nuevo stock:', pm.stock || '0');
|
||||
const newPrice = prompt(t('admin.linkMedicine.newPrice'), pm.price || '');
|
||||
const newStock = prompt(t('admin.linkMedicine.newStock'), pm.stock || '0');
|
||||
if (newPrice !== null && newStock !== null) {
|
||||
handleUpdate(pm.id, newPrice ? parseFloat(newPrice) : null, parseInt(newStock) || 0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Actualizar
|
||||
{t('admin.linkMedicine.update')}
|
||||
</button>
|
||||
<button className="btn-delete" onClick={() => handleDelete(pm.id)}>
|
||||
Eliminar
|
||||
{t('admin.linkMedicine.delete')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import './AdminComponents.css';
|
||||
|
||||
const MAX_PHARMACY_RESULTS = 25;
|
||||
@@ -8,6 +9,7 @@ function normalize(s) {
|
||||
}
|
||||
|
||||
function PharmacyProductLink() {
|
||||
const { t } = useTranslation();
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [productSearch, setProductSearch] = useState('');
|
||||
const [productResults, setProductResults] = useState([]);
|
||||
@@ -130,7 +132,7 @@ function PharmacyProductLink() {
|
||||
e.preventDefault();
|
||||
|
||||
if (!selectedProduct) {
|
||||
alert('Por favor, selecciona un producto primero');
|
||||
alert(t('admin.linkProduct.selectProductFirst'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -156,16 +158,16 @@ function PharmacyProductLink() {
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al vincular producto a farmacia');
|
||||
if (!response.ok) throw new Error(t('admin.linkProduct.linkError'));
|
||||
|
||||
resetForm();
|
||||
if (selectedPharmacy) {
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
}
|
||||
alert('¡Producto vinculado a la farmacia correctamente!');
|
||||
alert(t('admin.linkProduct.linkSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Error linking product:', error);
|
||||
alert('Error al vincular producto a farmacia');
|
||||
alert(t('admin.linkProduct.linkError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -178,18 +180,18 @@ function PharmacyProductLink() {
|
||||
body: JSON.stringify({ price, stock })
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al actualizar');
|
||||
if (!response.ok) throw new Error(t('admin.linkProduct.updateError'));
|
||||
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
alert('¡Actualizado correctamente!');
|
||||
alert(t('admin.linkProduct.updateSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Error updating:', error);
|
||||
alert('Error al actualizar');
|
||||
alert(t('admin.linkProduct.updateError'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('¿Eliminar este producto de la farmacia?')) return;
|
||||
if (!confirm(t('admin.linkProduct.deleteConfirm'))) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/pharmacy-products/${id}`, {
|
||||
@@ -197,13 +199,13 @@ function PharmacyProductLink() {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al eliminar');
|
||||
if (!response.ok) throw new Error(t('admin.linkProduct.deleteError'));
|
||||
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
alert('¡Producto eliminado de la farmacia!');
|
||||
alert(t('admin.linkProduct.deleteSuccess'));
|
||||
} catch (error) {
|
||||
console.error('Error deleting:', error);
|
||||
alert('Error al eliminar producto');
|
||||
alert(t('admin.linkProduct.deleteError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -266,11 +268,11 @@ function PharmacyProductLink() {
|
||||
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2>Vincular Producto a Farmacia</h2>
|
||||
<h2>{t('admin.linkProduct.title')}</h2>
|
||||
|
||||
<form className="admin-form" onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>Farmacia *</label>
|
||||
<label>{t('admin.linkProduct.pharmacy')}</label>
|
||||
<input
|
||||
ref={pharmacyInputRef}
|
||||
type="text"
|
||||
@@ -285,7 +287,7 @@ function PharmacyProductLink() {
|
||||
}}
|
||||
onFocus={() => setPharmacyDropdownOpen(true)}
|
||||
onBlur={() => setTimeout(() => setPharmacyDropdownOpen(false), 150)}
|
||||
placeholder={pharmacies.length ? `Buscar entre ${pharmacies.length} farmacias por nombre o dirección…` : 'Cargando farmacias…'}
|
||||
placeholder={pharmacies.length ? `${t('admin.linkProduct.searchPharmacy')} ${pharmacies.length} ${t('admin.linkProduct.pharmacies')}` : t('admin.linkProduct.loadingPharmacies')}
|
||||
autoComplete="off"
|
||||
required={!selectedPharmacy}
|
||||
/>
|
||||
@@ -293,7 +295,7 @@ function PharmacyProductLink() {
|
||||
<div className="medicine-search-results">
|
||||
{filteredPharmacies.length === 0 ? (
|
||||
<div className="search-result-item search-result-item--empty">
|
||||
<span>No hay farmacias que coincidan con "{pharmacyQuery}"</span>
|
||||
<span>{t('admin.linkProduct.noPharmacies')} "{pharmacyQuery}"</span>
|
||||
</div>
|
||||
) : (
|
||||
filteredPharmacies.map((pharmacy) => (
|
||||
@@ -314,14 +316,14 @@ function PharmacyProductLink() {
|
||||
<p>✅ Selected: <strong>{selectedPharmacy.name}</strong></p>
|
||||
<p className="medicine-details">{selectedPharmacy.address}</p>
|
||||
<button type="button" className="btn-small" onClick={clearPharmacy}>
|
||||
Cambiar farmacia
|
||||
{t('admin.linkProduct.changePharmacy')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Buscar Producto (CIMA / Parafarmacia) *</label>
|
||||
<label>{t('admin.linkProduct.product')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={productSearch}
|
||||
@@ -329,10 +331,10 @@ function PharmacyProductLink() {
|
||||
setProductSearch(e.target.value);
|
||||
setSelectedProduct(null);
|
||||
}}
|
||||
placeholder="Escribe para buscar medicamentos o productos de parafarmacia..."
|
||||
placeholder={t('admin.linkProduct.searchProduct')}
|
||||
required
|
||||
/>
|
||||
{searching && <p className="loading-text">Buscando...</p>}
|
||||
{searching && <p className="loading-text">{t('admin.linkProduct.searching')}</p>}
|
||||
|
||||
{productResults.length > 0 && !selectedProduct && (
|
||||
<div className="medicine-search-results">
|
||||
@@ -356,9 +358,9 @@ function PharmacyProductLink() {
|
||||
<div className="selected-medicine-info">
|
||||
<p>✅ Selected: <strong>{selectedProduct.product_name || selectedProduct.name}</strong></p>
|
||||
<p className="medicine-details">
|
||||
{selectedProduct.brand && `Marca: ${selectedProduct.brand} • `}
|
||||
{selectedProduct.brands && `Marca: ${selectedProduct.brands} • `}
|
||||
{selectedProduct.price != null && `Precio: ${selectedProduct.price}€ • `}
|
||||
{selectedProduct.brand && `${t('admin.linkProduct.brand')} ${selectedProduct.brand} • `}
|
||||
{selectedProduct.brands && `${t('admin.linkProduct.brand')} ${selectedProduct.brands} • `}
|
||||
{selectedProduct.price != null && `${t('admin.linkProduct.price')} ${selectedProduct.price}€ • `}
|
||||
{getSourceBadge(selectedProduct.source || 'parapharmacy')}
|
||||
{' '}
|
||||
{selectedProduct._id || selectedProduct.id || selectedProduct.nregistro}
|
||||
@@ -371,7 +373,7 @@ function PharmacyProductLink() {
|
||||
setProductSearch('');
|
||||
}}
|
||||
>
|
||||
Cambiar producto
|
||||
{t('admin.linkProduct.changeProduct')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -379,7 +381,7 @@ function PharmacyProductLink() {
|
||||
|
||||
<div className="form-row">
|
||||
<div className="form-group">
|
||||
<label>Precio (€)</label>
|
||||
<label>{t('admin.linkProduct.priceInput')}</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
@@ -390,7 +392,7 @@ function PharmacyProductLink() {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Stock</label>
|
||||
<label>{t('admin.linkProduct.stock')}</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.stock}
|
||||
@@ -402,21 +404,21 @@ function PharmacyProductLink() {
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn-primary">
|
||||
Vincular Producto
|
||||
{t('admin.linkProduct.linkBtn')}
|
||||
</button>
|
||||
<button type="button" className="btn-secondary" onClick={resetForm}>
|
||||
Reiniciar
|
||||
{t('admin.linkProduct.reset')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{selectedPharmacy && (
|
||||
<div className="pharmacy-medicines-section">
|
||||
<h3>Productos en {selectedPharmacy.name}</h3>
|
||||
<h3>{t('admin.linkProduct.productsIn')} {selectedPharmacy.name}</h3>
|
||||
{loading ? (
|
||||
<div className="loading">Cargando...</div>
|
||||
<div className="loading">{t('admin.linkProduct.loading')}</div>
|
||||
) : pharmacyProducts.length === 0 ? (
|
||||
<p className="empty-state">Aún no hay productos vinculados a esta farmacia.</p>
|
||||
<p className="empty-state">{t('admin.linkProduct.empty')}</p>
|
||||
) : (
|
||||
<div className="admin-list">
|
||||
{pharmacyProducts.map((pp) => (
|
||||
@@ -427,7 +429,7 @@ function PharmacyProductLink() {
|
||||
{getSourceBadge(pp.product_source)}
|
||||
</h4>
|
||||
<p>
|
||||
<strong>Precio:</strong> {pp.price ? `€${parseFloat(pp.price).toFixed(2)}` : 'No definido'} •
|
||||
<strong>{t('admin.linkProduct.priceLabel')}</strong> {pp.price ? `€${parseFloat(pp.price).toFixed(2)}` : t('admin.linkProduct.undefined')} •
|
||||
<strong> Stock:</strong> {pp.stock || 0}
|
||||
</p>
|
||||
</div>
|
||||
@@ -435,17 +437,17 @@ function PharmacyProductLink() {
|
||||
<button
|
||||
className="btn-edit"
|
||||
onClick={() => {
|
||||
const newPrice = prompt('Introduce nuevo precio:', pp.price || '');
|
||||
const newStock = prompt('Introduce nuevo stock:', pp.stock || '0');
|
||||
const newPrice = prompt(t('admin.linkProduct.newPrice'), pp.price || '');
|
||||
const newStock = prompt(t('admin.linkProduct.newStock'), pp.stock || '0');
|
||||
if (newPrice !== null && newStock !== null) {
|
||||
handleUpdate(pp.id, newPrice ? parseFloat(newPrice) : null, parseInt(newStock) || 0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Actualizar
|
||||
{t('admin.linkProduct.update')}
|
||||
</button>
|
||||
<button className="btn-delete" onClick={() => handleDelete(pp.id)}>
|
||||
Eliminar
|
||||
{t('admin.linkProduct.delete')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user