Restructure with Turborepo
Run Tests on Branches / Backend Tests (push) Successful in 3m38s
Run Tests on Branches / Frontend Tests (push) Successful in 3m28s

This commit is contained in:
Antoni Nuñez Romeu
2026-07-06 15:51:53 +02:00
parent f66cafbbc3
commit 190b3d163d
277 changed files with 53253 additions and 0 deletions
+149
View File
@@ -0,0 +1,149 @@
.app {
height: 100dvh;
max-width: 48rem;
margin: 0 auto;
display: flex;
flex-direction: column;
overflow: hidden;
}
.app-content {
flex: 1;
min-height: 0;
overflow-y: auto;
overscroll-behavior-y: contain;
}
/* Mobile-specific styles */
.mobile-view {
width: 100%;
padding: 0;
margin: 0;
}
/* Desktop-specific styles */
.desktop-view {
max-width: 100%;
padding: 0 var(--margin-main);
}
/* Mobile-specific view adjustments */
@media (max-width: 768px) {
.app-logo-wrapper {
flex-direction: column;
}
.home-card--scan {
min-height: 4.25rem;
padding: 0.75rem 1.25rem;
}
.home-card-icon {
width: 2.75rem;
height: 2.75rem;
}
}
/* Tablet-specific styles */
@media (min-width: 769px) and (max-width: 1024px) {
.home-card {
min-height: 4rem;
padding: 0.625rem 1rem;
}
}
/* Desktop-specific styles */
@media (min-width: 1025px) {
.app-content {
padding: 0 5rem;
}
.home-card {
min-height: 3.5rem;
padding: 0.5rem 0.875rem;
}
}
body {
min-height: 100vh;
font-size: calc(16px + 0.5vmin);
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
color: var(--on-surface);
background-color: var(--surface-container-lowest);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Touch target sizing for mobile */
@media (max-width: 768px) {
a, button {
min-height: 4rem;
padding: 1rem;
}
}
/* Card styling improvements */
.home-card {
width: 100%;
max-width: 28rem;
min-height: fit-content;
transition: transform 0.15s, box-shadow 0.15s;
}
.home-card:hover {
transform: translateY(-3px);
box-shadow: 0 1px 12px rgba(0, 0, 0, 0.1);
}
/* Fluid typography */
.home-desc {
font-size: clamp(1rem, 100vw, 1.5rem);
max-width: 100%;
}
.home-card-label {
font-size: clamp(1rem, 100vw, 1.25rem);
}
/* Global button styles using pastel variables */
button,
.btn {
appearance: none;
background: var(--primary);
color: var(--on-primary);
border: none;
padding: 0.6rem 1rem;
border-radius: var(--radius);
box-shadow: var(--primary-shadow);
transition: background-color 160ms ease, transform 120ms ease, box-shadow 160ms ease;
cursor: pointer;
}
button:hover,
.btn:hover {
background: var(--primary-hover);
transform: translateY(-1px);
}
button:focus,
.btn:focus {
outline: none;
box-shadow: 0 0 0 6px var(--primary-ring);
}
/* Outline / subtle buttons */
.btn--outline {
background: transparent;
color: var(--on-secondary);
border: 1px solid var(--secondary-container);
}
.btn--secondary {
background: var(--secondary);
color: var(--on-secondary);
}
.btn--ghost {
background: transparent;
color: var(--on-surface);
}
+163
View File
@@ -0,0 +1,163 @@
import React, { useState, useEffect } from 'react';
import './App.css';
import HomeView from './views/HomeView';
import SearchView from './views/SearchView';
import ScannerView from './views/ScannerView';
import AlertsView from './views/AlertsView';
import ProfileView from './views/ProfileView';
import AdminView from './views/AdminView';
import LoginModal from './components/LoginModal';
import SavedNotifications from './components/SavedNotifications';
import BottomNav from './components/BottomNav';
function App() {
const [screen, setScreen] = useState('home');
const [currentUser, setCurrentUser] = useState(null);
const [authChecked, setAuthChecked] = useState(false);
const [showLogin, setShowLogin] = useState(false);
const [showSaved, setShowSaved] = useState(false);
const [screenSize, setScreenSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
// Device detection
const isMobile = screenSize.width <= 768;
const isTablet = screenSize.width > 768 && screenSize.width <= 1024;
const isDesktop = screenSize.width > 1024;
useEffect(() => {
// Set initial screen size
const handleResize = () => {
setScreenSize({
width: window.innerWidth,
height: window.innerHeight
});
};
fetch('/api/auth/check')
.then(r => r.json())
.then(data => { if (data.authenticated) setCurrentUser(data.user); })
.catch(() => {})
.finally(() => setAuthChecked(true));
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
function handleLogin(user) {
setCurrentUser(user);
setShowLogin(false);
}
async function handleLogout() {
await fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
setCurrentUser(null);
setScreen('home');
}
function handleProfileSaved(updated) {
setCurrentUser(prev => ({ ...prev, ...updated }));
}
function handleAdminClick() {
setScreen('admin');
}
const isLoggedIn = Boolean(currentUser);
function handleNavChange(tab) {
if (tab === 'home') { setScreen('home'); return; }
if (tab === 'search') { setScreen('search'); return; }
if (tab === 'scan') { setScreen('scan'); return; }
if (tab === 'alerts') {
if (currentUser) setScreen('alerts');
else setShowLogin(true);
return;
}
if (tab === 'profile') {
if (currentUser) setScreen('profile');
else setShowLogin(true);
return;
}
}
let activeView;
let deviceClass = isMobile ? 'mobile-view' : 'desktop-view';
switch (screen) {
case 'profile':
activeView = (
<ProfileView
currentUser={currentUser}
onProfileSaved={handleProfileSaved}
onShowSaved={() => setShowSaved(true)}
onLogout={handleLogout}
onAdminClick={handleAdminClick}
/>
);
break;
case 'alerts':
activeView = <AlertsView />;
break;
case 'search':
activeView = (
<SearchView
currentUser={currentUser}
onLoginRequest={() => setShowLogin(true)}
/>
);
break;
case 'scan':
activeView = (
<ScannerView
onClose={() => setScreen('home')}
onSelectMedicine={(name) => {
setScreen('home');
}}
/>
);
break;
case 'admin':
activeView = <AdminView />;
break;
default:
activeView = (
<HomeView
currentUser={currentUser}
onLoginRequest={() => setShowLogin(true)}
onScanClick={() => setScreen('scan')}
onSearchClick={() => setScreen('search')}
/>
);
break;
}
return (
<div className={`app ${deviceClass}`}>
<div className="app-content">
{activeView}
</div>
<BottomNav
activeTab={screen}
onChange={handleNavChange}
isLoggedIn={Boolean(currentUser)}
badgeCount={currentUser ? 2 : 0}
/>
{showLogin && (
<LoginModal
onLogin={handleLogin}
onClose={() => setShowLogin(false)}
/>
)}
{showSaved && currentUser && (
<SavedNotifications onClose={() => setShowSaved(false)} />
)}
</div>
);
}
export default App;
+94
View File
@@ -0,0 +1,94 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, act } from '@testing-library/react'
import HomeView from './views/HomeView.jsx'
import SearchView from './views/SearchView.jsx'
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
describe('HomeView', () => {
it('renders two action buttons on the home screen', () => {
const onSearch = vi.fn()
const onScan = vi.fn()
render(<HomeView onSearchClick={onSearch} onScanClick={onScan} />)
expect(screen.getByRole('button', { name: /buscar medicamento/i })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /escanear tsi/i })).toBeInTheDocument()
})
it('calls onSearchClick when Buscar Medicamento is clicked', async () => {
const onSearch = vi.fn()
render(<HomeView onSearchClick={onSearch} onScanClick={vi.fn()} />)
fireEvent.click(screen.getByRole('button', { name: /buscar medicamento/i }))
expect(onSearch).toHaveBeenCalledTimes(1)
})
})
describe('SearchView', () => {
it('renders search bar with placeholder', () => {
render(<SearchView />)
expect(screen.getByPlaceholderText(/escriba el nombre del medicamento/i)).toBeInTheDocument()
})
it('does not fetch for queries shorter than 2 chars', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch')
render(<SearchView />)
fireEvent.change(screen.getByPlaceholderText(/escriba el nombre del medicamento/i), {
target: { value: 'a' },
})
await act(async () => {
await vi.runAllTimersAsync()
})
expect(fetchMock).not.toHaveBeenCalled()
})
it('fetches and displays results for valid query', async () => {
const medicines = [
{ id: 'REG001', name: 'Ibuprofeno 400mg', active_ingredient: 'Ibuprofeno', dosage: '400mg', form: 'Comprimido' },
]
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
json: async () => medicines,
})
render(<SearchView />)
fireEvent.change(screen.getByPlaceholderText(/escriba el nombre del medicamento/i), {
target: { value: 'ibu' },
})
await act(async () => {
await vi.runAllTimersAsync()
})
expect(screen.getByText('Ibuprofeno 400mg')).toBeInTheDocument()
})
it('clears results when query is cleared after a search', async () => {
const medicines = [
{ id: 'REG001', name: 'Ibuprofeno 400mg', active_ingredient: 'Ibuprofeno', dosage: '400mg', form: 'Comprimido' },
]
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
json: async () => medicines,
})
render(<SearchView />)
const input = screen.getByPlaceholderText(/escriba el nombre del medicamento/i)
fireEvent.change(input, { target: { value: 'ibu' } })
await act(async () => { await vi.runAllTimersAsync() })
expect(screen.getByText('Ibuprofeno 400mg')).toBeInTheDocument()
fireEvent.change(input, { target: { value: '' } })
await act(async () => { await vi.runAllTimersAsync() })
expect(screen.queryByText('Ibuprofeno 400mg')).not.toBeInTheDocument()
})
})
Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

+143
View File
@@ -0,0 +1,143 @@
.bottom-nav {
display: flex;
justify-content: space-around;
align-items: flex-end;
width: 100%;
max-width: 48rem;
z-index: 50;
padding: 0.25rem 0.5rem calc(0.5rem + env(safe-area-inset-bottom));
background: var(--surface-container-lowest);
box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
border-radius: var(--radius-lg) var(--radius-lg) 0 0;
height: 5.5rem;
flex-shrink: 0;
margin: 0 auto;
}
/* Desktop navigation - full width */
@media (min-width: 1025px) {
.bottom-nav {
max-width: 100%;
padding: 0.25rem 2rem calc(0.5rem + env(safe-area-inset-bottom));
border-radius: var(--radius-lg) var(--radius-lg) 0 0;
}
}
.bottom-nav-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
gap: 0.15rem;
padding: 0.25rem 0.5rem;
background: transparent;
border: none;
cursor: pointer;
color: var(--on-surface-variant);
font: inherit;
-webkit-tap-highlight-color: transparent;
transition: color 0.15s;
position: relative;
min-width: 3.5rem;
}
.bottom-nav-item.disabled {
opacity: 0.4;
cursor: not-allowed;
}
.nav-icon-wrap {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.75rem;
height: 2.75rem;
border-radius: var(--radius-full);
color: inherit;
position: relative;
}
.nav-fab {
display: inline-flex;
align-items: center;
justify-content: center;
width: 3.5rem;
height: 3.5rem;
border-radius: var(--radius-full);
/* Stronger, brighter blue to make scan button easy to find */
background: #2b5bb5;
color: #ffffff;
box-shadow: 0 8px 26px rgba(43, 91, 181, 0.32);
margin-top: -1.5rem;
transition: transform 0.12s, box-shadow 160ms ease;
}
.nav-fab:active {
transform: scale(0.92);
}
.nav-fab:hover {
transform: translateY(-2px);
box-shadow: 0 12px 36px rgba(43, 91, 181, 0.36);
}
.nav-fab:focus {
outline: none;
box-shadow: 0 0 0 6px rgba(43,91,181,0.12), 0 8px 26px rgba(43, 91, 181, 0.32);
}
.nav-badge {
position: absolute;
top: 0;
right: -2px;
width: 1.125rem;
height: 1.125rem;
background: var(--error);
color: var(--on-error);
font-size: 0.625rem;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-full);
border: 2px solid var(--surface-container-lowest);
line-height: 1;
}
.nav-label {
font-size: 0.7rem;
font-weight: 500;
line-height: 1;
color: var(--on-surface-variant);
}
.nav-label--active {
color: var(--primary);
font-weight: 700;
}
.nav-indicator {
width: 0.375rem;
height: 0.375rem;
background: var(--primary);
border-radius: var(--radius-full);
margin-top: 0.125rem;
}
.bottom-nav-item.active .nav-icon-wrap {
color: var(--primary);
}
.bottom-nav-item.active .nav-icon-wrap svg {
stroke-width: 2.5;
}
.bottom-nav-item:hover {
color: var(--primary);
background: transparent;
font-weight: 700;
}
.nav-elevated.active .nav-label {
color: var(--tertiary);
}
@@ -0,0 +1,58 @@
import { IconHome, IconSearch, IconScan, IconBell, IconUser } from './icons';
import './BottomNav.css';
function BottomNav({ activeTab, onChange, isLoggedIn, badgeCount }) {
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 },
];
return (
<nav className="bottom-nav" aria-label="Navegación principal">
{tabs.map(({ id, label, Icon, elevated, badge, badgeCount: count, requiresAuth }) => {
const disabled = requiresAuth && !isLoggedIn;
const isActive = activeTab === id;
return (
<button
key={id}
type="button"
className={[
'bottom-nav-item',
isActive ? 'active' : '',
disabled ? 'disabled' : '',
elevated ? 'nav-elevated' : '',
].filter(Boolean).join(' ')}
onClick={() => {
if (!disabled) onChange(id);
}}
disabled={disabled}
aria-current={isActive ? 'page' : undefined}
aria-label={label}
>
{elevated ? (
<div className="nav-fab">
<Icon size={28} />
</div>
) : (
<span className="nav-icon-wrap">
<Icon size={26} />
{badge && (
<span className="nav-badge">{count}</span>
)}
</span>
)}
<span className={`nav-label${isActive && !elevated ? ' nav-label--active' : ''}`}>
{label}
</span>
{isActive && !elevated && <span className="nav-indicator" />}
</button>
);
})}
</nav>
);
}
export default BottomNav;
+173
View File
@@ -0,0 +1,173 @@
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(28, 25, 23, 0.45);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
backdrop-filter: blur(2px);
animation: fadeIn 0.15s ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.modal-box {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 2rem 2.25rem 1.75rem;
width: 100%;
max-width: 360px;
box-shadow: 0 20px 60px rgba(28, 25, 23, 0.18);
animation: slideUp 0.18s ease;
}
@keyframes slideUp {
from { transform: translateY(12px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.modal-tabs {
display: flex;
gap: 0.25rem;
background: var(--surface-muted);
border: 1px solid var(--border);
border-radius: 999px;
padding: 4px;
margin-bottom: 1.25rem;
}
.modal-tab {
flex: 1;
background: transparent;
border: none;
padding: 0.5rem 0.85rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-muted);
transition: background 0.15s, color 0.15s, box-shadow 0.15s;
}
.modal-tab.is-active {
background: var(--surface);
color: var(--primary);
box-shadow: 0 1px 3px rgba(28, 25, 23, 0.08);
}
.modal-tab:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.modal-box h2 {
margin: 0 0 0.25rem;
font-size: 1.35rem;
font-weight: 700;
color: var(--text-main);
}
.modal-hint {
margin: 0.35rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
}
.modal-sub {
margin: 0 0 1.5rem;
font-size: 0.875rem;
color: var(--text-muted);
}
.modal-field {
display: flex;
flex-direction: column;
gap: 0.35rem;
margin-bottom: 1rem;
}
.modal-field label {
font-size: 0.82rem;
font-weight: 600;
color: var(--text-muted);
}
.modal-field input {
padding: 0.6rem 0.85rem;
border: 1px solid var(--border);
border-radius: calc(var(--radius) - 4px);
background: var(--surface-muted);
color: var(--text-main);
font-size: 0.95rem;
outline: none;
transition: border-color 0.15s;
}
.modal-field input:focus {
border-color: var(--primary);
}
.modal-field input:disabled {
opacity: 0.6;
}
.modal-error {
font-size: 0.82rem;
color: #b91c1c;
margin: 0.25rem 0 0.75rem;
}
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 0.65rem;
margin-top: 1.35rem;
}
.modal-cancel {
background: transparent;
border: 1px solid var(--border);
color: var(--text-muted);
padding: 0.55rem 1.1rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.875rem;
font-weight: 600;
transition: background 0.15s, color 0.15s;
}
.modal-cancel:hover:not(:disabled) {
background: var(--surface-muted);
color: var(--text-main);
}
.modal-submit {
background: var(--primary);
border: none;
color: #fff;
padding: 0.55rem 1.35rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.875rem;
font-weight: 600;
transition: opacity 0.15s;
}
.modal-submit:hover:not(:disabled) {
opacity: 0.88;
}
.modal-submit:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.modal-cancel:disabled {
opacity: 0.5;
cursor: not-allowed;
}
+154
View File
@@ -0,0 +1,154 @@
import React, { useState, useEffect, useRef } from 'react';
import './LoginModal.css';
function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
const [mode, setMode] = useState(initialMode === 'register' ? 'register' : 'login');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const usernameRef = useRef(null);
useEffect(() => {
usernameRef.current?.focus();
function handleKey(e) { if (e.key === 'Escape') onClose(); }
document.addEventListener('keydown', handleKey);
return () => document.removeEventListener('keydown', handleKey);
}, [onClose]);
useEffect(() => {
setError('');
}, [mode]);
async function handleSubmit(e) {
e.preventDefault();
const u = username.trim();
if (!u || !password) return;
if (mode === 'register' && password.length < 8) {
setError('La contraseña debe tener al menos 8 caracteres');
return;
}
setLoading(true);
setError('');
try {
const endpoint = mode === 'register' ? '/api/auth/register' : '/api/auth/login';
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ username: u, password }),
});
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'));
} else {
onLogin(data.user);
}
} catch {
setError('Error de red — inténtalo de nuevo');
} finally {
setLoading(false);
}
}
const isRegister = mode === 'register';
return (
<div className="modal-overlay" onClick={onClose}>
<div
className="modal-box"
onClick={e => e.stopPropagation()}
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
>
<div className="modal-tabs" role="tablist">
<button
type="button"
role="tab"
aria-selected={!isRegister}
className={`modal-tab${!isRegister ? ' is-active' : ''}`}
onClick={() => setMode('login')}
disabled={loading}
>
Iniciar sesión
</button>
<button
type="button"
role="tab"
aria-selected={isRegister}
className={`modal-tab${isRegister ? ' is-active' : ''}`}
onClick={() => setMode('register')}
disabled={loading}
>
Crear cuenta
</button>
</div>
<h2 id="modal-title">{isRegister ? 'Crea tu cuenta' : 'Bienvenido de nuevo'}</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.'}
</p>
<form onSubmit={handleSubmit} noValidate>
<div className="modal-field">
<label htmlFor="modal-username">Usuario</label>
<input
id="modal-username"
type="text"
value={username}
onChange={e => setUsername(e.target.value)}
autoComplete="username"
ref={usernameRef}
disabled={loading}
minLength={isRegister ? 3 : undefined}
maxLength={isRegister ? 32 : undefined}
/>
{isRegister && (
<p className="modal-hint">332 caracteres: letras, dígitos o guión bajo.</p>
)}
</div>
<div className="modal-field">
<label htmlFor="modal-password">Contraseña</label>
<input
id="modal-password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
autoComplete={isRegister ? 'new-password' : 'current-password'}
disabled={loading}
minLength={isRegister ? 8 : undefined}
/>
{isRegister && (
<p className="modal-hint">Al menos 8 caracteres.</p>
)}
</div>
{error && <p className="modal-error">{error}</p>}
<div className="modal-actions">
<button
type="button"
className="modal-cancel"
onClick={onClose}
disabled={loading}
>
Cancelar
</button>
<button
type="submit"
className="modal-submit"
disabled={loading || !username.trim() || !password}
>
{loading
? (isRegister ? 'Creando…' : 'Iniciando sesión…')
: (isRegister ? 'Crear cuenta' : 'Iniciar sesión')}
</button>
</div>
</form>
</div>
</div>
);
}
export default LoginModal;
@@ -0,0 +1,143 @@
.medicine-results {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1rem;
margin-top: 0.5rem;
max-height: 60vh;
overflow-y: auto;
overscroll-behavior: contain;
animation: fadeInUp 0.5s ease-out;
}
.medicine-card {
background: var(--surface-container-lowest);
border-radius: var(--radius-md);
padding: 1.25rem;
cursor: pointer;
transition: transform 0.15s, box-shadow 0.15s;
border: 1px solid var(--outline-variant);
display: flex;
flex-direction: column;
justify-content: space-between;
box-shadow: var(--shadow-soft);
}
.medicine-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
border-color: var(--primary);
}
.medicine-card-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 0.75rem;
}
.medicine-card h3 {
color: var(--on-surface);
font-size: 1.15rem;
font-weight: 700;
letter-spacing: -0.01em;
flex: 1;
margin: 0;
}
.notify-bell {
background: var(--surface-container-low);
border: 1px solid var(--outline-variant);
border-radius: var(--radius-full);
width: 2.75rem;
height: 2.75rem;
cursor: pointer;
font-size: 1.1rem;
line-height: 1;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
position: relative;
z-index: 1;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.15s, border-color 0.15s, transform 0.15s;
}
.notify-bell:hover:not(:disabled) {
border-color: var(--primary);
transform: scale(1.05);
}
.notify-bell:active:not(:disabled) {
transform: scale(0.95);
}
.notify-bell:disabled {
opacity: 0.55;
cursor: progress;
}
.notify-bell--on {
background: var(--primary);
border-color: var(--primary);
}
.notify-bell--locked {
opacity: 0.55;
}
.notify-error {
margin-top: 0.5rem;
font-size: 0.78rem;
color: var(--error);
}
.medicine-card-body {
margin-bottom: 1.15rem;
}
.medicine-card-body p {
font-size: 0.9rem;
color: var(--on-surface-variant);
line-height: 1.55;
margin-bottom: 0.25rem;
}
.medicine-card-body strong {
color: var(--on-surface);
font-weight: 600;
}
.medicine-card-footer {
padding-top: 1rem;
border-top: 1px solid var(--outline-variant);
}
.view-pharmacies {
color: var(--primary);
font-weight: 600;
font-size: 0.9rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.view-pharmacies::after {
content: "→";
transition: transform 0.2s;
}
.medicine-card:hover .view-pharmacies::after {
transform: translateX(4px);
}
.no-results {
text-align: center;
padding: 2.5rem 1.5rem;
background: var(--surface-container-low);
border-radius: var(--radius-md);
color: var(--on-surface-variant);
border: 1px dashed var(--outline-variant);
}
@@ -0,0 +1,114 @@
import React, { useEffect, useState } from 'react';
import './MedicineResults.css';
import {
pushSupported,
isSubscribedLocally,
subscribeToPush,
unsubscribeFromPush,
} from '../utils/notifications.js';
function MedicineResults({ medicines, onSelect, query, currentUser, onLoginRequest }) {
if (medicines.length === 0 && query.length >= 2) {
return (
<div className="no-results">
<p>No se encontraron medicamentos para "{query}"</p>
</div>
);
}
return (
<div className="medicine-results">
{medicines.map((medicine) => (
<MedicineCard
key={medicine.nregistro || medicine.id}
medicine={medicine}
onSelect={onSelect}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
))}
</div>
);
}
function MedicineCard({ medicine, onSelect, currentUser, onLoginRequest }) {
const nregistro = medicine.nregistro || medicine.id;
const [subscribed, setSubscribed] = useState(() => isSubscribedLocally(nregistro));
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const supported = pushSupported();
useEffect(() => {
setSubscribed(isSubscribedLocally(nregistro));
}, [nregistro]);
async function handleBell(e) {
e.stopPropagation();
if (!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).');
return;
}
if (busy) return;
setBusy(true);
setError(null);
try {
if (subscribed) {
await unsubscribeFromPush(nregistro);
setSubscribed(false);
} else {
await subscribeToPush(nregistro, medicine.name);
setSubscribed(true);
}
} catch (err) {
console.error('[notify] toggle failed:', err);
setError(err.message || 'No se pudo actualizar la suscripción');
} finally {
setBusy(false);
}
}
return (
<div className="medicine-card" onClick={() => onSelect(medicine)}>
<div className="medicine-card-header">
<h3>{medicine.name}</h3>
<button
type="button"
className={`notify-bell${subscribed && currentUser ? ' notify-bell--on' : ''}${!currentUser ? ' notify-bell--locked' : ''}`}
onClick={handleBell}
disabled={busy}
aria-pressed={subscribed && !!currentUser}
aria-label={
!currentUser
? 'Inicia sesión para activar notificaciones'
: subscribed
? 'Desactivar notificaciones para este medicamento'
: 'Notificarme cuando esté disponible'
}
title={
!currentUser
? 'Inicia sesión para activar notificaciones'
: subscribed
? 'Notificaciones activadas — clic para desactivar'
: 'Notificarme cuando este medicamento esté en una farmacia'
}
>
{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>
{error && <p className="notify-error" onClick={e => e.stopPropagation()}>{error}</p>}
</div>
<div className="medicine-card-footer">
<span className="view-pharmacies">Ver farmacias </span>
</div>
</div>
);
}
export default MedicineResults;
@@ -0,0 +1,166 @@
.pharmacy-list {
margin-top: 1rem;
}
.pharmacy-list-title {
font-size: 1.25rem;
font-weight: 700;
margin-bottom: 1rem;
color: var(--on-surface);
display: flex;
align-items: center;
gap: 0.5rem;
}
.pharmacy-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1rem;
}
.pharmacy-card {
background: var(--surface-container-lowest);
border-radius: var(--radius-md);
padding: 1.25rem;
border: 1px solid var(--outline-variant);
transition: transform 0.15s, box-shadow 0.15s;
box-shadow: var(--shadow-soft);
}
.pharmacy-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
border-color: var(--primary);
}
.pharmacy-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 0.75rem;
}
.pharmacy-header h4 {
color: var(--on-surface);
font-weight: 700;
margin: 0;
font-size: 1.05rem;
flex: 1;
}
.pharmacy-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.pharmacy-distance {
flex-shrink: 0;
background: rgba(0, 69, 13, 0.08);
color: var(--primary);
font-size: 0.78rem;
font-weight: 700;
padding: 0.3rem 0.7rem;
border-radius: var(--radius-full);
}
.pharmacy-card:hover .pharmacy-header h4 {
color: var(--primary);
}
.pharmacy-details {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.pharmacy-address,
.pharmacy-phone {
color: var(--on-surface-variant);
font-size: 0.9rem;
margin: 0;
line-height: 1.45;
}
.pharmacy-hours {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
font-weight: 600;
margin: 0;
padding: 0.25rem 0;
}
.pharmacy-hours-dot {
display: inline-block;
width: 0.5rem;
height: 0.5rem;
border-radius: var(--radius-full);
background: currentColor;
}
.pharmacy-hours--open {
color: var(--primary);
}
.pharmacy-hours--closed {
color: var(--on-surface-variant);
}
.pharmacy-pricing {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px solid var(--outline-variant);
}
.price {
font-size: 1.15rem;
font-weight: 700;
color: var(--primary);
}
.stock {
font-size: 0.72rem;
padding: 0.35rem 0.8rem;
border-radius: var(--radius-full);
font-weight: 700;
text-transform: uppercase;
}
.stock.in-stock {
background: rgba(0, 69, 13, 0.1);
color: var(--primary);
}
.stock.low-stock {
background: rgba(180, 83, 9, 0.12);
color: #b45309;
}
.stock.out-of-stock {
background: rgba(186, 26, 26, 0.1);
color: var(--error);
}
.loading-pharmacies,
.no-pharmacies {
text-align: center;
padding: 2.5rem 1.5rem;
background: var(--surface-container-low);
border-radius: var(--radius-md);
color: var(--on-surface-variant);
border: 1px solid var(--outline-variant);
margin-top: 1rem;
}
@media (max-width: 768px) {
.pharmacy-grid {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,164 @@
import React, { useEffect, useState } from 'react';
import './PharmacyList.css';
import { haversineKm, formatDistance } from '../utils/geo';
import { getOpenStatus } from '../utils/hours';
import {
pushSupported,
isSubscribedLocally,
subscribeToPush,
unsubscribeFromPush,
} from '../utils/notifications.js';
function PharmacyList({ pharmacies, loading, userPosition, medicine, currentUser, onLoginRequest }) {
if (loading) {
return (
<div className="loading-pharmacies">
<p>Cargando farmacias...</p>
</div>
);
}
if (pharmacies.length === 0) {
return (
<div className="no-pharmacies">
<p>No se encontraron farmacias con este medicamento</p>
</div>
);
}
return (
<div className="pharmacy-list">
<h3 className="pharmacy-list-title">
Disponible en {pharmacies.length} {pharmacies.length === 1 ? 'farmacia' : 'farmacias'}
</h3>
<div className="pharmacy-grid">
{pharmacies.map((pharmacy) => {
const distanceKm =
userPosition && pharmacy.latitude != null && pharmacy.longitude != null
? haversineKm(userPosition.lat, userPosition.lon, pharmacy.latitude, pharmacy.longitude)
: null;
return (
<PharmacyCard
key={pharmacy.id}
pharmacy={pharmacy}
distanceKm={distanceKm}
medicine={medicine}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
);
})}
</div>
</div>
);
}
function PharmacyCard({ pharmacy, distanceKm, medicine, currentUser, onLoginRequest }) {
const nregistro = medicine?.nregistro || medicine?.id;
const supported = pushSupported();
const outOfStock = pharmacy.stock !== undefined && pharmacy.stock <= 0;
const showBell = Boolean(medicine && nregistro && outOfStock);
const [subscribed, setSubscribed] = useState(() =>
showBell ? isSubscribedLocally(nregistro, pharmacy.id) : false
);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (showBell) setSubscribed(isSubscribedLocally(nregistro, pharmacy.id));
}, [nregistro, pharmacy.id, showBell]);
async function handleBell(e) {
e.stopPropagation();
if (!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).');
return;
}
if (busy) return;
setBusy(true);
setError(null);
try {
if (subscribed) {
await unsubscribeFromPush(nregistro, pharmacy.id);
setSubscribed(false);
} else {
await subscribeToPush(nregistro, medicine.name, pharmacy.id);
setSubscribed(true);
}
} catch (err) {
console.error('[notify] pharmacy toggle failed:', err);
setError(err.message || 'No se pudo actualizar la suscripción');
} finally {
setBusy(false);
}
}
const openStatus = getOpenStatus(pharmacy.opening_hours);
return (
<div className="pharmacy-card">
<div className="pharmacy-header">
<h4>🏥 {pharmacy.name}</h4>
<div className="pharmacy-header-actions">
{distanceKm != null && (
<span className="pharmacy-distance">{formatDistance(distanceKm)}</span>
)}
{showBell && (
<button
type="button"
className={`notify-bell${subscribed && currentUser ? ' notify-bell--on' : ''}${!currentUser ? ' notify-bell--locked' : ''}`}
onClick={handleBell}
disabled={busy}
aria-pressed={subscribed && !!currentUser}
aria-label={
!currentUser
? 'Inicia sesión para activar notificaciones'
: subscribed
? 'Desactivar notificaciones para esta farmacia'
: 'Notificarme cuando llegue a esta farmacia'
}
title={
!currentUser
? 'Inicia sesión para activar notificaciones'
: subscribed
? 'Notificaciones activadas para esta farmacia — clic para desactivar'
: 'Notificarme cuando llegue a esta farmacia'
}
>
{subscribed && currentUser ? '🔔' : '🔕'}
</button>
)}
</div>
</div>
<div className="pharmacy-details">
{openStatus && (
<p className={`pharmacy-hours pharmacy-hours--${openStatus.status}`}>
<span className="pharmacy-hours-dot" /> {openStatus.label}
</p>
)}
<p className="pharmacy-address">📍 {pharmacy.address}</p>
{pharmacy.phone && (
<p className="pharmacy-phone">📞 {pharmacy.phone}</p>
)}
{error && <p className="notify-error">{error}</p>}
<div className="pharmacy-pricing">
{pharmacy.price && (
<span className="price">{parseFloat(pharmacy.price).toFixed(2)}</span>
)}
{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'}
</span>
)}
</div>
</div>
</div>
);
}
export default PharmacyList;
@@ -0,0 +1,45 @@
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
// Fix default marker icon broken by webpack/vite asset bundling
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
});
function PharmacyMap({ pharmacies }) {
const located = pharmacies.filter(p => p.latitude != null && p.longitude != null);
if (located.length === 0) return null;
const center = [
located.reduce((s, p) => s + p.latitude, 0) / located.length,
located.reduce((s, p) => s + p.longitude, 0) / located.length,
];
return (
<div className="pharmacy-map-wrapper" style={{ height: '350px', width: '100%', marginTop: '1rem', borderRadius: '8px', overflow: 'hidden' }}>
<MapContainer center={center} zoom={13} style={{ height: '100%', width: '100%' }} scrollWheelZoom={false}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{located.map(pharmacy => (
<Marker key={pharmacy.id} position={[pharmacy.latitude, pharmacy.longitude]}>
<Popup>
<strong>{pharmacy.name}</strong><br />
{pharmacy.address}
{pharmacy.phone && <><br />{pharmacy.phone}</>}
</Popup>
</Marker>
))}
</MapContainer>
</div>
);
}
export default PharmacyMap;
@@ -0,0 +1,194 @@
.saved-notifications-backdrop {
position: fixed;
inset: 0;
background: rgba(28, 25, 23, 0.55);
display: flex;
align-items: flex-start;
justify-content: center;
padding: 5vh 1rem;
z-index: 1000;
animation: fadeInBackdrop 0.18s ease-out;
}
.saved-notifications-modal {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: 0 24px 60px rgba(28, 25, 23, 0.25);
width: 100%;
max-width: 560px;
max-height: 90vh;
display: flex;
flex-direction: column;
overflow: hidden;
animation: popIn 0.22s ease-out;
}
.saved-notifications-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border);
}
.saved-notifications-header h2 {
margin: 0;
font-size: 1.2rem;
font-weight: 700;
letter-spacing: -0.01em;
color: var(--text-main);
}
.saved-notifications-close {
background: transparent;
border: none;
font-size: 1.6rem;
line-height: 1;
color: var(--text-muted);
cursor: pointer;
padding: 0.25rem 0.5rem;
border-radius: 999px;
transition: background 0.15s, color 0.15s;
}
.saved-notifications-close:hover {
background: var(--surface-muted);
color: var(--text-main);
}
.saved-notifications-body {
overflow-y: auto;
padding: 1rem 1.5rem 1.5rem;
}
.saved-notifications-status,
.saved-notifications-empty,
.saved-notifications-error {
margin: 1.5rem 0;
text-align: center;
color: var(--text-muted);
font-size: 0.95rem;
line-height: 1.5;
}
.saved-notifications-error {
color: #b91c1c;
}
.saved-notifications-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.65rem;
}
.saved-notifications-item {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
padding: 0.85rem 1rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm, 12px);
background: var(--surface-muted, #fafaf9);
}
.saved-notifications-item-main {
flex: 1;
min-width: 0;
}
.saved-notifications-item-name {
font-weight: 600;
color: var(--text-main);
font-size: 0.95rem;
margin-bottom: 0.35rem;
word-break: break-word;
}
.saved-notifications-item-meta {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.82rem;
color: var(--text-muted);
}
.saved-notifications-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.2rem 0.55rem;
border-radius: 999px;
background: var(--secondary-container, #dbe7ff);
color: var(--on-secondary, #06204a);
font-size: 0.75rem;
font-weight: 600;
width: fit-content;
}
.saved-notifications-chip--pharmacy {
background: var(--primary-container, #cfead0);
color: var(--on-primary, #09310a);
}
.saved-notifications-address {
font-size: 0.78rem;
color: var(--text-muted);
}
.saved-notifications-remove {
background: transparent;
border: 1px solid var(--border);
color: var(--text-muted);
padding: 0.45rem 0.85rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 600;
cursor: pointer;
flex-shrink: 0;
transition: background 0.15s, border-color 0.15s, color 0.15s;
touch-action: manipulation;
}
.saved-notifications-remove:hover:not(:disabled) {
border-color: #b91c1c;
color: #b91c1c;
background: rgba(185, 28, 28, 0.06);
}
.saved-notifications-remove:disabled {
opacity: 0.55;
cursor: progress;
}
@keyframes fadeInBackdrop {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes popIn {
from { opacity: 0; transform: translateY(-8px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@media (max-width: 540px) {
.saved-notifications-backdrop {
padding: 2vh 0.5rem;
}
.saved-notifications-modal {
max-height: 95vh;
}
.saved-notifications-header {
padding: 1rem 1.1rem;
}
.saved-notifications-body {
padding: 0.85rem 1.1rem 1.25rem;
}
}
@@ -0,0 +1,113 @@
import React, { useEffect, useState } from 'react';
import './SavedNotifications.css';
function SavedNotifications({ onClose }) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [items, setItems] = useState([]);
const [busyId, setBusyId] = useState(null);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const res = await fetch('/api/notifications/mine', { credentials: 'include' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (cancelled) return;
const merged = [
...(data.pharmacy || []),
...(data.global || []),
].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');
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => { cancelled = true; };
}, []);
async function handleDelete(item) {
const key = `${item.scope}:${item.id}`;
setBusyId(key);
try {
const res = await fetch('/api/notifications/mine', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ scope: item.scope, id: item.id }),
});
if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`);
setItems(prev => prev.filter(i => !(i.scope === item.scope && i.id === item.id)));
} catch (err) {
setError(err.message || 'No se pudo eliminar la notificación');
} finally {
setBusyId(null);
}
}
return (
<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>
</div>
<div className="saved-notifications-body">
{loading && <p className="saved-notifications-status">Cargando</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.
</p>
)}
{!loading && !error && items.length > 0 && (
<ul className="saved-notifications-list">
{items.map(item => {
const key = `${item.scope}:${item.id}`;
return (
<li key={key} className="saved-notifications-item">
<div className="saved-notifications-item-main">
<div className="saved-notifications-item-name">
{item.medicine_name || item.medicine_nregistro}
</div>
<div className="saved-notifications-item-meta">
{item.scope === 'pharmacy' ? (
<>
<span className="saved-notifications-chip saved-notifications-chip--pharmacy">
🏥 {item.pharmacy_name || `Farmacia #${item.pharmacy_id}`}
</span>
{item.pharmacy_address && (
<span className="saved-notifications-address">{item.pharmacy_address}</span>
)}
</>
) : (
<span className="saved-notifications-chip">
Cualquier farmacia
</span>
)}
</div>
</div>
<button
type="button"
className="saved-notifications-remove"
onClick={() => handleDelete(item)}
disabled={busyId === key}
aria-label="Eliminar notificación"
>
{busyId === key ? '…' : 'Eliminar'}
</button>
</li>
);
})}
</ul>
)}
</div>
</div>
</div>
);
}
export default SavedNotifications;
@@ -0,0 +1,64 @@
.search-bar-container {
margin-bottom: 1.5rem;
}
.search-bar {
display: flex;
align-items: center;
background: var(--surface-container-lowest);
border-radius: var(--radius-md);
padding: 0.25rem 1rem;
border: 2px solid var(--outline-variant);
transition: border-color 0.2s;
position: relative;
}
.search-bar:focus-within {
border-color: var(--primary);
}
.search-icon {
color: var(--primary);
font-size: 1.5rem;
margin-right: 0.75rem;
display: flex;
align-items: center;
flex-shrink: 0;
}
.search-input {
flex: 1;
border: none;
background: transparent;
padding: 1rem 0;
font-size: 1.125rem;
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
color: var(--on-surface);
outline: none;
}
.search-input::placeholder {
color: var(--on-surface-variant);
opacity: 0.6;
}
.clear-button {
background: var(--surface-container-low);
border: 1px solid var(--outline-variant);
color: var(--on-surface-variant);
width: 2rem;
height: 2rem;
border-radius: var(--radius-full);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.75rem;
transition: background 0.15s;
margin-left: 0.5rem;
flex-shrink: 0;
}
.clear-button:hover {
background: var(--surface-container);
}
@@ -0,0 +1,36 @@
import React from 'react';
import './SearchBar.css';
function SearchBar({ value, onChange, placeholder }) {
return (
<div className="search-bar-container">
<div className="search-bar">
<span className="search-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
</span>
<input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
className="search-input"
autoFocus
/>
{value && (
<button
className="clear-button"
onClick={() => onChange('')}
aria-label="Limpiar búsqueda"
>
</button>
)}
</div>
</div>
);
}
export default SearchBar;
@@ -0,0 +1,602 @@
.admin-section {
width: 100%;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
flex-wrap: wrap;
gap: 1rem;
}
.section-header h2 {
color: var(--text-main);
margin: 0;
font-weight: 700;
font-size: 1.5rem;
}
.admin-form {
background: var(--surface-muted);
padding: 2rem;
border-radius: var(--radius-sm);
margin-bottom: 2rem;
border: 1px solid var(--border);
}
.admin-form h3 {
color: var(--primary);
margin-top: 0;
margin-bottom: 1.5rem;
font-weight: 700;
}
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
color: var(--text-main);
font-weight: 600;
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.form-group input,
.form-group select {
width: 100%;
padding: 0.85rem 1rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-size: 1rem;
font-family: inherit;
transition: border-color 0.2s, box-shadow 0.2s;
background: var(--surface);
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-ring);
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.form-actions {
display: flex;
gap: 1rem;
margin-top: 1.5rem;
}
.hours-editor {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 1rem 1.25rem 1.25rem;
margin: 0.5rem 0 1rem;
background: var(--surface);
}
.hours-editor legend {
padding: 0 0.5rem;
font-weight: 600;
color: var(--text-main);
}
.hours-editor-hint {
font-size: 0.85rem;
color: var(--text-muted);
margin: 0 0 0.85rem;
}
.hours-row {
display: grid;
grid-template-columns: 7rem 6.5rem 1fr auto 1fr;
align-items: center;
gap: 0.6rem;
padding: 0.35rem 0;
}
.hours-row.is-closed input[type="time"] {
opacity: 0.45;
}
.hours-day {
font-weight: 600;
color: var(--text-main);
font-size: 0.9rem;
}
.hours-closed-toggle {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-size: 0.85rem;
color: var(--text-muted);
cursor: pointer;
}
.hours-sep {
text-align: center;
color: var(--text-muted);
}
.hours-row input[type="time"] {
width: 100%;
padding: 0.45rem 0.6rem;
border: 1px solid var(--border);
border-radius: 8px;
font-size: 0.9rem;
font-family: inherit;
background: var(--surface);
color: var(--text-main);
}
@media (max-width: 600px) {
.hours-row {
grid-template-columns: 1fr 1fr;
grid-template-areas:
"day closed"
"open close";
}
.hours-day { grid-area: day; }
.hours-closed-toggle { grid-area: closed; justify-self: end; }
.hours-row input[type="time"]:first-of-type { grid-area: open; }
.hours-row input[type="time"]:last-of-type { grid-area: close; }
.hours-sep { display: none; }
}
.btn-primary,
.btn-secondary,
.btn-edit,
.btn-delete {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 10px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
font-family: inherit;
}
.btn-primary {
background: var(--primary);
color: white;
}
.btn-primary:hover {
background: var(--primary-hover);
transform: translateY(-1px);
box-shadow: 0 4px 14px var(--primary-shadow);
}
.btn-secondary {
background: var(--surface-muted);
color: var(--text-main);
border: 1px solid var(--border);
}
.btn-secondary:hover {
background: var(--surface-card);
border-color: var(--border-strong);
}
.btn-edit {
background: rgba(4, 120, 87, 0.1);
color: var(--accent);
padding: 0.5rem 1rem;
font-size: 0.85rem;
}
.btn-edit:hover {
background: rgba(4, 120, 87, 0.16);
}
.btn-delete {
background: rgba(239, 68, 68, 0.1);
color: #ef4444;
padding: 0.5rem 1rem;
font-size: 0.85rem;
}
.btn-delete:hover {
background: rgba(239, 68, 68, 0.2);
}
.admin-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.admin-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.25rem 1.5rem;
background: var(--surface-muted);
border-radius: var(--radius-sm);
border: 1px solid var(--border);
transition: border-color 0.2s, box-shadow 0.2s;
}
.admin-item:hover {
border-color: var(--primary);
box-shadow: 0 2px 8px rgba(28, 25, 23, 0.06);
}
.item-content {
flex: 1;
}
.item-content h4 {
color: var(--text-main);
margin: 0 0 0.35rem 0;
font-size: 1.05rem;
font-weight: 600;
}
.item-content p {
margin: 0.2rem 0;
color: var(--text-muted);
font-size: 0.9rem;
}
.item-actions {
display: flex;
gap: 0.5rem;
}
.empty-state {
text-align: center;
color: var(--text-muted);
padding: 2.5rem;
font-style: italic;
background: var(--surface-muted);
border-radius: var(--radius-sm);
border: 1px dashed var(--border-strong);
}
.info-text {
color: var(--text-muted);
margin-bottom: 1rem;
font-size: 0.95rem;
}
.info-box {
background: var(--primary-faint);
padding: 1rem 1.25rem;
margin-bottom: 1.5rem;
border-radius: var(--radius-sm);
border: 1px solid var(--border);
border-left: 4px solid var(--primary);
}
.info-box p {
margin: 0.5rem 0;
color: var(--text-muted);
font-size: 0.95rem;
}
.info-box p:first-child {
margin-top: 0;
}
.info-box p:last-child {
margin-bottom: 0;
}
.medicine-meta {
font-size: 0.8rem;
color: var(--text-muted);
margin-top: 0.5rem;
}
.pharmacy-medicines-section {
margin-top: 2rem;
padding-top: 2rem;
border-top: 1px solid var(--border);
}
.pharmacy-medicines-section h3 {
color: var(--text-main);
font-weight: 700;
margin-bottom: 1rem;
}
/* Medicine search styles */
.loading-text {
color: var(--text-muted);
font-size: 0.9rem;
margin-top: 0.5rem;
font-weight: 500;
}
.medicine-search-results {
position: relative;
max-height: 300px;
overflow-y: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
margin-top: 0.5rem;
background: var(--surface);
box-shadow: var(--glass-shadow);
}
.search-result-item {
padding: 1rem 1.25rem;
cursor: pointer;
border-bottom: 1px solid var(--border);
transition: background-color 0.15s;
}
.search-result-item:last-child {
border-bottom: none;
}
.search-result-item:hover {
background-color: var(--surface-muted);
}
.search-result-item strong {
color: var(--text-main);
display: block;
margin-bottom: 0.25rem;
font-weight: 600;
}
.search-result-item span {
color: var(--text-muted);
font-size: 0.9rem;
}
.selected-medicine-info {
background: var(--primary-faint);
border: 1px solid var(--primary);
border-radius: var(--radius-sm);
padding: 1.25rem;
margin-top: 0.5rem;
}
.selected-medicine-info p {
margin: 0.25rem 0;
}
.selected-medicine-info .medicine-details {
color: var(--text-muted);
font-size: 0.85rem;
margin-top: 0.5rem;
}
.btn-small {
padding: 0.4rem 0.8rem;
font-size: 0.85rem;
background: var(--surface-muted);
color: var(--text-main);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
cursor: pointer;
margin-top: 0.5rem;
transition: background 0.2s, border-color 0.2s;
font-family: inherit;
font-weight: 600;
}
.btn-small:hover {
background: var(--surface-card);
border-color: var(--border-strong);
}
/* Pharmacies: search, region import, list filter */
.pharmacy-tools-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 1.5rem 1.75rem;
margin-bottom: 1.75rem;
box-shadow: 0 1px 2px rgba(28, 25, 23, 0.04);
}
.pharmacy-tools-card h3 {
margin: 0 0 0.35rem 0;
font-size: 1.05rem;
font-weight: 700;
color: var(--text-main);
}
.pharmacy-tools-hint {
font-size: 0.88rem;
color: var(--text-muted);
margin: 0 0 1.25rem 0;
line-height: 1.45;
}
.city-lookup-form {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 0.75rem 1rem;
margin-bottom: 0.75rem;
}
.city-lookup-input-wrap {
flex: 1 1 220px;
margin-bottom: 0;
}
.city-lookup-submit {
flex-shrink: 0;
margin-bottom: 0;
}
.city-lookup-feedback {
font-size: 0.88rem;
margin: 0 0 1.1rem 0;
line-height: 1.45;
}
.city-lookup-feedback.ok {
color: var(--accent);
}
.city-lookup-feedback.err {
color: #b91c1c;
}
.pharmacy-tools-hint a {
color: var(--primary);
text-decoration: underline;
text-underline-offset: 2px;
}
.pharmacy-tools-hint a:hover {
color: var(--primary-hover);
}
.region-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
margin-bottom: 1rem;
}
@media (max-width: 640px) {
.region-grid {
grid-template-columns: 1fr;
}
}
.region-presets {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
margin-bottom: 1rem;
}
.region-presets label {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.region-presets select {
padding: 0.45rem 0.75rem;
border-radius: var(--radius-sm);
border: 1px solid var(--border);
font-family: inherit;
font-size: 0.9rem;
background: var(--surface);
color: var(--text-main);
}
.import-mode-row {
margin-bottom: 1rem;
}
.import-mode-select-wrap {
max-width: 28rem;
margin-bottom: 0;
}
.open-data-url-row {
margin-bottom: 1rem;
}
.pharmacy-tools-hint code {
font-size: 0.85em;
background: var(--surface-muted);
padding: 0.15rem 0.4rem;
border-radius: 4px;
border: 1px solid var(--border);
}
.tool-actions-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 1rem 1.25rem;
}
.tool-actions-row .btn-import-webhook {
margin: 0;
}
.filter-region-toggle {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
color: var(--text-main);
cursor: pointer;
user-select: none;
}
.filter-region-toggle input {
width: 1rem;
height: 1rem;
accent-color: var(--primary);
}
.import-feedback {
margin-top: 1rem;
padding: 0.85rem 1rem;
border-radius: var(--radius-sm);
font-size: 0.9rem;
line-height: 1.5;
}
.import-feedback.success {
background: rgba(4, 120, 87, 0.1);
border: 1px solid rgba(4, 120, 87, 0.25);
color: var(--text-main);
}
.import-feedback.error {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
}
.list-meta {
font-size: 0.88rem;
color: var(--text-muted);
margin: -0.5rem 0 1rem 0;
}
@media (max-width: 768px) {
.form-row {
grid-template-columns: 1fr;
}
.admin-item {
flex-direction: column;
align-items: flex-start;
gap: 1rem;
}
.item-actions {
width: 100%;
}
.item-actions button {
flex: 1;
}
.section-header {
flex-direction: column;
align-items: flex-start;
}
}
@@ -0,0 +1,162 @@
.login-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
padding: 2rem;
animation: fadeInUp 0.8s ease-out;
}
.login-box {
background: var(--surface);
border-radius: var(--radius);
padding: 3rem;
box-shadow: var(--glass-shadow);
border: 1px solid var(--border);
width: 100%;
max-width: 420px;
}
.login-header {
text-align: center;
margin-bottom: 2.5rem;
}
.login-header h2 {
color: var(--text-main);
margin-bottom: 0.5rem;
font-size: 1.85rem;
font-weight: 800;
letter-spacing: -0.02em;
}
.login-header h2::after {
content: "";
display: block;
width: 2.5rem;
height: 3px;
margin: 0.85rem auto 0;
background: var(--primary);
border-radius: 2px;
}
.login-header p {
color: var(--text-muted);
font-size: 0.95rem;
}
.login-form {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.login-form .form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.login-form .form-group label {
color: var(--text-main);
font-weight: 600;
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.login-form .form-group input {
padding: 0.85rem 1rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-size: 1rem;
font-family: inherit;
transition: border-color 0.2s, box-shadow 0.2s, background 0.2s;
background: var(--surface-muted);
}
.login-form .form-group input:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-ring);
background: var(--surface);
}
.login-form .form-group input:disabled {
background: var(--surface-muted);
cursor: not-allowed;
opacity: 0.7;
}
.error-message {
background: #fef2f2;
color: #b91c1c;
padding: 0.75rem 1rem;
border-radius: var(--radius-sm);
border: 1px solid #fecaca;
font-size: 0.9rem;
text-align: center;
font-weight: 500;
}
.login-button {
background: var(--primary);
color: #fff;
border: none;
padding: 0.95rem;
border-radius: var(--radius-sm);
font-size: 1rem;
font-weight: 700;
cursor: pointer;
transition: background 0.2s, transform 0.2s, box-shadow 0.2s;
margin-top: 0.5rem;
font-family: inherit;
}
.login-button:hover:not(:disabled) {
background: var(--primary-hover);
transform: translateY(-1px);
box-shadow: 0 6px 18px var(--primary-shadow);
}
.login-button:disabled {
background: var(--border-strong);
cursor: not-allowed;
}
.login-footer {
margin-top: 2rem;
text-align: center;
}
.help-text {
color: var(--text-muted);
font-size: 0.85rem;
margin: 0.5rem 0;
}
.help-text code {
background: var(--surface-muted);
padding: 0.2rem 0.5rem;
border-radius: 6px;
font-size: 0.85em;
color: var(--primary);
font-weight: 600;
border: 1px solid var(--border);
}
.warning-text {
color: var(--accent-warm);
background: rgba(180, 83, 9, 0.08);
padding: 0.75rem 1rem;
border-radius: var(--radius-sm);
font-size: 0.85rem;
margin-top: 1rem;
border: 1px solid rgba(180, 83, 9, 0.2);
}
@media (max-width: 768px) {
.login-box {
padding: 2rem;
}
}
@@ -0,0 +1,106 @@
import React, { useState } from 'react';
import './LoginForm.css';
function LoginForm({ onLogin }) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Important for sessions
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Inicio de sesión fallido');
}
// Success - notify parent component
onLogin(data.user);
} catch (error) {
console.error('Login error:', error);
setError(error.message || 'Usuario o contraseña inválidos');
} finally {
setLoading(false);
}
};
return (
<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>
</div>
<form onSubmit={handleSubmit} className="login-form">
{error && (
<div className="error-message">
{error}
</div>
)}
<div className="form-group">
<label htmlFor="username">Usuario</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Introduce usuario"
required
autoFocus
disabled={loading}
/>
</div>
<div className="form-group">
<label htmlFor="password">Contraseña</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Introduce contraseña"
required
disabled={loading}
/>
</div>
<button
type="submit"
className="login-button"
disabled={loading || !username || !password}
>
{loading ? 'Iniciando sesión...' : 'Iniciar sesión'}
</button>
</form>
<div className="login-footer">
<p className="help-text">
Credenciales por defecto: <code>admin</code> / <code>admin123</code>
</p>
<p className="warning-text">
¡Cambia la contraseña por defecto tras el primer inicio de sesión!
</p>
</div>
</div>
</div>
);
}
export default LoginForm;
@@ -0,0 +1,102 @@
import React, { useState, useEffect } from 'react';
import './AdminComponents.css';
const SEARCH_DEBOUNCE_MS = 400;
function MedicineManagement() {
const [searchQuery, setSearchQuery] = useState('');
const [medicines, setMedicines] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
const q = searchQuery.trim();
if (q.length < 2) {
setMedicines([]);
setLoading(false);
return;
}
const controller = new AbortController();
const timeoutId = setTimeout(async () => {
setLoading(true);
try {
const response = await fetch(
`/api/medicines/search?q=${encodeURIComponent(q)}`,
{ credentials: 'include', signal: controller.signal }
);
const data = await response.json();
setMedicines(Array.isArray(data) ? data : []);
} catch (error) {
if (error.name === 'AbortError') return;
console.error('Error searching medicines:', error);
alert('Error al buscar medicamentos en la API CIMA');
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}, SEARCH_DEBOUNCE_MS);
return () => {
clearTimeout(timeoutId);
controller.abort();
};
}, [searchQuery]);
return (
<div className="admin-section">
<div className="section-header">
<h2>Buscar Medicamentos (API CIMA)</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>
</div>
<div className="admin-form">
<div className="form-group">
<label>Buscar medicamentos</label>
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Escribe el nombre de un medicamento..."
/>
</div>
</div>
{loading && <div className="loading">Buscando en API CIMA...</div>}
{!loading && medicines.length > 0 && (
<div className="admin-list">
<p className="info-text">Se encontraron {medicines.length} medicamentos</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>
{medicine.dosage && <span><strong>Dosis:</strong> {medicine.dosage}</span>}
{medicine.dosage && medicine.form && ' • '}
{medicine.form && <span><strong>Forma:</strong> {medicine.form}</span>}
</p>
<p className="medicine-meta">
<strong>Laboratorio:</strong> {medicine.laboratory}
<strong> Registro:</strong> {medicine.nregistro}
{medicine.generic ? ' Genérico' : ' Marca'}
</p>
</div>
</div>
))}
</div>
)}
{!loading && searchQuery.trim().length >= 2 && medicines.length === 0 && (
<p className="empty-state">No se encontraron medicamentos con ese nombre.</p>
)}
</div>
);
}
export default MedicineManagement;
@@ -0,0 +1,715 @@
import React, { useState, useEffect, useMemo } from 'react';
import './AdminComponents.css';
import { DAY_KEYS, DAY_LABEL } from '../../utils/hours';
function emptyHoursDraft() {
const draft = {};
for (const day of DAY_KEYS) {
draft[day] = { open: '09:00', close: '21:00', closed: true };
}
return draft;
}
function hoursToDraft(raw) {
let parsed = null;
if (raw) {
try { parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; }
catch { parsed = null; }
}
const draft = {};
for (const day of DAY_KEYS) {
const v = parsed && parsed[day];
if (Array.isArray(v) && v.length === 2) {
draft[day] = { open: v[0], close: v[1], closed: false };
} else {
draft[day] = { open: '09:00', close: '21:00', closed: true };
}
}
return draft;
}
function draftToHours(draft) {
const out = {};
let hasAny = false;
for (const day of DAY_KEYS) {
const d = draft[day];
if (d && !d.closed && d.open && d.close) {
out[day] = [d.open, d.close];
hasAny = true;
} else {
out[day] = null;
}
}
return hasAny ? out : null;
}
/** Distance in metres between two WGS84 points */
function haversineMeters(lat1, lon1, lat2, lon2) {
const R = 6371000;
const toRad = (d) => (d * Math.PI) / 180;
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
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',
},
];
async function geocodeErrorMessage(response) {
const text = await response.text();
let body = {};
try {
body = text ? JSON.parse(text) : {};
} catch {
/* non-JSON */
}
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.';
}
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 'Servicio de geocodificación no encontrado. Actualiza el backend y reinícialo.';
}
return `Búsqueda fallida (HTTP ${response.status}).`;
}
function PharmacyManagement() {
const [pharmacies, setPharmacies] = useState([]);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [showForm, setShowForm] = useState(false);
const [editingPharmacy, setEditingPharmacy] = useState(null);
const [formData, setFormData] = useState({
name: '',
address: '',
phone: '',
latitude: '',
longitude: '',
});
const [hoursDraft, setHoursDraft] = useState(() => emptyHoursDraft());
const [cityQuery, setCityQuery] = useState('');
const [cityLookupLoading, setCityLookupLoading] = useState(false);
const [cityLookupMessage, setCityLookupMessage] = useState(null);
const [regionLat, setRegionLat] = useState('41.5631');
const [regionLon, setRegionLon] = useState('2.0038');
const [regionRadio, setRegionRadio] = useState('1500');
const [regionPreset, setRegionPreset] = useState('rubi');
const [filterByRegion, setFilterByRegion] = useState(false);
const [importing, setImporting] = useState(false);
const [importFeedback, setImportFeedback] = useState(null);
/** @type {'webhook' | 'osm' | 'openData'} */
const [importMode, setImportMode] = useState('osm');
const [openDataUrl, setOpenDataUrl] = useState('');
useEffect(() => {
fetchPharmacies();
}, []);
const fetchPharmacies = async () => {
setLoading(true);
try {
const response = await fetch('/api/pharmacies', {
credentials: 'include',
});
const data = await response.json();
setPharmacies(data);
} catch (error) {
console.error('Error fetching pharmacies:', error);
alert('Error al cargar farmacias');
} finally {
setLoading(false);
}
};
const applyPreset = (id) => {
setRegionPreset(id);
const p = REGION_PRESETS.find((x) => x.id === id);
if (!p || id === 'custom') return;
setRegionLat(p.lat);
setRegionLon(p.lon);
setRegionRadio(p.radio);
};
const displayedPharmacies = useMemo(() => {
if (!filterByRegion) return pharmacies;
const lat = parseFloat(regionLat);
const lon = parseFloat(regionLon);
const r = parseFloat(regionRadio);
if (!Number.isFinite(lat) || !Number.isFinite(lon) || !Number.isFinite(r)) {
return pharmacies;
}
return pharmacies.filter((p) => {
if (p.latitude == null || p.longitude == null) return false;
return haversineMeters(lat, lon, p.latitude, p.longitude) <= r;
});
}, [pharmacies, filterByRegion, regionLat, regionLon, regionRadio]);
const handleCityLookup = async (e) => {
e?.preventDefault();
const q = cityQuery.trim();
if (!q) {
setCityLookupMessage({ type: 'err', text: 'Introduce una ciudad o lugar.' });
return;
}
setCityLookupLoading(true);
setCityLookupMessage(null);
try {
const response = await fetch(`/api/admin/geocode?q=${encodeURIComponent(q)}`, {
credentials: 'include',
});
if (!response.ok) {
throw new Error(await geocodeErrorMessage(response));
}
const data = await response.json();
setRegionLat(String(data.lat));
setRegionLon(String(data.lon));
setRegionRadio(String(data.radius));
setRegionPreset('custom');
setCityLookupMessage({
type: 'ok',
text: `Using: ${data.displayName} — radius ~${data.radius} m (you can edit below).`,
});
} catch (err) {
setCityLookupMessage({ type: 'err', text: err.message });
} finally {
setCityLookupLoading(false);
}
};
const handlePharmacyImport = async () => {
setImporting(true);
setImportFeedback(null);
try {
if (importMode === 'webhook') {
const body = {};
const lat = parseFloat(regionLat);
const lon = parseFloat(regionLon);
const radio = parseFloat(regionRadio);
if (Number.isFinite(lat) && Number.isFinite(lon) && Number.isFinite(radio)) {
body.lat = lat;
body.lon = lon;
body.radio = radio;
}
const response = await fetch('/api/admin/pharmacies/import-webhook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error || `Import failed (${response.status})`);
}
setImportFeedback({
type: 'success',
text: `[n8n] Imported ${data.inserted} new. Skipped ${data.skipped} duplicate(s). ${data.invalid || 0} invalid. ${data.totalReceived} from webhook.`,
});
await fetchPharmacies();
return;
}
if (importMode === 'openData') {
const url = openDataUrl.trim();
if (!url) {
throw new Error('Paste an open-data JSON URL (array or GeoJSON).');
}
const response = await fetch('/api/admin/pharmacies/import-external', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ source: 'openData', openDataUrl: url }),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error || `Import failed (${response.status})`);
}
const label = data.message || `openData: ${data.totalReceived} rows`;
setImportFeedback({
type: 'success',
text: `${label}. Inserted ${data.inserted}, skipped ${data.skipped}, invalid ${data.invalid || 0}.`,
});
await fetchPharmacies();
return;
}
const lat = parseFloat(regionLat);
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).');
}
const response = await fetch('/api/admin/pharmacies/import-external', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
source: importMode,
lat,
lon,
radio,
}),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error || `Import failed (${response.status})`);
}
const src = data.source === 'osm' ? 'OSM' : 'OpenStreetMap';
setImportFeedback({
type: 'success',
text: `[${src}] ${data.message || `Received ${data.totalReceived} pharmacies.`} Inserted ${data.inserted}, skipped ${data.skipped}, invalid ${data.invalid || 0}.`,
});
await fetchPharmacies();
} catch (error) {
setImportFeedback({ type: 'error', text: error.message });
} finally {
setImporting(false);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (saving) return;
setSaving(true);
try {
const payload = {
...formData,
latitude: formData.latitude ? parseFloat(formData.latitude) : null,
longitude: formData.longitude ? parseFloat(formData.longitude) : null,
opening_hours: draftToHours(hoursDraft),
};
if (editingPharmacy) {
const response = await fetch(`/api/admin/pharmacies/${editingPharmacy.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(payload),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Error al actualizar farmacia');
}
} else {
const response = await fetch('/api/admin/pharmacies', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(payload),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Error al crear farmacia');
}
}
resetForm();
fetchPharmacies();
alert(editingPharmacy ? '¡Farmacia actualizada!' : '¡Farmacia añadida!');
} catch (error) {
console.error('Error saving pharmacy:', error);
alert(`Error al guardar farmacia: ${error.message}`);
} finally {
setSaving(false);
}
};
const handleEdit = (pharmacy) => {
setEditingPharmacy(pharmacy);
setFormData({
name: pharmacy.name || '',
address: pharmacy.address || '',
phone: pharmacy.phone || '',
latitude: pharmacy.latitude ?? '',
longitude: pharmacy.longitude ?? '',
});
setHoursDraft(hoursToDraft(pharmacy.opening_hours));
setShowForm(true);
};
const handleDelete = async (id) => {
if (!confirm('¿Estás seguro de que quieres eliminar esta farmacia?')) return;
try {
const response = await fetch(`/api/admin/pharmacies/${id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!response.ok) throw new Error('Error al eliminar farmacia');
fetchPharmacies();
alert('¡Farmacia eliminada!');
} catch (error) {
console.error('Error deleting pharmacy:', error);
alert('Error al eliminar farmacia');
}
};
const resetForm = () => {
setFormData({
name: '',
address: '',
phone: '',
latitude: '',
longitude: '',
});
setHoursDraft(emptyHoursDraft());
setEditingPharmacy(null);
setShowForm(false);
};
const updateDay = (day, patch) => {
setHoursDraft((prev) => ({ ...prev, [day]: { ...prev[day], ...patch } }));
};
const onRegionFieldChange = (setter) => (e) => {
setRegionPreset('custom');
setter(e.target.value);
};
return (
<div className="admin-section">
<div className="section-header">
<h2>Gestionar Farmacias</h2>
<button
type="button"
className="btn-primary"
onClick={() => {
resetForm();
setShowForm(true);
}}
>
+ Añadir Nueva Farmacia
</button>
</div>
<div className="pharmacy-tools-card">
<h3>Ciudad, región e importación</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>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
</a>{' '}
(Nominatim).
</p>
<form className="city-lookup-form" onSubmit={handleCityLookup}>
<div className="form-group city-lookup-input-wrap">
<label htmlFor="city-finder">Buscar ciudad</label>
<input
id="city-finder"
type="search"
placeholder="Ej: Rubí, Madrid, Valencia…"
value={cityQuery}
onChange={(e) => {
setCityQuery(e.target.value);
setCityLookupMessage(null);
}}
autoComplete="address-level2"
/>
</div>
<button
type="submit"
className="btn-secondary city-lookup-submit"
disabled={cityLookupLoading}
>
{cityLookupLoading ? 'Buscando…' : 'Buscar ciudad'}
</button>
</form>
{cityLookupMessage && (
<p
className={`city-lookup-feedback ${cityLookupMessage.type === 'ok' ? 'ok' : 'err'}`}
role="status"
>
{cityLookupMessage.text}
</p>
)}
<div className="region-presets">
<label htmlFor="region-preset">Preset de área</label>
<select
id="region-preset"
value={regionPreset}
onChange={(e) => applyPreset(e.target.value)}
>
{REGION_PRESETS.map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
))}
</select>
</div>
<div className="region-grid">
<div className="form-group">
<label htmlFor="region-lat">Latitud</label>
<input
id="region-lat"
type="text"
inputMode="decimal"
value={regionLat}
onChange={onRegionFieldChange(setRegionLat)}
placeholder="41.5631"
/>
</div>
<div className="form-group">
<label htmlFor="region-lon">Longitud</label>
<input
id="region-lon"
type="text"
inputMode="decimal"
value={regionLon}
onChange={onRegionFieldChange(setRegionLon)}
placeholder="2.0038"
/>
</div>
<div className="form-group">
<label htmlFor="region-radio">Radio (m)</label>
<input
id="region-radio"
type="text"
inputMode="numeric"
value={regionRadio}
onChange={onRegionFieldChange(setRegionRadio)}
placeholder="1500"
/>
</div>
</div>
<div className="import-mode-row">
<div className="form-group import-mode-select-wrap">
<label htmlFor="import-mode">Fuente de datos</label>
<select
id="import-mode"
value={importMode}
onChange={(e) => {
setImportMode(e.target.value);
setImportFeedback(null);
}}
>
<option value="osm">OpenStreetMap (Overpass, gratuito)</option>
<option value="webhook">n8n webhook (heredado)</option>
<option value="openData">URL de datos abiertos JSON</option>
</select>
</div>
</div>
{importMode === 'openData' && (
<div className="form-group open-data-url-row">
<label htmlFor="open-data-url">URL JSON</label>
<input
id="open-data-url"
type="url"
placeholder="https://…/pharmacies.json"
value={openDataUrl}
onChange={(e) => setOpenDataUrl(e.target.value)}
autoComplete="off"
/>
</div>
)}
<div className="tool-actions-row">
<button
type="button"
className="btn-primary btn-import-webhook"
onClick={handlePharmacyImport}
disabled={importing}
>
{importing
? 'Importando…'
: importMode === 'webhook'
? 'Importar desde webhook'
: importMode === 'openData'
? 'Importar desde URL'
: `Importar desde ${importMode === 'osm' ? 'Overpass' : 'OpenStreetMap'}`}
</button>
<label className="filter-region-toggle">
<input
type="checkbox"
checked={filterByRegion}
onChange={(e) => setFilterByRegion(e.target.checked)}
/>
Mostrar solo farmacias dentro del radio
</label>
</div>
{importFeedback && (
<div
className={`import-feedback ${importFeedback.type === 'success' ? 'success' : 'error'}`}
role="status"
>
{importFeedback.text}
</div>
)}
</div>
{showForm && (
<form className="admin-form" onSubmit={handleSubmit}>
<h3>{editingPharmacy ? 'Editar Farmacia' : 'Añadir Nueva Farmacia'}</h3>
<div className="form-group">
<label>Nombre *</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
required
/>
</div>
<div className="form-group">
<label>Dirección *</label>
<input
type="text"
value={formData.address}
onChange={(e) => setFormData({ ...formData, address: e.target.value })}
required
/>
</div>
<div className="form-group">
<label>Teléfono</label>
<input
type="text"
value={formData.phone}
onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
/>
</div>
<div className="form-row">
<div className="form-group">
<label>Latitud</label>
<input
type="number"
step="any"
value={formData.latitude}
onChange={(e) => setFormData({ ...formData, latitude: e.target.value })}
/>
</div>
<div className="form-group">
<label>Longitud</label>
<input
type="number"
step="any"
value={formData.longitude}
onChange={(e) => setFormData({ ...formData, longitude: e.target.value })}
/>
</div>
</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>
{DAY_KEYS.map((day) => {
const d = hoursDraft[day];
return (
<div key={day} className={`hours-row ${d.closed ? 'is-closed' : ''}`}>
<span className="hours-day">{DAY_LABEL[day]}</span>
<label className="hours-closed-toggle">
<input
type="checkbox"
checked={d.closed}
onChange={(e) => updateDay(day, { closed: e.target.checked })}
/>
Cerrado
</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`}
/>
<span className="hours-sep"></span>
<input
type="time"
value={d.close}
disabled={d.closed}
onChange={(e) => updateDay(day, { close: e.target.value })}
aria-label={`${DAY_LABEL[day]} cierra a las`}
/>
</div>
);
})}
</fieldset>
<div className="form-actions">
<button type="submit" className="btn-primary" disabled={saving}>
{saving ? 'Guardando...' : editingPharmacy ? 'Actualizar' : 'Añadir'} Farmacia
</button>
<button type="button" className="btn-secondary" onClick={resetForm} disabled={saving}>
Cancelar
</button>
</div>
</form>
)}
{loading ? (
<div className="loading">Cargando farmacias...</div>
) : (
<div className="admin-list">
<p className="list-meta">
Mostrando {displayedPharmacies.length} de {pharmacies.length} farmacias
{filterByRegion && ' (dentro del radio)'}
</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.'}
</p>
) : (
displayedPharmacies.map((pharmacy) => (
<div key={pharmacy.id} className="admin-item">
<div className="item-content">
<h4>{pharmacy.name}</h4>
<p>📍 {pharmacy.address}</p>
{pharmacy.phone && <p>📞 {pharmacy.phone}</p>}
{(pharmacy.latitude != null || pharmacy.longitude != null) && (
<p>
🌐 {pharmacy.latitude}, {pharmacy.longitude}
</p>
)}
</div>
<div className="item-actions">
<button type="button" className="btn-edit" onClick={() => handleEdit(pharmacy)}>
Editar
</button>
<button type="button" className="btn-delete" onClick={() => handleDelete(pharmacy.id)}>
Eliminar
</button>
</div>
</div>
))
)}
</div>
)}
</div>
);
}
export default PharmacyManagement;
@@ -0,0 +1,404 @@
import React, { useState, useEffect, useMemo, useRef } from 'react';
import './AdminComponents.css';
const MAX_PHARMACY_RESULTS = 25;
function normalize(s) {
return (s || '').toString().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
}
function PharmacyMedicineLink() {
const [pharmacies, setPharmacies] = useState([]);
const [medicineSearch, setMedicineSearch] = useState('');
const [medicineResults, setMedicineResults] = useState([]);
const [selectedPharmacy, setSelectedPharmacy] = useState(null);
const [selectedMedicine, setSelectedMedicine] = useState(null);
const [pharmacyMedicines, setPharmacyMedicines] = useState([]);
const [loading, setLoading] = useState(false);
const [searching, setSearching] = useState(false);
const [pharmacyQuery, setPharmacyQuery] = useState('');
const [pharmacyDropdownOpen, setPharmacyDropdownOpen] = useState(false);
const pharmacyInputRef = useRef(null);
const [formData, setFormData] = useState({
pharmacy_id: '',
price: '',
stock: ''
});
const filteredPharmacies = useMemo(() => {
const q = normalize(pharmacyQuery).trim();
if (!q) return pharmacies.slice(0, MAX_PHARMACY_RESULTS);
const tokens = q.split(/\s+/).filter(Boolean);
return pharmacies
.filter(p => {
const hay = `${normalize(p.name)} ${normalize(p.address)}`;
return tokens.every(tok => hay.includes(tok));
})
.slice(0, MAX_PHARMACY_RESULTS);
}, [pharmacies, pharmacyQuery]);
useEffect(() => {
fetchPharmacies();
}, []);
useEffect(() => {
if (selectedPharmacy) {
fetchPharmacyMedicines(selectedPharmacy.id);
}
}, [selectedPharmacy]);
// Buscar medicamentos en la API de CIMA mientras el usuario escribe
useEffect(() => {
const q = medicineSearch.trim();
if (q.length < 2) {
setMedicineResults([]);
setSearching(false);
return;
}
const controller = new AbortController();
const timeoutId = setTimeout(async () => {
setSearching(true);
try {
const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(q)}`, {
credentials: 'include',
signal: controller.signal,
});
const data = await response.json();
setMedicineResults(Array.isArray(data) ? data : []);
} catch (error) {
if (error.name === 'AbortError') return;
console.error('Error searching medicines:', error);
} finally {
if (!controller.signal.aborted) setSearching(false);
}
}, 500);
return () => {
clearTimeout(timeoutId);
controller.abort();
};
}, [medicineSearch]);
const fetchPharmacies = async () => {
try {
const response = await fetch('/api/pharmacies', {
credentials: 'include',
});
const data = await response.json();
setPharmacies(data);
} catch (error) {
console.error('Error fetching pharmacies:', error);
}
};
const fetchPharmacyMedicines = async (pharmacyId) => {
setLoading(true);
try {
const response = await fetch(`/api/admin/pharmacies/${pharmacyId}/medicines`, {
credentials: 'include',
});
const data = await response.json();
setPharmacyMedicines(data);
} catch (error) {
console.error('Error fetching pharmacy medicines:', error);
} finally {
setLoading(false);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!selectedMedicine) {
alert('Por favor, selecciona un medicamento primero');
return;
}
try {
const payload = {
pharmacy_id: parseInt(formData.pharmacy_id),
medicine_nregistro: selectedMedicine.nregistro,
medicine_name: selectedMedicine.name,
price: formData.price ? parseFloat(formData.price) : null,
stock: formData.stock ? parseInt(formData.stock) : 0
};
const response = await fetch('/api/admin/pharmacy-medicines', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(payload)
});
if (!response.ok) throw new Error('Error al vincular medicamento a farmacia');
resetForm();
if (selectedPharmacy) {
fetchPharmacyMedicines(selectedPharmacy.id);
}
alert('¡Medicamento vinculado a la farmacia correctamente!');
} catch (error) {
console.error('Error linking medicine:', error);
alert('Error al vincular medicamento a farmacia');
}
};
const handleUpdate = async (id, price, stock) => {
try {
const response = await fetch(`/api/admin/pharmacy-medicines/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ price, stock })
});
if (!response.ok) throw new Error('Error al actualizar');
fetchPharmacyMedicines(selectedPharmacy.id);
alert('¡Actualizado correctamente!');
} catch (error) {
console.error('Error updating:', error);
alert('Error al actualizar');
}
};
const handleDelete = async (id) => {
if (!confirm('¿Eliminar este medicamento de la farmacia?')) return;
try {
const response = await fetch(`/api/admin/pharmacy-medicines/${id}`, {
method: 'DELETE',
credentials: 'include'
});
if (!response.ok) throw new Error('Error al eliminar');
fetchPharmacyMedicines(selectedPharmacy.id);
alert('¡Medicamento eliminado de la farmacia!');
} catch (error) {
console.error('Error deleting:', error);
alert('Error al eliminar medicamento');
}
};
const resetForm = () => {
setFormData({
pharmacy_id: selectedPharmacy ? selectedPharmacy.id.toString() : '',
price: '',
stock: ''
});
setSelectedMedicine(null);
setMedicineSearch('');
setMedicineResults([]);
};
const selectMedicine = (medicine) => {
setSelectedMedicine(medicine);
setMedicineSearch(medicine.name);
setMedicineResults([]);
};
const pickPharmacy = (pharmacy) => {
setSelectedPharmacy(pharmacy);
setFormData(prev => ({ ...prev, pharmacy_id: pharmacy.id.toString() }));
setPharmacyQuery(`${pharmacy.name}${pharmacy.address}`);
setPharmacyDropdownOpen(false);
};
const clearPharmacy = () => {
setSelectedPharmacy(null);
setFormData(prev => ({ ...prev, pharmacy_id: '' }));
setPharmacyQuery('');
setPharmacyDropdownOpen(true);
setTimeout(() => pharmacyInputRef.current?.focus(), 0);
};
return (
<div className="admin-section">
<h2>Vincular Medicamento a Farmacia</h2>
<form className="admin-form" onSubmit={handleSubmit}>
<div className="form-group">
<label>Farmacia *</label>
<input
ref={pharmacyInputRef}
type="text"
value={pharmacyQuery}
onChange={(e) => {
setPharmacyQuery(e.target.value);
if (selectedPharmacy) {
setSelectedPharmacy(null);
setFormData(prev => ({ ...prev, pharmacy_id: '' }));
}
setPharmacyDropdownOpen(true);
}}
onFocus={() => setPharmacyDropdownOpen(true)}
onBlur={() => setTimeout(() => setPharmacyDropdownOpen(false), 150)}
placeholder={pharmacies.length ? `Buscar entre ${pharmacies.length} farmacias por nombre o dirección…` : 'Cargando farmacias…'}
autoComplete="off"
required={!selectedPharmacy}
/>
{!selectedPharmacy && pharmacyDropdownOpen && (
<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>
</div>
) : (
filteredPharmacies.map((pharmacy) => (
<div
key={pharmacy.id}
className="search-result-item"
onMouseDown={(e) => { e.preventDefault(); pickPharmacy(pharmacy); }}
>
<strong>{pharmacy.name}</strong>
<span>{pharmacy.address}</span>
</div>
))
)}
</div>
)}
{selectedPharmacy && (
<div className="selected-medicine-info">
<p> Selected: <strong>{selectedPharmacy.name}</strong></p>
<p className="medicine-details">{selectedPharmacy.address}</p>
<button type="button" className="btn-small" onClick={clearPharmacy}>
Cambiar farmacia
</button>
</div>
)}
</div>
<div className="form-group">
<label>Buscar Medicamento (API CIMA) *</label>
<input
type="text"
value={medicineSearch}
onChange={(e) => {
setMedicineSearch(e.target.value);
setSelectedMedicine(null);
}}
placeholder="Escribe para buscar medicamentos en CIMA..."
required
/>
{searching && <p className="loading-text">Buscando...</p>}
{medicineResults.length > 0 && !selectedMedicine && (
<div className="medicine-search-results">
{medicineResults.slice(0, 10).map((medicine) => (
<div
key={medicine.nregistro}
className="search-result-item"
onClick={() => selectMedicine(medicine)}
>
<strong>{medicine.name}</strong>
{medicine.active_ingredient && <span> - {medicine.active_ingredient}</span>}
{medicine.dosage && <span> ({medicine.dosage})</span>}
</div>
))}
</div>
)}
{selectedMedicine && (
<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}`}
Registro: {selectedMedicine.nregistro}
</p>
<button
type="button"
className="btn-small"
onClick={() => {
setSelectedMedicine(null);
setMedicineSearch('');
}}
>
Cambiar medicamento
</button>
</div>
)}
</div>
<div className="form-row">
<div className="form-group">
<label>Precio ()</label>
<input
type="number"
step="0.01"
value={formData.price}
onChange={(e) => setFormData({ ...formData, price: e.target.value })}
placeholder="e.g., 12.50"
/>
</div>
<div className="form-group">
<label>Stock</label>
<input
type="number"
value={formData.stock}
onChange={(e) => setFormData({ ...formData, stock: e.target.value })}
placeholder="e.g., 50"
/>
</div>
</div>
<div className="form-actions">
<button type="submit" className="btn-primary">
Vincular Medicamento
</button>
<button type="button" className="btn-secondary" onClick={resetForm}>
Reiniciar
</button>
</div>
</form>
{selectedPharmacy && (
<div className="pharmacy-medicines-section">
<h3>Medicamentos en {selectedPharmacy.name}</h3>
{loading ? (
<div className="loading">Cargando...</div>
) : pharmacyMedicines.length === 0 ? (
<p className="empty-state">Aún no hay medicamentos vinculados a esta farmacia.</p>
) : (
<div className="admin-list">
{pharmacyMedicines.map((pm) => (
<div key={pm.id} className="admin-item">
<div className="item-content">
<h4>{pm.medicine_name}</h4>
<p>
<strong>Precio:</strong> {pm.price ? `${parseFloat(pm.price).toFixed(2)}` : 'No definido'}
<strong> Stock:</strong> {pm.stock || 0}
</p>
</div>
<div className="item-actions">
<button
className="btn-edit"
onClick={() => {
const newPrice = prompt('Introduce nuevo precio:', pm.price || '');
const newStock = prompt('Introduce nuevo stock:', pm.stock || '0');
if (newPrice !== null && newStock !== null) {
handleUpdate(pm.id, newPrice ? parseFloat(newPrice) : null, parseInt(newStock) || 0);
}
}}
>
Actualizar
</button>
<button className="btn-delete" onClick={() => handleDelete(pm.id)}>
Eliminar
</button>
</div>
</div>
))}
</div>
)}
</div>
)}
</div>
);
}
export default PharmacyMedicineLink;
+70
View File
@@ -0,0 +1,70 @@
export function IconHome({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...props}>
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
<polyline points="9 22 9 12 15 12 15 22" />
</svg>
);
}
export function IconSearch({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...props}>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
);
}
export function IconScan({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...props}>
<path d="M3 7V5a2 2 0 0 1 2-2h2" />
<path d="M17 3h2a2 2 0 0 1 2 2v2" />
<path d="M21 17v2a2 2 0 0 1-2 2h-2" />
<path d="M7 21H5a2 2 0 0 1-2-2v-2" />
<path d="M7 8v8M11 8v8M15 8v8M19 8v8" />
</svg>
);
}
export function IconBell({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...props}>
<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
<path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
</svg>
);
}
export function IconUser({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...props}>
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
);
}
export function IconCog({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...props}>
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
</svg>
);
}
export function IconLogo({ size = 24, ...props }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
<path d="M19 8h-1V6a3 3 0 0 0-3-3H9a3 3 0 0 0-3 3v2H5a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-6a3 3 0 0 0-3-3zM8 6a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2H8V6zm4 11a3 3 0 1 1 3-3 3 3 0 0 1-3 3z" />
</svg>
);
}
+123
View File
@@ -0,0 +1,123 @@
:root {
/* Pastel, softer palette */
--primary: #7fbf8f; /* soft green */
--on-primary: #09310a; /* dark accent for contrast */
--primary-container: #cfead0;
--on-primary-container: #0d2b12;
--secondary: #a3b8ff; /* soft blue */
--on-secondary: #06204a;
--secondary-container: #dbe7ff;
--on-secondary-container: #0b2a66;
--tertiary: #c9b3ff; /* soft lavender */
--on-tertiary: #241342;
--tertiary-container: #efe7ff;
--on-tertiary-container: #3b2a5a;
--surface: #fbfbfb;
--on-surface: #111417;
--on-surface-variant: #41493e;
--surface-container-lowest: #ffffff;
--surface-container-low: #f2f4f5;
--surface-container: #eceeef;
--surface-container-high: #e6e8e9;
--surface-container-highest: #e1e3e4;
--error: #b91c1c;
--on-error: #ffffff;
--error-container: #feecec;
--on-error-container: #610909;
--outline: #717a6d;
--outline-variant: #c0c9bb;
--on-background: #191c1d;
--inverse-surface: #2e3132;
--inverse-on-surface: #eff1f2;
--inverse-primary: #91d78a;
--surface-tint: #8ccb8e;
--surface-dim: #d8dadb;
--surface-bright: #f8fafb;
--surface-variant: #e1e3e4;
--primary-fixed: #acf4a4;
--primary-fixed-dim: #91d78a;
--secondary-fixed: #d9e2ff;
--secondary-fixed-dim: #b0c6ff;
--tertiary-fixed: #e9ddff;
--tertiary-fixed-dim: #cfbcff;
--radius-sm: 0.25rem;
--radius: 0.5rem;
--radius-md: 0.75rem;
--radius-lg: 1rem;
--radius-xl: 1.5rem;
--radius-full: 9999px;
--margin-main: 1.5rem;
--card-padding: 1.25rem;
--gutter: 1rem;
--touch-target-min: 3rem;
--shadow-soft: 0 4px 20px rgba(0, 0, 0, 0.08);
--text-main: var(--on-surface);
--text-muted: var(--on-surface-variant);
--surface-muted: var(--surface-container-low);
--surface-card: var(--surface-container-lowest);
--border: var(--outline-variant);
--border-strong: var(--outline);
--glass-bg: var(--surface-container-lowest);
--glass-border: var(--outline-variant);
--glass-shadow: var(--shadow-soft);
--accent: var(--primary);
--accent-warm: #f5a97a;
--primary-hover: #6fb47f; /* slightly darker than primary */
--primary-ring: rgba(127, 191, 143, 0.22);
--primary-shadow: rgba(127, 191, 143, 0.12);
--primary-light: #eaf7ec;
--primary-faint: rgba(127, 191, 143, 0.06);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
height: 100%;
overflow: hidden;
overscroll-behavior: none;
}
html {
overflow-x: clip;
}
body {
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
color: var(--on-surface);
background-color: var(--surface-container-lowest);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body::before {
content: "";
position: fixed;
inset: 0;
background-image: url('./assets/bg-SHmHDvQz.png');
background-size: cover;
background-position: center;
background-attachment: fixed;
opacity: 0.5;
z-index: -1;
}
body::after {
content: "";
position: fixed;
inset: 0;
background-color: rgba(255, 252, 245, 0.48);
z-index: -1;
}
#root {
height: 100dvh;
overflow: hidden;
}
+19
View File
@@ -0,0 +1,19 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { initNativeShell } from './utils/native';
import { initFaro } from './utils/faro';
// Initialize Grafana Faro (browser RUM) before rendering.
// No-op if VITE_FARO_ENDPOINT is not configured.
initFaro();
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
initNativeShell();
+47
View File
@@ -0,0 +1,47 @@
/// <reference lib="webworker" />
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { clientsClaim } from 'workbox-core';
cleanupOutdatedCaches();
precacheAndRoute(self.__WB_MANIFEST || []);
self.skipWaiting();
clientsClaim();
self.addEventListener('push', (event) => {
let data = {};
if (event.data) {
try {
data = event.data.json();
} catch {
data = { title: 'FarmaClic', body: event.data.text() };
}
}
const title = data.title || 'FarmaClic';
const options = {
body: data.body || '',
icon: '/icon.svg',
badge: '/icon.svg',
data: { url: data.url || '/' },
tag: data.medicine_nregistro || undefined,
renotify: Boolean(data.medicine_nregistro),
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const targetUrl = event.notification.data?.url || '/';
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
for (const client of clientList) {
if ('focus' in client) {
client.focus();
if ('navigate' in client) client.navigate(targetUrl);
return;
}
}
if (self.clients.openWindow) return self.clients.openWindow(targetUrl);
})
);
});
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom'
+69
View File
@@ -0,0 +1,69 @@
// Grafana Faro — browser RUM SDK initializer.
// Sends Web Vitals, JS errors, console messages, fetch/XHR, navigation,
// and React component lifecycle events to Grafana Alloy via OTLP HTTP.
//
// Required env vars (Vite injects VITE_* at build time):
// VITE_FARO_ENDPOINT — e.g. http://localhost:4318
// VITE_FARO_APP_NAME — e.g. farmaclic-frontend
// VITE_FARO_ENV — e.g. production | staging | development
// VITE_FARO_APP_VERSION — optional, defaults to 1.0.0
import {
getWebInstrumentations,
ReactIntegration,
initializeFaro,
} from '@grafana/faro-react';
import { TracingInstrumentation } from '@grafana/faro-web-tracing';
import { OtlpHttpTransport } from '@grafana/faro-transport-otlp-http';
let initialized = false;
export function initFaro() {
if (initialized) return;
initialized = true;
const endpoint = import.meta.env.VITE_FARO_ENDPOINT;
if (!endpoint) {
// Faro is optional. If the endpoint is not configured (e.g. local dev
// without an Alloy collector), do nothing so the app still runs.
return;
}
const appName = import.meta.env.VITE_FARO_APP_NAME || 'farmaclic-frontend';
const environment = import.meta.env.VITE_FARO_ENV || 'production';
const version = import.meta.env.VITE_FARO_APP_VERSION || '1.0.0';
try {
initializeFaro({
url: `${endpoint.replace(/\/$/, '')}/v1/traces`,
app: {
name: appName,
environment,
version,
},
instrumentations: [
...getWebInstrumentations({
captureConsole: true,
captureConsoleDisabledLevels: ['debug'],
captureException: true,
captureMessage: true,
captureResource: true,
captureUserInteraction: true,
captureXHRInstrumentation: true,
captureFetchInstrumentation: true,
captureWebVitals: true,
captureNavigation: true,
}),
new ReactIntegration(),
new TracingInstrumentation(),
],
transport: new OtlpHttpTransport({
url: `${endpoint.replace(/\/$/, '')}/v1/traces`,
}),
});
} catch (err) {
// Never let Faro init failure break the app.
// eslint-disable-next-line no-console
console.warn('[faro] init failed', err);
}
}
+38
View File
@@ -0,0 +1,38 @@
export function haversineKm(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = ((lat2 - lat1) * Math.PI) / 180;
const dLon = ((lon2 - lon1) * Math.PI) / 180;
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
export function getUserPosition() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocalización no compatible con este navegador'));
return;
}
if (typeof window !== 'undefined' && window.isSecureContext === false) {
reject(new Error('La geolocalización requiere HTTPS (o localhost)'));
return;
}
navigator.geolocation.getCurrentPosition(
pos => resolve({ lat: pos.coords.latitude, lon: pos.coords.longitude }),
err => {
console.error('[geo] getCurrentPosition failed — code:', err && err.code, 'message:', err && err.message);
reject(err);
},
{ timeout: 15000, maximumAge: 60000, enableHighAccuracy: false }
);
});
}
export function formatDistance(km) {
if (km < 1) return `${Math.round(km * 1000)} m`;
if (km < 10) return `${km.toFixed(1)} km`;
return `${Math.round(km)} km`;
}
+73
View File
@@ -0,0 +1,73 @@
const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const DAY_LABELS = {
sun: 'Domingo',
mon: 'Lunes',
tue: 'Martes',
wed: 'Miércoles',
thu: 'Jueves',
fri: 'Viernes',
sat: 'Sábado',
};
export const DAY_KEYS = DAYS;
export const DAY_LABEL = DAY_LABELS;
function parseHM(str) {
const [h, m] = str.split(':').map(Number);
if (!Number.isFinite(h) || !Number.isFinite(m)) return null;
return h * 60 + m;
}
function parseHours(raw) {
if (!raw) return null;
try {
return typeof raw === 'string' ? JSON.parse(raw) : raw;
} catch {
return null;
}
}
function findNextOpen(hours, now) {
for (let offset = 1; offset <= 7; offset++) {
const day = DAYS[(now.getDay() + offset) % 7];
const range = hours[day];
if (Array.isArray(range) && range.length === 2) {
const openStr = range[0];
if (offset === 1) return `mañana a las ${openStr}`;
return `${DAY_LABELS[day]} a las ${openStr}`;
}
}
return null;
}
export function getOpenStatus(rawHours, now = new Date()) {
const hours = parseHours(rawHours);
if (!hours) return null;
const day = DAYS[now.getDay()];
const range = hours[day];
if (!Array.isArray(range) || range.length !== 2) {
const next = findNextOpen(hours, now);
return { status: 'closed', label: next ? `Cerrado · Abre ${next}` : 'Cerrado' };
}
const openMins = parseHM(range[0]);
const closeMins = parseHM(range[1]);
if (openMins == null || closeMins == null) return null;
const nowMins = now.getHours() * 60 + now.getMinutes();
if (nowMins < openMins) {
return { status: 'closed', label: `Cerrado · Abre a las ${range[0]}` };
}
if (nowMins >= closeMins) {
const next = findNextOpen(hours, now);
return { status: 'closed', label: next ? `Cerrado · Abre ${next}` : 'Cerrado' };
}
return { status: 'open', label: `Abierto · Cierra a las ${range[1]}` };
}
export function emptyHours() {
return { sun: null, mon: null, tue: null, wed: null, thu: null, fri: null, sat: null };
}
+38
View File
@@ -0,0 +1,38 @@
// Capacitor bootstrap — no-ops on the web, configures native shell on mobile.
// Plugins are dynamic-imported so the web bundle isn't penalized.
let initStarted = false;
export function isNativeApp() {
return typeof window !== 'undefined' && Boolean(window.Capacitor?.isNativePlatform?.());
}
export async function initNativeShell() {
if (initStarted || !isNativeApp()) return;
initStarted = true;
try {
const { StatusBar, Style } = await import('@capacitor/status-bar');
await StatusBar.setBackgroundColor({ color: '#27633a' }).catch(() => {});
await StatusBar.setStyle({ style: Style.Light }).catch(() => {});
} catch {
/* plugin not present — fine on web */
}
try {
const { SplashScreen } = await import('@capacitor/splash-screen');
await SplashScreen.hide({ fadeOutDuration: 250 }).catch(() => {});
} catch {
/* plugin not present — fine on web */
}
try {
const { App } = await import('@capacitor/app');
App.addListener('backButton', ({ canGoBack }) => {
if (canGoBack) window.history.back();
else App.exitApp();
});
} catch {
/* plugin not present — fine on web */
}
}
+130
View File
@@ -0,0 +1,130 @@
const STORAGE_KEY = 'farmaclic.subscriptions.v1';
export function getStoredSubscriptions() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function storageKey(nregistro, pharmacyId = null) {
return pharmacyId ? `${nregistro}:${pharmacyId}` : nregistro;
}
export function isSubscribedLocally(nregistro, pharmacyId = null) {
return getStoredSubscriptions().includes(storageKey(nregistro, pharmacyId));
}
function setStoredSubscriptions(list) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify([...new Set(list)]));
} catch {}
}
export function pushSupported() {
return (
typeof window !== 'undefined' &&
'serviceWorker' in navigator &&
'PushManager' in window &&
'Notification' in window
);
}
export async function getVapidPublicKey() {
const res = await fetch('/api/notifications/vapid-public-key', { credentials: 'include' });
if (!res.ok) {
const message = res.status === 503
? 'Las notificaciones push no están configuradas en el servidor'
: `No se pudo obtener la clave VAPID (HTTP ${res.status})`;
throw new Error(message);
}
const { publicKey } = await res.json();
if (!publicKey) throw new Error('El servidor devolvió una clave VAPID vacía');
return publicKey;
}
export function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const raw = atob(base64);
const arr = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) arr[i] = raw.charCodeAt(i);
return arr;
}
async function getOrCreateSubscription() {
if (!pushSupported()) {
throw new Error('Las notificaciones push no son compatibles con este navegador');
}
if (window.isSecureContext === false) {
throw new Error('Las notificaciones push requieren HTTPS (o localhost)');
}
const reg = await navigator.serviceWorker.ready;
let sub = await reg.pushManager.getSubscription();
if (sub) return sub;
if (Notification.permission === 'denied') {
throw new Error('Permiso de notificaciones denegado — actívalo en la configuración del navegador');
}
if (Notification.permission === 'default') {
const result = await Notification.requestPermission();
if (result !== 'granted') {
throw new Error('Notification permission was not granted');
}
}
const publicKey = await getVapidPublicKey();
sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicKey),
});
return sub;
}
export async function subscribeToPush(medicineNregistro, medicineName, pharmacyId = null) {
const subscription = await getOrCreateSubscription();
const res = await fetch('/api/notifications/subscribe', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
medicine_nregistro: medicineNregistro,
medicine_name: medicineName || null,
subscription,
pharmacy_id: pharmacyId || null,
}),
});
if (!res.ok) {
const detail = await res.text().catch(() => '');
throw new Error(`Suscripción fallida (HTTP ${res.status}) ${detail}`);
}
setStoredSubscriptions([...getStoredSubscriptions(), storageKey(medicineNregistro, pharmacyId)]);
}
export async function unsubscribeFromPush(medicineNregistro, pharmacyId = null) {
let endpoint = null;
if (pushSupported()) {
try {
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.getSubscription();
endpoint = sub?.endpoint || null;
} catch {}
}
if (endpoint) {
await fetch('/api/notifications/unsubscribe', {
method: 'DELETE',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
medicine_nregistro: medicineNregistro,
endpoint,
pharmacy_id: pharmacyId || null,
}),
}).catch(() => {});
}
const key = storageKey(medicineNregistro, pharmacyId);
setStoredSubscriptions(getStoredSubscriptions().filter(n => n !== key));
}
@@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { subscribeToPush } from './notifications.js';
describe('subscribeToPush', () => {
beforeEach(() => {
vi.restoreAllMocks();
localStorage.clear();
});
it('sends the subscription request with credentials so the session is preserved', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce({ ok: true, json: async () => ({ publicKey: 'test-public-key' }) })
.mockResolvedValueOnce({ ok: true, text: async () => '' });
vi.stubGlobal('fetch', fetchMock);
Object.defineProperty(window, 'isSecureContext', {
configurable: true,
value: true,
});
Object.defineProperty(window, 'PushManager', {
configurable: true,
value: class PushManager {},
});
Object.defineProperty(window, 'Notification', {
configurable: true,
value: { permission: 'granted' },
});
Object.defineProperty(navigator, 'serviceWorker', {
configurable: true,
value: {
ready: Promise.resolve({
pushManager: {
getSubscription: vi.fn().mockResolvedValue(null),
subscribe: vi.fn().mockResolvedValue({ endpoint: 'https://example.test/push' }),
},
}),
},
});
await subscribeToPush('123456', 'Paracetamol');
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls[1][1]).toMatchObject({
method: 'POST',
credentials: 'include',
});
});
});
+127
View File
@@ -0,0 +1,127 @@
.admin-header-content {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
text-align: left;
}
.admin-header-content h1 {
margin-bottom: 0.35rem;
font-size: 2.35rem;
font-weight: 800;
color: var(--text-main);
letter-spacing: -0.02em;
}
.admin-header-content h1::after {
display: none;
}
.admin-header-content p {
color: var(--text-muted);
font-size: 1.05rem;
margin: 0;
line-height: 1.5;
}
.admin-user-info {
display: flex;
align-items: center;
gap: 1rem;
background: var(--surface);
padding: 0.5rem 1rem;
border-radius: 999px;
border: 1px solid var(--border);
box-shadow: 0 1px 2px rgba(28, 25, 23, 0.04);
}
.admin-user-info span {
font-weight: 600;
color: var(--text-main);
font-size: 0.9rem;
}
.logout-button {
background: #fef2f2;
color: #b91c1c;
border: 1px solid #fecaca;
padding: 0.4rem 0.85rem;
border-radius: 999px;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s, border-color 0.2s;
}
.logout-button:hover {
background: #fee2e2;
border-color: #fca5a5;
}
.admin-tabs {
display: flex;
gap: 0.35rem;
margin-bottom: 2rem;
padding: 0.35rem;
background: var(--surface-muted);
border-radius: var(--radius);
border: 1px solid var(--border);
width: fit-content;
flex-wrap: wrap;
}
.admin-tab {
background: transparent;
border: none;
padding: 0.7rem 1.35rem;
border-radius: var(--radius-sm);
font-weight: 600;
font-size: 0.9rem;
color: var(--text-muted);
cursor: pointer;
transition: color 0.2s, background 0.2s, box-shadow 0.2s;
}
.admin-tab:hover {
color: var(--text-main);
}
.admin-tab.active {
background: var(--surface);
color: var(--primary);
box-shadow: 0 1px 3px rgba(28, 25, 23, 0.08);
border: 1px solid var(--border);
}
.admin-content {
background: var(--surface);
border-radius: var(--radius);
padding: 2.5rem;
border: 1px solid var(--border);
box-shadow: var(--glass-shadow);
animation: fadeInUp 0.6s ease-out;
min-height: 400px;
}
@media (max-width: 768px) {
.admin-header-content {
flex-direction: column;
text-align: center;
gap: 1rem;
}
.admin-tabs {
flex-direction: column;
width: 100%;
}
.admin-tab {
width: 100%;
text-align: center;
}
.admin-content {
padding: 1.5rem;
}
}
+131
View File
@@ -0,0 +1,131 @@
import React, { useState, useEffect } from 'react';
import '../App.css';
import './AdminView.css';
import LoginForm from '../components/admin/LoginForm';
import PharmacyManagement from '../components/admin/PharmacyManagement';
import MedicineManagement from '../components/admin/MedicineManagement';
import PharmacyMedicineLink from '../components/admin/PharmacyMedicineLink';
function AdminView() {
const [authenticated, setAuthenticated] = useState(false);
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState('pharmacies'); // 'pharmacies', 'medicines', 'link'
useEffect(() => {
checkAuth();
}, []);
const checkAuth = async () => {
try {
const response = await fetch('/api/auth/check', {
credentials: 'include',
});
const data = await response.json();
if (data.authenticated) {
setAuthenticated(true);
setUser(data.user);
} else {
setAuthenticated(false);
setUser(null);
}
} catch (error) {
console.error('Error checking auth:', error);
setAuthenticated(false);
} finally {
setLoading(false);
}
};
const handleLogin = (userData) => {
setAuthenticated(true);
setUser(userData);
};
const handleLogout = async () => {
try {
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
});
setAuthenticated(false);
setUser(null);
} catch (error) {
console.error('Error logging out:', error);
}
};
if (loading) {
return (
<div className="app-main">
<div className="loading">Comprobando autenticación...</div>
</div>
);
}
if (!authenticated) {
return (
<>
<header className="app-header">
<h1> Panel de Administración</h1>
<p>Autenticación requerida</p>
</header>
<main className="app-main">
<LoginForm onLogin={handleLogin} />
</main>
</>
);
}
return (
<>
<header className="app-header">
<div className="admin-header-content">
<div>
<h1> Panel de Administración</h1>
<p>Gestiona farmacias y medicamentos</p>
</div>
<div className="admin-user-info">
<span>👤 {user?.username}</span>
<button className="logout-button" onClick={handleLogout}>
Cerrar sesión
</button>
</div>
</div>
</header>
<main className="app-main">
<div className="admin-tabs">
<button
className={`admin-tab ${activeTab === 'pharmacies' ? 'active' : ''}`}
onClick={() => setActiveTab('pharmacies')}
>
🏥 Farmacias
</button>
<button
className={`admin-tab ${activeTab === 'medicines' ? 'active' : ''}`}
onClick={() => setActiveTab('medicines')}
>
💊 Medicamentos
</button>
<button
className={`admin-tab ${activeTab === 'link' ? 'active' : ''}`}
onClick={() => setActiveTab('link')}
>
🔗 Vincular Medicamento a Farmacia
</button>
</div>
<div className="admin-content">
{activeTab === 'pharmacies' && <PharmacyManagement />}
{activeTab === 'medicines' && <MedicineManagement />}
{activeTab === 'link' && <PharmacyMedicineLink />}
</div>
</main>
</>
);
}
export default AdminView;
+137
View File
@@ -0,0 +1,137 @@
.alerts-view {
width: 100%;
max-width: 48rem;
margin: 0 auto;
}
.alerts-main {
padding: 1.5rem var(--margin-main) 2rem;
}
.alerts-header {
margin-bottom: 2rem;
}
.alerts-title {
font-size: 2rem;
font-weight: 700;
color: var(--on-surface);
line-height: 1.2;
margin-bottom: 0.25rem;
}
.alerts-subtitle {
font-size: 1.125rem;
color: var(--on-surface-variant);
font-weight: 400;
}
.alerts-list {
display: flex;
flex-direction: column;
gap: var(--gutter);
}
.alert-card {
background: var(--surface-container-lowest);
border-radius: var(--radius-md);
box-shadow: var(--shadow-soft);
padding: var(--card-padding);
display: flex;
flex-direction: column;
gap: 1rem;
border: 2px solid transparent;
}
.alert-card--primary { border-color: rgba(0, 69, 13, 0.1); }
.alert-card--tertiary { border-color: rgba(70, 0, 173, 0.1); }
.alert-card-top {
display: flex;
align-items: flex-start;
gap: 1rem;
}
.alert-icon {
width: 3.25rem;
height: 3.25rem;
border-radius: var(--radius-md);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.alert-icon--primary {
background: var(--primary-container);
color: var(--on-primary-container);
}
.alert-icon--tertiary {
background: var(--tertiary-container);
color: var(--on-tertiary);
}
.alert-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.alert-title {
font-size: 1.25rem;
font-weight: 700;
color: var(--on-surface);
line-height: 1.3;
}
.alert-badge {
display: inline-block;
width: fit-content;
padding: 0.25rem 0.75rem;
border-radius: var(--radius-full);
font-size: 0.875rem;
font-weight: 700;
}
.alert-badge--primary {
background: var(--error-container);
color: var(--on-error-container);
}
.alert-badge--tertiary {
background: var(--tertiary-fixed);
color: var(--on-tertiary-fixed-variant);
}
.alert-actions {
display: flex;
gap: 0.5rem;
align-items: center;
}
.alert-delete {
width: var(--touch-target-min);
height: var(--touch-target-min);
display: flex;
align-items: center;
justify-content: center;
border: 2px solid var(--outline);
border-radius: var(--radius-md);
background: transparent;
color: var(--outline);
cursor: pointer;
flex-shrink: 0;
transition: background 0.15s;
}
.alert-delete:hover {
background: var(--surface-container-high);
}
@media (max-width: 400px) {
.alerts-title {
font-size: 1.5rem;
}
}
+168
View File
@@ -0,0 +1,168 @@
import React, { useState, useEffect } from 'react';
import './AlertsView.css';
const iconMap = {
bell: (
<svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z" />
</svg>
),
store: (
<svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
<path d="M18.36 9l.6 3H5.04l.6-3h12.72M20 4H4v2h16V4zm0 3H4l-1 5v2h1v6h10v-6h4v6h2v-6h1v-2l-1-5zM6 18v-4h6v4H6z" />
</svg>
),
};
function AlertsView() {
const [availability, setAvailability] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchAvailabilityNotifications = async () => {
try {
setLoading(true);
setError(null);
const notifsRes = await fetch('/api/notifications/mine', { credentials: 'include' });
if (notifsRes.status === 401) {
setError('Por favor, inicia sesión para ver tus avisos.');
setLoading(false);
return;
}
let notifsData = { global: [], pharmacy: [] };
if (notifsRes.ok) {
notifsData = await notifsRes.json();
}
const mergedAvailability = [
...(notifsData.global || []).map(item => ({ ...item, scope: 'global' })),
...(notifsData.pharmacy || []).map(item => ({ ...item, scope: 'pharmacy' })),
].sort((a, b) => (b.created_at || '').localeCompare(a.created_at || ''));
setAvailability(mergedAvailability);
} catch (err) {
console.error('Error fetching availability notifications:', err);
setError('No se pudieron cargar los avisos.');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchAvailabilityNotifications();
}, []);
const handleDeleteAvailability = async (item) => {
try {
const res = await fetch('/api/notifications/mine', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ scope: item.scope, id: item.id }),
});
if (res.ok || res.status === 204) {
setAvailability(prev => prev.filter(i => !(i.scope === item.scope && i.id === item.id)));
// Also update local storage if possible to reflect that we unsubscribed
try {
const STORAGE_KEY = 'farmaclic.subscriptions.v1';
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
const keyToSearch = item.scope === 'pharmacy'
? `${item.medicine_nregistro}:${item.pharmacy_id}`
: item.medicine_nregistro;
const filtered = parsed.filter(k => k !== keyToSearch);
localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered));
}
}
} catch (e) {
console.warn('Could not update localStorage subscriptions:', e);
}
} else {
throw new Error('Error deleting availability alert');
}
} catch (err) {
console.error(err);
setError('No se pudo eliminar la alerta de disponibilidad.');
}
};
return (
<div className="alerts-view">
<main className="alerts-main">
<div className="alerts-header">
<h2 className="alerts-title">Mis Avisos</h2>
<p className="alerts-subtitle">Mantente al día con tus medicamentos.</p>
</div>
{loading && <p className="alerts-status" style={{ textAlign: 'center', padding: '2rem' }}>Cargando avisos...</p>}
{!loading && error && <p className="alerts-error" style={{ color: 'var(--error)', textAlign: 'center', padding: '2rem' }}>{error}</p>}
{!loading && !error && (
<>
{/* Availability Section */}
<section className="alerts-section">
<h3 className="alerts-section-title" style={{ marginBottom: '1rem' }}>Disponibilidad</h3>
<div className="alerts-list">
{availability.length === 0 ? (
<p className="alerts-empty" style={{ color: 'var(--on-surface-variant)', fontStyle: 'italic' }}>No tienes suscripciones de disponibilidad.</p>
) : (
availability.map((alert) => {
const cardColor = alert.scope === 'pharmacy' ? 'primary' : 'tertiary';
const cardIcon = alert.scope === 'pharmacy' ? 'store' : 'bell';
const key = `${alert.scope}:${alert.id}`;
return (
<div key={key} className={`alert-card alert-card--${cardColor}`}>
<div className="alert-card-top">
<div className={`alert-icon alert-icon--${cardColor}`}>
{iconMap[cardIcon]}
</div>
<div className="alert-info">
<h3 className="alert-title">{alert.medicine_name || alert.medicine_nregistro}</h3>
{alert.scope === 'pharmacy' ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.25rem', marginTop: '0.25rem' }}>
<span className={`alert-badge alert-badge--${cardColor}`} style={{ width: 'fit-content' }}>
🏥 {alert.pharmacy_name || `Farmacia #${alert.pharmacy_id}`}
</span>
{alert.pharmacy_address && (
<p className="alert-address-text" style={{ fontSize: '0.9rem', color: 'var(--on-surface-variant)', margin: 0 }}>
📍 {alert.pharmacy_address}
</p>
)}
</div>
) : (
<span className={`alert-badge alert-badge--${cardColor}`} style={{ width: 'fit-content', marginTop: '0.25rem' }}>
🔔 Notificarme cuando esté disponible
</span>
)}
</div>
</div>
<div className="alert-actions" style={{ justifyContent: 'flex-end' }}>
<button
className="alert-delete"
aria-label="Eliminar"
onClick={() => handleDeleteAvailability(alert)}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
</button>
</div>
</div>
);
})
)}
</div>
</section>
</>
)}
</main>
</div>
);
}
export default AlertsView;
+311
View File
@@ -0,0 +1,311 @@
.home-view {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100%;
max-width: 100%;
width: 100%;
padding: 1rem;
gap: 1.5rem;
animation: fadeInUp 0.6s ease-out;
}
/* Mobile optimizations */
@media (max-width: 768px) {
.home-view {
padding: 0.75rem;
gap: 1rem;
}
.home-logo-wrapper {
flex-direction: column;
align-items: center;
}
.home-logo {
width: min(12rem, 80vw);
}
.home-desc {
font-size: clamp(0.9rem, 5vw, 1.125rem);
max-width: 90%;
text-align: center;
}
.home-cards {
width: 100%;
max-width: 100%;
gap: 1rem;
}
.home-card {
min-height: 4rem;
padding: 0.75rem 1rem;
gap: 0.75rem;
flex-direction: row;
}
.home-card-icon {
width: 2.5rem;
height: 2.5rem;
}
.home-card-label {
font-size: 1rem;
}
}
/* Tablet optimizations */
@media (min-width: 769px) and (max-width: 1024px) {
.home-view {
padding: 1rem 0.5rem;
}
.home-card {
min-height: 4.25rem;
padding: 0.75rem 1.25rem;
}
.home-card-icon {
width: 2.75rem;
height: 2.75rem;
}
}
/* Desktop optimizations */
@media (min-width: 1025px) {
.home-view {
padding: 1rem var(--margin-main);
max-width: 100%;
}
.home-hero {
text-align: left;
align-items: flex-start;
}
.home-logo-wrapper {
flex-direction: row;
justify-content: flex-start;
}
.home-desc {
font-size: 1.125rem;
max-width: 30rem;
text-align: left;
}
.home-cards {
flex-direction: row;
flex-wrap: wrap;
gap: 1.5rem;
max-width: 80rem;
}
.home-card {
min-height: 5rem;
padding: 1rem 1.5rem;
flex-direction: row;
}
}
.home-hero {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 0.75rem;
}
.home-logo-wrapper {
display: contents;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 1rem;
margin-bottom: 0.5rem;
}
.home-logo {
width: min(10rem, 50vw);
height: auto;
}
.home-brand-name {
height: 2rem;
width: auto;
}
@media (max-height: 700px) {
.home-logo {
width: min(12rem, 60vw);
}
}
@media (max-height: 600px) {
.home-logo {
width: min(10rem, 50vw);
}
}
.home-desc {
font-size: 1.125rem;
color: var(--on-surface-variant);
font-weight: 400;
max-width: 20rem;
line-height: 1.5;
}
.home-cards {
display: flex;
flex-direction: column;
gap: var(--gutter);
width: 100%;
max-width: 28rem;
}
.home-card {
display: flex;
align-items: center;
gap: 1.25rem;
width: 100%;
min-height: 5rem;
padding: 1rem 1.5rem;
border: none;
border-radius: var(--radius-md);
cursor: pointer;
text-align: left;
transition: transform 0.15s, box-shadow 0.15s;
}
.home-card:active {
transform: scale(0.98);
}
.home-card--search {
/* Make suggestion/search buttons softer and more harmonious */
background: var(--primary-container);
color: var(--on-primary-container);
box-shadow: 0 6px 18px rgba(13, 43, 18, 0.06);
}
.home-card--scan {
/* Keep the scan button vivid and easy to find (intentionally prominent) */
background: #2b5bb5; /* vivid blue to stand out */
color: #ffffff;
box-shadow: 0 8px 28px rgba(43, 91, 181, 0.28);
transform: translateY(0);
}
.home-card--scan:hover {
transform: translateY(-3px);
}
.home-card--scan:focus {
outline: none;
box-shadow: 0 0 0 6px rgba(43,91,181,0.12), 0 8px 28px rgba(43,91,181,0.28);
}
.home-card-icon {
width: 3.5rem;
height: 3.5rem;
border-radius: var(--radius);
background: rgba(255, 255, 255, 0.2);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.home-card-text {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.home-card-label {
font-size: 1.25rem;
font-weight: 700;
line-height: 1.2;
}
.home-card-arrow {
opacity: 0.7;
flex-shrink: 0;
display: flex;
}
@media (max-width: 400px) {
.home-card {
min-height: 4.25rem;
padding: 0.75rem 1.25rem;
}
.home-card-label {
font-size: 1.1rem;
}
}
@media (max-height: 700px) {
.home-view {
gap: 1rem;
padding: 0.5rem var(--margin-main);
}
.home-card {
min-height: 4rem;
padding: 0.625rem 1rem;
}
.home-card-icon {
width: 2.75rem;
height: 2.75rem;
}
.home-card-icon svg {
width: 24px;
height: 24px;
}
.home-card-label {
font-size: 1.05rem;
}
.home-desc {
font-size: 0.95rem;
}
}
@media (max-height: 600px) {
.home-view {
gap: 0.5rem;
padding: 0.25rem var(--margin-main);
}
.home-card {
min-height: 3.5rem;
padding: 0.5rem 0.875rem;
gap: 0.75rem;
}
.home-card-icon {
width: 2.25rem;
height: 2.25rem;
}
.home-card-icon svg {
width: 20px;
height: 20px;
}
.home-card-label {
font-size: 0.95rem;
}
.home-desc {
font-size: 0.85rem;
}
}
+57
View File
@@ -0,0 +1,57 @@
import React from 'react';
import './HomeView.css';
function HomeView({ onScanClick, onSearchClick }) {
return (
<div className="home-view">
<div className="home-hero">
<div className="home-logo-wrapper">
<img src="/farmaclic_logo.png" alt="FarmaClic" className="home-logo" />
<img src="/farmaclic_text.png" alt="FarmaClic" className="home-brand-name" />
</div>
<p className="home-desc">Encuentra tus medicamentos en farmacias cercanas</p>
</div>
<div className="home-cards">
<button className="home-card home-card--search" onClick={onSearchClick}>
<div className="home-card-icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
</div>
<div className="home-card-text">
<span className="home-card-label">Buscar Medicamento</span>
<span className="home-card-arrow">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="9 18 15 12 9 6" />
</svg>
</span>
</div>
</button>
<button className="home-card home-card--scan" onClick={onScanClick}>
<div className="home-card-icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 7V5a2 2 0 0 1 2-2h2" />
<path d="M17 3h2a2 2 0 0 1 2 2v2" />
<path d="M21 17v2a2 2 0 0 1-2 2h-2" />
<path d="M7 21H5a2 2 0 0 1-2-2v-2" />
<path d="M7 8v8M11 8v8M15 8v8M19 8v8" />
</svg>
</div>
<div className="home-card-text">
<span className="home-card-label">Escanear TSI</span>
<span className="home-card-arrow">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="9 18 15 12 9 6" />
</svg>
</span>
</div>
</button>
</div>
</div>
);
}
export default HomeView;
+347
View File
@@ -0,0 +1,347 @@
.profile-view {
width: 100%;
max-width: 48rem;
margin: 0 auto;
padding: 2rem var(--margin-main) 2rem;
animation: fadeInUp 0.5s ease-out;
}
.profile-avatar-section {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 2rem;
}
.profile-avatar-circle {
width: 8rem;
height: 8rem;
border-radius: var(--radius-full);
background: var(--secondary-container);
color: var(--on-secondary-container);
display: flex;
align-items: center;
justify-content: center;
border: 4px solid var(--surface-container-lowest);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
margin-bottom: 0.75rem;
}
.profile-name {
font-size: 1.75rem;
font-weight: 700;
color: var(--on-surface);
text-align: center;
}
.profile-info-cards {
display: flex;
flex-direction: column;
gap: var(--gutter);
margin-bottom: 2rem;
}
.profile-info-card {
background: var(--surface-container-lowest);
padding: var(--card-padding);
border-radius: var(--radius-md);
border: 2px solid var(--surface-container-high);
box-shadow: var(--shadow-soft);
}
.info-card-label {
font-size: 0.875rem;
font-weight: 600;
color: var(--on-surface-variant);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 0.25rem;
}
.info-card-value {
font-size: 1.25rem;
font-weight: 500;
color: var(--on-surface);
}
.profile-menu {
display: flex;
flex-direction: column;
gap: var(--gutter);
margin-bottom: 3rem;
}
.profile-menu-item {
display: flex;
align-items: center;
gap: 1rem;
width: 100%;
height: 5rem;
padding: 0 1.5rem;
background: var(--surface-container-lowest);
border: 2px solid var(--surface-container-high);
border-radius: var(--radius-md);
cursor: pointer;
text-align: left;
box-shadow: var(--shadow-soft);
transition: background 0.15s;
}
.profile-menu-item:active {
background: var(--surface-container);
}
.menu-item-icon {
width: 3rem;
height: 3rem;
border-radius: var(--radius);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.menu-item-icon--primary {
background: rgba(0, 69, 13, 0.08);
color: var(--primary);
}
.menu-item-icon--error {
background: rgba(186, 26, 26, 0.08);
color: var(--error);
}
.menu-item-icon--secondary {
background: rgba(43, 91, 181, 0.08);
color: var(--secondary);
}
.menu-item-icon--error-outline {
background: rgba(186, 26, 26, 0.08);
color: var(--error);
}
.menu-item-label {
flex: 1;
font-size: 1.125rem;
font-weight: 500;
color: var(--on-surface);
}
.menu-item-chevron {
color: var(--on-surface-variant);
flex-shrink: 0;
}
.profile-location-section {
background: var(--surface-container-lowest);
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
padding: var(--card-padding);
margin-bottom: 1.5rem;
}
.profile-location-section h3 {
font-size: 1.1rem;
font-weight: 700;
color: var(--on-surface);
margin-bottom: 0.25rem;
}
.profile-section-sub {
font-size: 0.9rem;
color: var(--on-surface-variant);
margin-bottom: 1rem;
line-height: 1.45;
}
.profile-form {
display: flex;
flex-direction: column;
gap: 0.85rem;
}
.profile-field {
display: flex;
flex-direction: column;
gap: 0.3rem;
flex: 1;
min-width: 0;
}
.profile-field label {
font-size: 0.75rem;
font-weight: 600;
color: var(--on-surface-variant);
letter-spacing: 0.03em;
}
.profile-field input {
padding: 0.65rem 0.85rem;
border: 2px solid var(--outline-variant);
border-radius: var(--radius);
background: var(--surface);
color: var(--on-surface);
font-size: 0.95rem;
outline: none;
transition: border-color 0.15s;
width: 100%;
font-family: inherit;
}
.profile-field input:focus {
border-color: var(--primary);
}
.profile-field input:disabled {
opacity: 0.6;
}
.profile-field-row {
display: flex;
gap: 0.85rem;
}
.profile-helper-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.profile-btn-secondary {
background: var(--surface-container-low);
border: 1px solid var(--outline-variant);
color: var(--on-surface);
padding: 0.5rem 1rem;
border-radius: var(--radius-full);
cursor: pointer;
font-size: 0.8rem;
font-weight: 600;
font-family: inherit;
transition: background 0.15s;
}
.profile-btn-secondary:hover:not(:disabled) {
background: var(--surface-container);
}
.profile-btn-secondary:disabled {
opacity: 0.6;
cursor: progress;
}
.profile-feedback {
margin: 0;
font-size: 0.85rem;
padding: 0.5rem 0.75rem;
border-radius: var(--radius);
line-height: 1.4;
}
.profile-feedback--ok {
background: rgba(0, 69, 13, 0.08);
color: var(--primary);
border: 1px solid rgba(0, 69, 13, 0.2);
}
.profile-feedback--err {
background: rgba(186, 26, 26, 0.08);
color: var(--error);
border: 1px solid rgba(186, 26, 26, 0.2);
}
.profile-actions {
display: flex;
justify-content: flex-end;
margin-top: 0.25rem;
}
.profile-btn-primary {
background: var(--primary);
color: var(--on-primary);
border: none;
padding: 0.65rem 1.5rem;
border-radius: var(--radius-full);
cursor: pointer;
font-size: 0.9rem;
font-weight: 700;
font-family: inherit;
transition: opacity 0.15s;
}
.profile-btn-primary:hover:not(:disabled) {
opacity: 0.9;
}
.profile-btn-primary:disabled {
opacity: 0.55;
}
.profile-logout-btn {
display: flex;
align-items: center;
gap: 1rem;
width: 100%;
height: 5rem;
padding: 0 1.5rem;
background: rgba(186, 26, 26, 0.06);
border: 2px solid rgba(186, 26, 26, 0.2);
border-radius: var(--radius-md);
cursor: pointer;
text-align: left;
color: var(--error);
font-size: 1.125rem;
font-weight: 700;
font-family: inherit;
transition: background 0.15s;
}
.profile-logout-btn:active {
background: rgba(186, 26, 26, 0.12);
}
@media (max-width: 480px) {
.profile-view {
padding: 1rem var(--margin-main) 1rem;
}
.profile-menu-item {
height: auto;
padding: 0.875rem 1rem;
min-height: 4rem;
}
.menu-item-icon {
width: 2.5rem;
height: 2.5rem;
}
.profile-field-row {
flex-direction: column;
gap: 0.85rem;
}
.profile-avatar-circle {
width: 6rem;
height: 6rem;
}
.profile-btn-secondary {
width: 100%;
justify-content: center;
}
.profile-btn-primary {
width: 100%;
}
.profile-actions {
width: 100%;
}
.profile-logout-btn {
height: auto;
padding: 0.875rem 1rem;
min-height: 4rem;
}
}
+250
View File
@@ -0,0 +1,250 @@
import React, { useEffect, useState } from 'react';
import './ProfileView.css';
import { getUserPosition } from '../utils/geo';
function ProfileView({ currentUser, onProfileSaved, onShowSaved, onLogout, onAdminClick }) {
const [address, setAddress] = useState(currentUser?.address || '');
const [latitude, setLatitude] = useState(
currentUser?.latitude != null ? String(currentUser.latitude) : ''
);
const [longitude, setLongitude] = useState(
currentUser?.longitude != null ? String(currentUser.longitude) : ''
);
const [saving, setSaving] = useState(false);
const [geocoding, setGeocoding] = useState(false);
const [locating, setLocating] = useState(false);
const [feedback, setFeedback] = useState(null);
useEffect(() => {
setAddress(currentUser?.address || '');
setLatitude(currentUser?.latitude != null ? String(currentUser.latitude) : '');
setLongitude(currentUser?.longitude != null ? String(currentUser.longitude) : '');
setFeedback(null);
}, [currentUser?.id]);
async function handleSave(e) {
e?.preventDefault();
setSaving(true);
setFeedback(null);
try {
const res = await fetch('/api/users/me', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
address: address.trim() || null,
latitude: latitude === '' ? null : latitude,
longitude: longitude === '' ? null : longitude,
}),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `Error al guardar (HTTP ${res.status})`);
}
const updated = await res.json();
onProfileSaved?.(updated);
setFeedback({ type: 'ok', text: 'Perfil guardado.' });
} catch (err) {
setFeedback({ type: 'err', text: err.message || 'Error al guardar' });
} finally {
setSaving(false);
}
}
async function handleUseLocation() {
setLocating(true);
setFeedback(null);
try {
const pos = await getUserPosition();
setLatitude(String(pos.lat));
setLongitude(String(pos.lon));
setFeedback({ type: 'ok', text: 'Ubicación obtenida — recuerda Guardar.' });
} catch (err) {
let msg = 'No se pudo obtener la ubicación';
if (err && typeof err.code === 'number') {
if (err.code === 1) msg = 'Permiso de ubicación denegado';
else if (err.code === 2) msg = 'Ubicación no disponible';
else if (err.code === 3) msg = 'La solicitud expiró';
}
setFeedback({ type: 'err', text: msg });
} finally {
setLocating(false);
}
}
async function handleGeocode() {
const q = address.trim();
if (!q) {
setFeedback({ type: 'err', text: 'Ingresa una dirección primero.' });
return;
}
setGeocoding(true);
setFeedback(null);
try {
const res = await fetch(`/api/geocode?q=${encodeURIComponent(q)}`, {
credentials: 'include',
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `Error en la búsqueda (HTTP ${res.status})`);
}
const data = await res.json();
setLatitude(String(data.lat));
setLongitude(String(data.lon));
setFeedback({
type: 'ok',
text: `Ubicado: ${data.displayName} — recuerda Guardar.`,
});
} catch (err) {
setFeedback({ type: 'err', text: err.message || 'Error en la búsqueda' });
} finally {
setGeocoding(false);
}
}
const username = currentUser?.username || 'Usuario';
return (
<div className="profile-view">
<div className="profile-avatar-section">
<div className="profile-avatar-circle">
<svg width="80" height="80" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
</svg>
</div>
<h2 className="profile-name">Mi Perfil</h2>
</div>
<div className="profile-info-cards">
<div className="profile-info-card">
<p className="info-card-label">Nombre</p>
<p className="info-card-value">{username}</p>
</div>
</div>
<div className="profile-menu">
<button className="profile-menu-item" onClick={onShowSaved}>
<div className="menu-item-icon menu-item-icon--primary">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
</svg>
</div>
<span className="menu-item-label">Mis Direcciones</span>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="menu-item-chevron">
<polyline points="9 18 15 12 9 6" />
</svg>
</button>
<button className="profile-menu-item">
<div className="menu-item-icon menu-item-icon--error">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M22 3H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM8 6c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H2v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1zm8-5h-5V9h5v4z" />
</svg>
</div>
<span className="menu-item-label">Contactos de Emergencia</span>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="menu-item-chevron">
<polyline points="9 18 15 12 9 6" />
</svg>
</button>
<button className="profile-menu-item">
<div className="menu-item-icon menu-item-icon--secondary">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-7 2h2.5v12H13V6zm-2 12H8.5V6H11v12zM4 6h2.5v12H4V6zm16 12h-2.5V6H20v12z" />
</svg>
</div>
<span className="menu-item-label">Configuración de Texto</span>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="menu-item-chevron">
<polyline points="9 18 15 12 9 6" />
</svg>
</button>
{currentUser?.is_admin && (
<button className="profile-menu-item" onClick={onAdminClick}>
<div className="menu-item-icon menu-item-icon--primary">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z" />
</svg>
</div>
<span className="menu-item-label">Panel de Administración</span>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="menu-item-chevron">
<polyline points="9 18 15 12 9 6" />
</svg>
</button>
)}
</div>
<div className="profile-location-section">
<h3>Tu Ubicación</h3>
<p className="profile-section-sub">Guarda tu dirección para ordenar por distancia sin pedir permiso cada vez.</p>
<form onSubmit={handleSave} className="profile-form">
<div className="profile-field">
<label htmlFor="profile-address">Dirección</label>
<input
id="profile-address"
type="text"
placeholder="Calle Mayor 1, Madrid"
value={address}
onChange={(e) => setAddress(e.target.value)}
autoComplete="street-address"
disabled={saving}
/>
</div>
<div className="profile-field-row">
<div className="profile-field">
<label htmlFor="profile-lat">Latitud</label>
<input
id="profile-lat"
type="number"
step="any"
placeholder="40.4168"
value={latitude}
onChange={(e) => setLatitude(e.target.value)}
disabled={saving}
/>
</div>
<div className="profile-field">
<label htmlFor="profile-lon">Longitud</label>
<input
id="profile-lon"
type="number"
step="any"
placeholder="-3.7038"
value={longitude}
onChange={(e) => setLongitude(e.target.value)}
disabled={saving}
/>
</div>
</div>
<div className="profile-helper-actions">
<button type="button" className="profile-btn-secondary" onClick={handleGeocode} disabled={geocoding || saving}>
{geocoding ? 'Buscando…' : '📍 Buscar desde dirección'}
</button>
<button type="button" className="profile-btn-secondary" onClick={handleUseLocation} disabled={locating || saving}>
{locating ? 'Localizando…' : '🛰️ Usar mi ubicación'}
</button>
</div>
{feedback && (
<p className={`profile-feedback profile-feedback--${feedback.type}`}>{feedback.text}</p>
)}
<div className="profile-actions">
<button type="submit" className="profile-btn-primary" disabled={saving}>
{saving ? 'Guardando…' : 'Guardar'}
</button>
</div>
</form>
</div>
<button className="profile-logout-btn" onClick={onLogout}>
<div className="menu-item-icon menu-item-icon--error-outline">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z" />
</svg>
</div>
<span>Cerrar Sesión</span>
</button>
</div>
);
}
export default ProfileView;
+262
View File
@@ -0,0 +1,262 @@
import React, { useState, useEffect, useMemo } from 'react';
import '../App.css';
import SearchBar from '../components/SearchBar';
import MedicineResults from '../components/MedicineResults';
import PharmacyList from '../components/PharmacyList';
import PharmacyMap from '../components/PharmacyMap';
import HomeView from './HomeView';
import ScannerView from './ScannerView';
import { haversineKm, getUserPosition } from '../utils/geo';
function PublicView({
currentUser,
onLoginRequest,
screen: screenProp,
onScreenChange,
}) {
// ponytail: uncontrolled by default (own state); controlled when App.jsx passes props
// so BottomNav can drive the inner screen directly. No-op fallback breaks tests.
const [internalScreen, setInternalScreen] = useState('home');
const screen = screenProp ?? internalScreen;
const setScreen = onScreenChange ?? setInternalScreen;
const [searchQuery, setSearchQuery] = useState('');
const [medicines, setMedicines] = useState([]);
const [selectedMedicine, setSelectedMedicine] = useState(null);
const [pharmacies, setPharmacies] = useState([]);
const [loading, setLoading] = useState(false);
const [userPosition, setUserPosition] = useState(null);
const [positionSource, setPositionSource] = useState(null); // 'profile' | 'browser'
const [sortByDistance, setSortByDistance] = useState(false);
const [locating, setLocating] = useState(false);
const [locationError, setLocationError] = useState('');
useEffect(() => {
const searchMedicines = async () => {
if (searchQuery.trim().length < 2) {
setMedicines([]);
setSelectedMedicine(null);
setPharmacies([]);
return;
}
setLoading(true);
try {
const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(searchQuery)}`);
const data = await response.json();
setMedicines(data);
} catch (error) {
console.error('Error searching medicines:', error);
} finally {
setLoading(false);
}
};
const timeoutId = setTimeout(searchMedicines, 300);
return () => clearTimeout(timeoutId);
}, [searchQuery]);
useEffect(() => {
const fetchPharmacies = async () => {
if (!selectedMedicine) {
setPharmacies([]);
return;
}
setLoading(true);
try {
const response = await fetch(`/api/medicines/${selectedMedicine.id}/pharmacies`);
const data = await response.json();
setPharmacies(data);
} catch (error) {
console.error('Error fetching pharmacies:', error);
} finally {
setLoading(false);
}
};
fetchPharmacies();
}, [selectedMedicine]);
const savedLat = currentUser?.latitude;
const savedLon = currentUser?.longitude;
const hasSavedCoords = savedLat != null && savedLon != null;
const handleSortByDistance = async () => {
if (sortByDistance) {
setSortByDistance(false);
return;
}
setLocationError('');
if (hasSavedCoords) {
setUserPosition({ lat: savedLat, lon: savedLon });
setPositionSource('profile');
setSortByDistance(true);
return;
}
if (userPosition) {
setSortByDistance(true);
return;
}
setLocating(true);
try {
const pos = await getUserPosition();
setUserPosition(pos);
setPositionSource('browser');
setSortByDistance(true);
} catch (err) {
console.error('[location] error', err);
let msg;
if (err && typeof err.code === 'number') {
if (err.code === 1) msg = 'Permiso de ubicación denegado — actívalo en la configuración del navegador';
else if (err.code === 2) msg = 'Ubicación no disponible — comprueba los servicios de ubicación/WiFi';
else if (err.code === 3) msg = 'La solicitud de ubicación expiró — inténtalo de nuevo';
else msg = `Error de geolocalización (código ${err.code})`;
} else {
msg = err && err.message ? err.message : 'No se pudo obtener tu ubicación';
}
setLocationError(msg);
} finally {
setLocating(false);
}
};
const displayedPharmacies = useMemo(() => {
if (!sortByDistance || !userPosition) return pharmacies;
return [...pharmacies].sort((a, b) => {
if (a.latitude == null || a.longitude == null) return 1;
if (b.latitude == null || b.longitude == null) return -1;
return (
haversineKm(userPosition.lat, userPosition.lon, a.latitude, a.longitude) -
haversineKm(userPosition.lat, userPosition.lon, b.latitude, b.longitude)
);
});
}, [pharmacies, sortByDistance, userPosition]);
/* ── Scanner → Search handoff ──────────────────────────── */
function handleScanSelectMedicine(medicineName) {
setSearchQuery(medicineName);
setSelectedMedicine(null);
setPharmacies([]);
setScreen('search');
}
/* ── Screens ─────────────────────────────────────────────── */
if (screen === 'home') {
return (
<HomeView
onScanClick={() => setScreen('scan')}
onSearchClick={() => setScreen('search')}
/>
);
}
if (screen === 'scan') {
return (
<ScannerView
onClose={() => setScreen('home')}
onSelectMedicine={handleScanSelectMedicine}
/>
);
}
// screen === 'search'
return (
<>
<header className="app-header">
<button
className="back-to-home-btn"
onClick={() => {
setSearchQuery('');
setSelectedMedicine(null);
setPharmacies([]);
setScreen('home');
}}
aria-label="Volver al inicio"
>
Inicio
</button>
<h1>💊 FarmaClic</h1>
<p>Encuentra tu medicamento en farmacias cercanas</p>
</header>
<main className="app-main">
<SearchBar
value={searchQuery}
onChange={setSearchQuery}
placeholder="Buscar un medicamento..."
/>
{loading && <div className="loading">Buscando...</div>}
{searchQuery && !selectedMedicine && (
<MedicineResults
medicines={medicines}
onSelect={setSelectedMedicine}
query={searchQuery}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
)}
{selectedMedicine && (
<div className="selected-medicine-section">
<div className="medicine-info">
<h2>{selectedMedicine.name}</h2>
<div className="medicine-details">
<span><strong>Principio Activo:</strong> {selectedMedicine.active_ingredient}</span>
<span><strong>Dosis:</strong> {selectedMedicine.dosage}</span>
<span><strong>Forma:</strong> {selectedMedicine.form}</span>
</div>
<button
className="back-button"
onClick={() => {
setSelectedMedicine(null);
setPharmacies([]);
}}
>
Volver a búsqueda
</button>
</div>
{pharmacies.length > 0 && (
<div className="pharmacy-controls">
<button
className={`sort-distance-button ${sortByDistance ? 'active' : ''}`}
onClick={handleSortByDistance}
disabled={locating}
>
{locating
? '📍 Localizando…'
: sortByDistance
? '📍 Ordenado por distancia · Reset'
: hasSavedCoords
? '📍 Ordenar por ubicación guardada'
: '📍 Ordenar por distancia'}
</button>
{sortByDistance && positionSource === 'profile' && (
<span className="location-source">Usando tu dirección guardada</span>
)}
{locationError && (
<span className="location-error">{locationError}</span>
)}
</div>
)}
<PharmacyMap pharmacies={displayedPharmacies} />
<PharmacyList
pharmacies={displayedPharmacies}
loading={loading}
userPosition={sortByDistance ? userPosition : null}
medicine={selectedMedicine}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
</div>
)}
</main>
</>
);
}
export default PublicView;
+444
View File
@@ -0,0 +1,444 @@
.scanner-view {
width: 100%;
max-width: 48rem;
margin: 0 auto;
}
.scanner-content {
padding: 2rem var(--margin-main) 2rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: fadeInUp 0.5s ease-out;
}
.scanner-hero {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 0.75rem;
}
.scanner-icon-circle {
width: 4.5rem;
height: 4.5rem;
border-radius: var(--radius-full);
background: var(--tertiary-container);
color: var(--on-tertiary);
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 0.25rem;
}
.scanner-heading {
font-size: 1.5rem;
font-weight: 700;
color: var(--on-surface);
line-height: 1.2;
}
.scanner-desc {
font-size: 1rem;
color: var(--on-surface-variant);
font-weight: 400;
max-width: 22rem;
line-height: 1.5;
}
.scan-error-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
background: var(--error-container);
border-radius: var(--radius-md);
padding: 1.5rem 1.25rem;
text-align: center;
}
.scan-error-icon {
color: var(--error);
width: 2.5rem;
height: 2.5rem;
}
.scan-error-text {
color: var(--on-error-container);
font-size: 0.95rem;
line-height: 1.5;
margin: 0;
}
.scan-btn {
height: var(--touch-target-min);
border: none;
border-radius: var(--radius-md);
font-size: 1rem;
font-weight: 700;
cursor: pointer;
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
transition: opacity 0.15s, transform 0.1s;
}
.scan-btn:active {
transform: scale(0.97);
}
.scan-btn--primary {
background: var(--primary);
color: var(--on-primary);
}
.scan-btn--outline {
background: transparent;
border: 2px solid var(--error);
color: var(--on-error-container);
}
.scan-btn--ghost {
background: var(--surface-container-low);
border: 1px solid var(--outline-variant);
color: var(--on-surface-variant);
width: 100%;
}
.scan-btn--start {
width: 100%;
padding: 0 1.5rem;
height: 3.75rem;
font-size: 1.125rem;
}
.scanner-camera-container {
position: relative;
width: 100%;
border-radius: var(--radius-md);
overflow: hidden;
background: #000;
aspect-ratio: 4/3;
}
.scanner-video {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.scanner-frame {
position: absolute;
inset: 10% 12%;
pointer-events: none;
}
.corner {
position: absolute;
width: 22px;
height: 22px;
border-color: var(--tertiary-container);
border-style: solid;
border-width: 0;
}
.corner.tl { top: 0; left: 0; border-top-width: 3px; border-left-width: 3px; border-radius: 4px 0 0 0; }
.corner.tr { top: 0; right: 0; border-top-width: 3px; border-right-width: 3px; border-radius: 0 4px 0 0; }
.corner.bl { bottom: 0; left: 0; border-bottom-width: 3px; border-left-width: 3px; border-radius: 0 0 0 4px; }
.corner.br { bottom: 0; right: 0; border-bottom-width: 3px; border-right-width: 3px; border-radius: 0 0 4px 0; }
.scanner-hint {
position: absolute;
bottom: 0.75rem;
left: 50%;
transform: translateX(-50%);
white-space: nowrap;
font-size: 0.78rem;
color: rgba(255,255,255,0.75);
background: rgba(0,0,0,0.55);
backdrop-filter: blur(6px);
padding: 0.3rem 0.75rem;
border-radius: var(--radius-full);
}
.scanning-active {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
padding: 2rem;
}
.scanning-active p {
color: var(--on-surface-variant);
font-size: 0.95rem;
margin: 0;
}
.scanner-spinner {
width: 36px;
height: 36px;
border: 3px solid var(--outline-variant);
border-top-color: var(--primary);
border-radius: 50%;
animation: spin 0.75s linear infinite;
}
.cip-form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.cip-label {
font-size: 0.8rem;
color: var(--on-surface-variant);
font-weight: 600;
letter-spacing: 0.04em;
}
.cip-row {
display: flex;
gap: 0.5rem;
}
.cip-input {
flex: 1;
background: var(--surface-container-lowest);
border: 2px solid var(--outline-variant);
border-radius: var(--radius-md);
padding: 0.85rem 1rem;
font-size: 1rem;
font-family: 'Courier New', monospace;
color: var(--on-surface);
letter-spacing: 0.08em;
outline: none;
transition: border-color 0.15s;
}
.cip-input::placeholder {
color: var(--on-surface-variant);
letter-spacing: 0.04em;
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
opacity: 0.6;
}
.cip-input:focus {
border-color: var(--primary);
}
/* Prescriptions panel */
.prescriptions-panel {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.cip-badge {
display: flex;
align-items: center;
gap: 1rem;
background: rgba(0, 69, 13, 0.08);
border: 1px solid rgba(0, 69, 13, 0.2);
border-radius: var(--radius-md);
padding: 1rem 1.25rem;
color: var(--primary);
}
.cip-badge-label {
font-size: 0.85rem;
font-weight: 600;
margin: 0;
}
.cip-badge-value {
font-size: 0.85rem;
font-family: 'Courier New', monospace;
color: var(--on-surface-variant);
margin: 0.1rem 0 0;
}
.rx-title {
font-size: 1.25rem;
font-weight: 700;
color: var(--on-surface);
margin: 0;
}
.rx-subtitle {
font-size: 0.9rem;
color: var(--on-surface-variant);
margin: -0.75rem 0 0;
}
.rx-loading {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 2rem 0;
color: var(--on-surface-variant);
font-size: 0.9rem;
}
.rx-empty {
color: var(--on-surface-variant);
text-align: center;
padding: 1.5rem 0;
font-size: 0.9rem;
}
.rx-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.rx-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
background: var(--surface-container-lowest);
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
padding: 1rem 1.25rem;
cursor: pointer;
width: 100%;
text-align: left;
font-family: inherit;
transition: background 0.15s, border-color 0.15s;
}
.rx-item:hover {
background: var(--surface-container);
border-color: var(--primary);
}
.rx-item-info {
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.rx-name {
font-size: 1rem;
font-weight: 700;
color: var(--on-surface);
}
.rx-detail {
font-size: 0.85rem;
color: var(--on-surface-variant);
}
.rx-ingredient {
font-size: 0.8rem;
color: var(--primary);
font-weight: 500;
}
.rx-arrow {
color: var(--primary);
flex-shrink: 0;
}
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(14px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Photo upload section */
.upload-section {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.upload-label {
font-size: 0.8rem;
color: var(--on-surface-variant);
font-weight: 600;
letter-spacing: 0.04em;
}
.upload-row {
display: flex;
gap: 0.75rem;
}
.upload-option {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 1.25rem 0.75rem;
background: var(--surface-container-lowest);
border: 2px solid var(--outline-variant);
border-radius: var(--radius-md);
cursor: pointer;
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
font-size: 0.9rem;
font-weight: 600;
color: var(--on-surface);
transition: border-color 0.15s, background 0.15s;
}
.upload-option:hover {
border-color: var(--primary);
background: var(--surface-container);
}
.upload-option:active {
transform: scale(0.97);
}
.upload-option svg {
color: var(--primary);
}
.upload-hidden-input {
display: none;
}
/* Photo preview */
.photo-preview-panel {
display: flex;
flex-direction: column;
gap: 1rem;
}
.photo-preview-container {
width: 100%;
border-radius: var(--radius-md);
overflow: hidden;
background: #000;
max-height: 22rem;
}
.photo-preview-img {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
max-height: 22rem;
}
.photo-preview-actions {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
+535
View File
@@ -0,0 +1,535 @@
import React, { useState, useCallback, useRef } from 'react';
import { BarcodeScanner, BarcodeFormat } from '@capacitor-mlkit/barcode-scanning';
import { Capacitor } from '@capacitor/core';
import { BrowserMultiFormatReader } from '@zxing/browser';
import { BarcodeFormat as ZxingFormat, DecodeHintType } from '@zxing/library';
import './ScannerView.css';
const CIP_REGEX = /^[A-Z0-9]{8,30}$/i;
function playBeep() {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(1046, ctx.currentTime);
osc.frequency.exponentialRampToValueAtTime(1318, ctx.currentTime + 0.08);
gain.gain.setValueAtTime(0.28, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.35);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + 0.38);
} catch (_) { }
}
function ScannerView({ onClose, onSelectMedicine }) {
const videoRef = useRef(null);
const streamRef = useRef(null);
const rafRef = useRef(null);
const detectorRef = useRef(null);
// Log de diagnóstico al montar
React.useEffect(() => {
console.log('[Scanner] BarcodeDetector global:', typeof BarcodeDetector);
console.log('[Scanner] Navegador:', navigator.userAgent);
}, []);
const [phase, setPhase] = useState('idle');
const [manualCip, setManualCip] = useState('');
const [prescriptions, setPrescriptions] = useState([]);
const [scannedCip, setScannedCip] = useState(null);
const [loadingPrescriptions, setLoadingPrescriptions] = useState(false);
const [errorMsg, setErrorMsg] = useState('');
// Photo upload state
const [previewUrl, setPreviewUrl] = useState(null);
const [ocrLoading, setOcrLoading] = useState(false);
const cameraInputRef = useRef(null);
const galleryInputRef = useRef(null);
const isNative = Capacitor.isNativePlatform();
const fetchPrescriptions = useCallback(async (cip) => {
setLoadingPrescriptions(true);
try {
const res = await fetch(`/api/tsi/${encodeURIComponent(cip)}/prescriptions`);
const data = await res.json();
setPrescriptions(data);
} catch {
setPrescriptions([]);
} finally {
setLoadingPrescriptions(false);
}
}, []);
function stopCamera() {
streamRef.current?.getTracks().forEach(t => t.stop());
streamRef.current = null;
if (rafRef.current) {
cancelAnimationFrame(rafRef.current);
rafRef.current = null;
}
}
async function handleNativeScan() {
setErrorMsg('');
try {
const supported = await BarcodeScanner.isSupported();
if (!supported) {
setErrorMsg('El escáner no está disponible en este dispositivo.');
setPhase('error');
return;
}
const permission = await BarcodeScanner.checkPermissions();
if (permission.camera !== 'granted') {
const request = await BarcodeScanner.requestPermissions();
if (request.camera !== 'granted') {
setErrorMsg('Permiso de cámara denegado. Actívalo en ajustes o introduce el código CIP manualmente.');
setPhase('error');
return;
}
}
setPhase('scanning');
const result = await BarcodeScanner.scan({
formats: [BarcodeFormat.PDF417, BarcodeFormat.Code128, BarcodeFormat.QrCode],
autoZoom: true,
});
const barcode = result.barcodes[0];
const rawValue = barcode?.rawValue;
if (!rawValue || !CIP_REGEX.test(rawValue)) {
setErrorMsg('Código de barras inválido. Intenta de nuevo o introduce el CIP manualmente.');
setPhase('error');
return;
}
playBeep();
setScannedCip(rawValue);
setPhase('prescriptions');
fetchPrescriptions(rawValue);
} catch (err) {
if (err?.message?.includes('cancel') || err?.message?.includes('User')) {
setPhase('idle');
return;
}
setErrorMsg(`Error al escanear: ${err.message || 'Error desconocido'}`);
setPhase('error');
}
}
async function handleWebScan() {
setErrorMsg('');
console.log('[Scanner] Iniciando escaneo web...');
try {
if (!navigator.mediaDevices?.getUserMedia) {
setErrorMsg('Cámara no disponible en este navegador.');
setPhase('error');
return;
}
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: 'environment' }, width: { ideal: 1280 }, height: { ideal: 720 } },
});
console.log('[Scanner] Stream de cámara obtenido');
streamRef.current = stream;
setPhase('scanning');
await new Promise((resolve) => {
const waitForVideo = () => {
if (videoRef.current) {
videoRef.current.srcObject = stream;
videoRef.current.play().then(() => {
console.log('[Scanner] Video reproduciéndose');
console.log('[Scanner] Video dims:', videoRef.current.videoWidth, 'x', videoRef.current.videoHeight);
resolve();
}).catch((e) => {
console.error('[Scanner] Error al reproducir video:', e);
resolve();
});
} else {
requestAnimationFrame(waitForVideo);
}
};
requestAnimationFrame(waitForVideo);
});
console.log('[Scanner] Usando zxing local (@zxing/browser)...');
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
ZxingFormat.CODE_128,
ZxingFormat.CODE_39,
ZxingFormat.CODE_93,
ZxingFormat.PDF_417,
ZxingFormat.QR_CODE,
ZxingFormat.EAN_13,
ZxingFormat.EAN_8,
ZxingFormat.UPC_A,
ZxingFormat.UPC_E,
ZxingFormat.ITF,
]);
hints.set(DecodeHintType.TRY_HARDER, true);
const zxingReader = new BrowserMultiFormatReader(hints);
detectorRef.current = zxingReader;
const formatNames = { 0:'AZTEC', 1:'CODABAR', 2:'CODE_39', 3:'CODE_93', 4:'CODE_128', 5:'DATA_MATRIX', 6:'EAN_8', 7:'EAN_13', 8:'ITF', 10:'PDF_417', 11:'QR_CODE', 12:'RSS_14', 14:'UPC_A', 15:'UPC_E' };
console.log('[Scanner] Iniciando decodeFromVideoElement...');
const controls = await zxingReader.decodeFromVideoElement(videoRef.current, (result, error) => {
if (result) {
const rawValue = result.getText();
const cleaned = rawValue.replace(/[^A-Z0-9]/gi, '');
const format = result.getBarcodeFormat();
console.log('[Scanner] zxing detectó! raw:', rawValue, '| limpio:', cleaned, '| formato:', formatNames[format] || format);
if (cleaned && CIP_REGEX.test(cleaned)) {
console.log('[Scanner] CIP válido ✓');
controls.stop();
stopCamera();
playBeep();
setScannedCip(cleaned);
setPhase('prescriptions');
fetchPrescriptions(cleaned);
} else if (rawValue) {
console.log('[Scanner] Código no cumple regex:', cleaned);
}
}
});
console.log('[Scanner] Escaneando...');
} catch (err) {
console.error('[Scanner] Error general:', err);
stopCamera();
if (err.name === 'NotAllowedError') {
setErrorMsg('Permiso de cámara denegado. Permite el acceso e intenta de nuevo.');
} else if (err.name === 'NotFoundError') {
setErrorMsg('No se detectó ninguna cámara. Introduce el código CIP manualmente.');
} else {
setErrorMsg(`Error de cámara: ${err.message || 'Error desconocido'}`);
}
setPhase('error');
}
}
function handleStartScan() {
if (isNative) {
handleNativeScan();
} else {
handleWebScan();
}
}
function handleManualSubmit(e) {
e.preventDefault();
const cip = manualCip.trim();
if (!cip) {
setErrorMsg('Introduce un código CIP.');
setPhase('error');
return;
}
if (!CIP_REGEX.test(cip)) {
setErrorMsg('Formato CIP inválido. Debe tener 16 caracteres alfanuméricos.');
setPhase('error');
return;
}
playBeep();
setScannedCip(cip);
setPhase('prescriptions');
fetchPrescriptions(cip);
}
// Photo upload handlers
function handlePhotoSelect(e) {
const file = e.target.files?.[0];
if (!file) return;
setErrorMsg('');
setPreviewUrl(URL.createObjectURL(file));
setPhase('photo-preview');
// Reset input so selecting the same file again triggers onChange
e.target.value = '';
}
async function handlePhotoOcr() {
if (!previewUrl) return;
setOcrLoading(true);
setErrorMsg('');
try {
const res = await fetch(previewUrl);
const blob = await res.blob();
const formData = new FormData();
formData.append('photo', blob, 'tsi.jpg');
const ocrRes = await fetch('/api/tsi/ocr', { method: 'POST', body: formData });
const data = await ocrRes.json();
if (!ocrRes.ok) {
setErrorMsg(data.error || 'No se pudo leer la imagen. Intenta con otra foto.');
setPhase('error');
return;
}
const cip = data.cip;
if (!CIP_REGEX.test(cip)) {
setErrorMsg(`CIP detectado "${cip}" no tiene formato válido. Introduce el código manualmente.`);
setPhase('error');
return;
}
playBeep();
setScannedCip(cip);
setPreviewUrl(null);
setPhase('prescriptions');
fetchPrescriptions(cip);
} catch (err) {
setErrorMsg(`Error al procesar la imagen: ${err.message || 'Error desconocido'}`);
setPhase('error');
} finally {
setOcrLoading(false);
}
}
function handlePhotoDiscard() {
setPreviewUrl(null);
setPhase('idle');
}
function handlePickPrescription(rx) {
stopCamera();
onSelectMedicine(rx.name);
}
function handleBack() {
stopCamera();
if (phase === 'prescriptions') {
setPhase('idle');
setPrescriptions([]);
setScannedCip(null);
} else if (phase === 'photo-preview') {
setPreviewUrl(null);
setPhase('idle');
} else {
onClose();
}
}
return (
<div className="scanner-view">
<div className="scanner-content">
<div className="scanner-hero">
<div className="scanner-icon-circle">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 7V5a2 2 0 0 1 2-2h2" />
<path d="M17 3h2a2 2 0 0 1 2 2v2" />
<path d="M21 17v2a2 2 0 0 1-2 2h-2" />
<path d="M7 21H5a2 2 0 0 1-2-2v-2" />
<path d="M7 8v8M11 8v8M15 8v8M19 8v8" />
</svg>
</div>
<h2 className="scanner-heading">Escanear TSI</h2>
<p className="scanner-desc">Escanea el código de barras de tu tarjeta sanitaria para ver tus recetas activas</p>
</div>
{phase !== 'prescriptions' && (
<>
{phase === 'error' && (
<div className="scan-error-card">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" className="scan-error-icon">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
</svg>
<p className="scan-error-text">{errorMsg}</p>
<button className="scan-btn scan-btn--outline" onClick={() => { setErrorMsg(''); setPhase('idle'); }}>
Intentar de nuevo
</button>
</div>
)}
{phase === 'idle' && (
<>
<button className="scan-btn scan-btn--primary scan-btn--start" onClick={handleStartScan}>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
<circle cx="12" cy="13" r="4" />
</svg>
Abrir cámara
</button>
<div className="upload-section">
<label className="upload-label">O sube una foto de tu TSI</label>
<div className="upload-row">
<button className="upload-option" onClick={() => cameraInputRef.current?.click()}>
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
<circle cx="12" cy="13" r="4" />
</svg>
<span>Hacer foto</span>
</button>
<button className="upload-option" onClick={() => galleryInputRef.current?.click()}>
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
<span>Subir de galería</span>
</button>
</div>
<input
ref={cameraInputRef}
type="file"
accept="image/*"
capture="environment"
onChange={handlePhotoSelect}
className="upload-hidden-input"
/>
<input
ref={galleryInputRef}
type="file"
accept="image/*"
onChange={handlePhotoSelect}
className="upload-hidden-input"
/>
</div>
</>
)}
{phase === 'scanning' && !isNative && (
<div className="scanner-camera-container">
<video ref={videoRef} className="scanner-video" autoPlay muted playsInline />
<div className="scanner-frame">
<div className="corner tl" />
<div className="corner tr" />
<div className="corner bl" />
<div className="corner br" />
</div>
<p className="scanner-hint">Apunta al código de barras</p>
</div>
)}
{phase === 'scanning' && isNative && (
<div className="scanning-active">
<div className="scanner-spinner" />
<p>Abriendo cámara</p>
</div>
)}
{phase === 'photo-preview' && (
<div className="photo-preview-panel">
<div className="photo-preview-container">
<img src={previewUrl} alt="TSI capturada" className="photo-preview-img" />
</div>
{ocrLoading ? (
<div className="scanning-active">
<div className="scanner-spinner" />
<p>Procesando imagen</p>
</div>
) : (
<div className="photo-preview-actions">
<button className="scan-btn scan-btn--primary scan-btn--start" onClick={handlePhotoOcr}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="4 7 4 4 20 4 20 7" />
<line x1="9" y1="20" x2="15" y2="20" />
<line x1="12" y1="4" x2="12" y2="20" />
</svg>
Escanear imagen
</button>
<button className="scan-btn scan-btn--ghost" onClick={handlePhotoDiscard}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
Descartar
</button>
</div>
)}
</div>
)}
<form className="cip-form" onSubmit={handleManualSubmit}>
<label className="cip-label" htmlFor="cip-input">O introduce el código CIP manualmente</label>
<div className="cip-row">
<input
id="cip-input"
className="cip-input"
type="text"
placeholder="Código CIP de 16 dígitos"
value={manualCip}
onChange={(e) => setManualCip(e.target.value)}
maxLength={16}
autoComplete="off"
spellCheck={false}
/>
<button type="submit" className="scan-btn scan-btn--primary">Buscar</button>
</div>
</form>
</>
)}
{phase === 'prescriptions' && (
<div className="prescriptions-panel">
<div className="cip-badge">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6zm3 10c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" />
</svg>
<div>
<p className="cip-badge-label">TSI Escaneada</p>
<p className="cip-badge-value">{scannedCip}</p>
</div>
</div>
<h3 className="rx-title">Recetas Activas</h3>
<p className="rx-subtitle">Toca un medicamento para ver disponibilidad en farmacias cercanas.</p>
{loadingPrescriptions && (
<div className="rx-loading">
<div className="scanner-spinner" />
<p>Cargando recetas</p>
</div>
)}
{!loadingPrescriptions && prescriptions.length === 0 && (
<p className="rx-empty">No se encontraron recetas activas para esta tarjeta.</p>
)}
<ul className="rx-list">
{prescriptions.map((rx, i) => (
<li key={i}>
<button className="rx-item" onClick={() => handlePickPrescription(rx)}>
<div className="rx-item-info">
<span className="rx-name">{rx.name}</span>
<span className="rx-detail">{rx.dosage} · {rx.form}</span>
{rx.active_ingredient && (
<span className="rx-ingredient">{rx.active_ingredient}</span>
)}
</div>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="rx-arrow">
<polyline points="9 18 15 12 9 6" />
</svg>
</button>
</li>
))}
</ul>
<button className="scan-btn scan-btn--ghost" onClick={() => {
stopCamera();
setPhase('idle');
setPrescriptions([]);
setScannedCip(null);
}}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="1 4 1 10 7 10" />
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" />
</svg>
Escanear otra tarjeta
</button>
</div>
)}
</div>
</div>
);
}
export default ScannerView;
+305
View File
@@ -0,0 +1,305 @@
.search-view {
width: 100%;
max-width: 48rem;
margin: 0 auto;
}
.search-content {
padding: 1rem var(--margin-main) 2rem;
animation: fadeInUp 0.5s ease-out;
}
.section-title {
font-size: 1.5rem;
font-weight: 700;
color: var(--on-surface);
margin-bottom: 1.25rem;
line-height: 1.2;
}
.suggestions-section {
margin-bottom: 2rem;
}
.suggestions-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--gutter);
}
.suggestion-btn {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
padding: var(--card-padding);
border: none;
border-radius: var(--radius-md);
cursor: pointer;
text-align: left;
transition: all 0.15s;
}
.suggestion-btn:active {
transform: scale(0.96);
}
.suggestion-btn:hover {
background: #83afd6;
font-weight: 700;
}
.suggestion-btn--neutral-1 {
background: #ffffff;
color: #1e293b;
border: 1px solid #e2e8f0;
}
.suggestion-btn--neutral-2 {
background: #f0f7ff;
color: #1e293b;
border: 1px solid #dbeafe;
}
.suggestion-btn--neutral-3 {
background: #e0f0ff;
color: #1e293b;
border: 1px solid #bfdbfe;
}
.suggestion-btn--neutral-4 {
background: #d4ebff;
color: #1e293b;
border: 1px solid #93c5fd;
}
.suggestion-icon {
width: 2.5rem;
height: 2.5rem;
border-radius: var(--radius);
background: rgba(59, 130, 246, 0.08);
color: #3b82f6;
display: flex;
align-items: center;
justify-content: center;
}
.suggestion-name {
font-size: 1.125rem;
font-weight: 700;
line-height: 1.2;
}
.recent-section {
margin-bottom: 2rem;
}
.recent-list {
display: flex;
flex-direction: column;
gap: var(--gutter);
}
.recent-card {
background: var(--surface-container-lowest);
border-radius: var(--radius-md);
box-shadow: var(--shadow-soft);
padding: var(--card-padding);
display: flex;
flex-direction: column;
gap: 0.75rem;
border: 1px solid var(--outline-variant);
}
.recent-card-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 0.5rem;
}
.recent-name {
font-size: 1.25rem;
font-weight: 700;
color: var(--primary);
line-height: 1.2;
}
.recent-detail {
font-size: 1rem;
color: var(--on-surface-variant);
margin-top: 0.125rem;
}
.recent-tag {
padding: 0.25rem 0.75rem;
background: var(--secondary-fixed);
color: var(--on-secondary-fixed-variant);
border-radius: var(--radius-full);
font-size: 0.875rem;
font-weight: 600;
white-space: nowrap;
}
.recent-distance {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--primary);
font-weight: 700;
font-size: 0.875rem;
}
.recent-btn {
width: 100%;
height: var(--touch-target-min);
background: var(--primary-container);
color: var(--on-primary-container);
border: none;
border-radius: var(--radius-md);
font-size: 1rem;
font-weight: 700;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
transition: opacity 0.15s;
}
.recent-btn:active {
opacity: 0.85;
}
.loading {
text-align: center;
color: var(--on-surface-variant);
font-size: 1rem;
font-weight: 500;
margin: 3rem 0;
display: flex;
flex-direction: column;
gap: 1rem;
align-items: center;
}
.loading::after {
content: "";
width: 36px;
height: 36px;
border: 3px solid var(--outline-variant);
border-top-color: var(--primary);
border-radius: 50%;
animation: spin 0.75s linear infinite;
}
.selected-medicine-section {
margin-top: 1.5rem;
max-height: 60vh;
overflow-y: auto;
overscroll-behavior: contain;
}
.medicine-info {
background: var(--surface-container-lowest);
border-radius: var(--radius-md);
padding: 1.5rem;
margin-bottom: 1.5rem;
box-shadow: var(--shadow-soft);
border: 1px solid var(--outline-variant);
}
.medicine-info h2 {
color: var(--on-surface);
margin-bottom: 1rem;
font-size: 1.75rem;
font-weight: 700;
}
.medicine-details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 1rem;
margin-bottom: 1.5rem;
padding: 1rem;
background: var(--surface-container-low);
border-radius: var(--radius);
border: 1px solid var(--outline-variant);
}
.medicine-details span {
font-size: 0.95rem;
color: var(--on-surface-variant);
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.medicine-details strong {
color: var(--on-surface);
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.back-button {
background: var(--surface-container-low);
color: var(--on-surface);
border: 1px solid var(--outline-variant);
padding: 0.75rem 1.5rem;
border-radius: var(--radius);
cursor: pointer;
font-size: 0.9rem;
font-weight: 600;
transition: background 0.15s;
}
.back-button:hover {
background: var(--surface-container);
}
.pharmacy-controls {
display: flex;
align-items: center;
gap: 0.75rem;
margin: 1rem 0 0.5rem;
flex-wrap: wrap;
}
.sort-distance-button {
background: var(--surface-container-lowest);
color: var(--on-surface);
border: 1px solid var(--outline-variant);
padding: 0.6rem 1.1rem;
border-radius: var(--radius-full);
cursor: pointer;
font-size: 0.85rem;
font-weight: 600;
transition: all 0.15s;
}
.sort-distance-button:hover:not(:disabled) {
border-color: var(--primary);
color: var(--primary);
}
.sort-distance-button.active {
background: var(--primary);
border-color: var(--primary);
color: var(--on-primary);
}
.sort-distance-button:disabled {
opacity: 0.6;
cursor: progress;
}
.location-error {
color: var(--error);
font-size: 0.85rem;
}
.location-source {
color: var(--primary);
font-size: 0.85rem;
}
+311
View File
@@ -0,0 +1,311 @@
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import SearchBar from '../components/SearchBar';
import MedicineResults from '../components/MedicineResults';
import PharmacyList from '../components/PharmacyList';
import PharmacyMap from '../components/PharmacyMap';
import { haversineKm, getUserPosition } from '../utils/geo';
import './SearchView.css';
const suggestions = [
{ name: 'Paracetamol', icon: 'medication', color: 'neutral-1' },
{ name: 'Ibuprofeno', icon: 'pill', color: 'neutral-2' },
{ name: 'Aspirina', icon: 'vaccines', color: 'neutral-3' },
{ name: 'Omeprazol', icon: 'emergency_home', color: 'neutral-4' },
];
function SearchView({ currentUser, onLoginRequest }) {
const [searchQuery, setSearchQuery] = useState('');
const [medicines, setMedicines] = useState([]);
const [selectedMedicine, setSelectedMedicine] = useState(null);
const [pharmacies, setPharmacies] = useState([]);
const [loading, setLoading] = useState(false);
const [userPosition, setUserPosition] = useState(null);
const [positionSource, setPositionSource] = useState(null);
const [sortByDistance, setSortByDistance] = useState(false);
const [locating, setLocating] = useState(false);
const [locationError, setLocationError] = useState('');
const [recentSearches, setRecentSearches] = useState([]);
// Fetch recent searches when user is logged in
useEffect(() => {
if (!currentUser) {
setRecentSearches([]);
return;
}
fetch('/api/search/recent', { credentials: 'include' })
.then((r) => r.json())
.then((data) => setRecentSearches(Array.isArray(data) ? data : []))
.catch(() => setRecentSearches([]));
}, [currentUser]);
const saveToRecent = useCallback((medicine) => {
if (!currentUser) return;
fetch('/api/search/recent', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ medicine }),
}).catch(() => {});
// Update local state immediately
setRecentSearches((prev) => {
const filtered = prev.filter((m) => m.id !== medicine.id);
return [
{
id: medicine.id,
name: medicine.name,
active_ingredient: medicine.active_ingredient,
dosage: medicine.dosage,
form: medicine.form,
timestamp: Date.now(),
},
...filtered,
].slice(0, 10);
});
}, [currentUser]);
useEffect(() => {
const searchMedicines = async () => {
if (searchQuery.trim().length < 2) {
setMedicines([]);
setSelectedMedicine(null);
setPharmacies([]);
return;
}
setLoading(true);
try {
const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(searchQuery)}`);
const data = await response.json();
setMedicines(data);
} catch (error) {
console.error('Error searching medicines:', error);
} finally {
setLoading(false);
}
};
const timeoutId = setTimeout(searchMedicines, 300);
return () => clearTimeout(timeoutId);
}, [searchQuery]);
useEffect(() => {
const fetchPharmacies = async () => {
if (!selectedMedicine) {
setPharmacies([]);
return;
}
setLoading(true);
try {
const response = await fetch(`/api/medicines/${selectedMedicine.id}/pharmacies`);
const data = await response.json();
setPharmacies(data);
} catch (error) {
console.error('Error fetching pharmacies:', error);
} finally {
setLoading(false);
}
};
fetchPharmacies();
}, [selectedMedicine]);
const savedLat = currentUser?.latitude;
const savedLon = currentUser?.longitude;
const hasSavedCoords = savedLat != null && savedLon != null;
const handleSortByDistance = async () => {
if (sortByDistance) {
setSortByDistance(false);
return;
}
setLocationError('');
if (hasSavedCoords) {
setUserPosition({ lat: savedLat, lon: savedLon });
setPositionSource('profile');
setSortByDistance(true);
return;
}
if (userPosition) {
setSortByDistance(true);
return;
}
setLocating(true);
try {
const pos = await getUserPosition();
setUserPosition(pos);
setPositionSource('browser');
setSortByDistance(true);
} catch (err) {
let msg = 'No se pudo obtener tu ubicación';
if (err && typeof err.code === 'number') {
if (err.code === 1) msg = 'Permiso de ubicación denegado';
else if (err.code === 2) msg = 'Ubicación no disponible';
else if (err.code === 3) msg = 'La solicitud de ubicación expiró';
}
setLocationError(msg);
} finally {
setLocating(false);
}
};
const displayedPharmacies = useMemo(() => {
if (!sortByDistance || !userPosition) return pharmacies;
return [...pharmacies].sort((a, b) => {
if (a.latitude == null || a.longitude == null) return 1;
if (b.latitude == null || b.longitude == null) return -1;
return (
haversineKm(userPosition.lat, userPosition.lon, a.latitude, a.longitude) -
haversineKm(userPosition.lat, userPosition.lon, b.latitude, b.longitude)
);
});
}, [pharmacies, sortByDistance, userPosition]);
return (
<div className="search-view">
<div className="search-content">
<SearchBar
value={searchQuery}
onChange={setSearchQuery}
placeholder="Escriba el nombre del medicamento"
/>
{loading && <div className="loading">Buscando...</div>}
{!searchQuery && !selectedMedicine && (
<>
<section className="suggestions-section">
<h2 className="section-title">Sugerencias</h2>
<div className="suggestions-grid">
{suggestions.map((s, i) => (
<button
key={i}
className={`suggestion-btn suggestion-btn--${s.color}`}
onClick={() => setSearchQuery(s.name)}
>
<div className="suggestion-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z" />
</svg>
</div>
<span className="suggestion-name">{s.name}</span>
</button>
))}
</div>
</section>
{currentUser && recentSearches.length > 0 && (
<section className="recent-section">
<h2 className="section-title">Resultados Recientes</h2>
<div className="recent-list">
{recentSearches.map((r) => (
<div
key={r.id}
className="recent-card"
onClick={() => setSelectedMedicine(r)}
style={{ cursor: 'pointer' }}
>
<div className="recent-card-top">
<div>
<h3 className="recent-name">{r.name}</h3>
<p className="recent-detail">
{r.dosage && `${r.dosage}`}
{r.dosage && r.form && ' \u2022 '}
{r.form}
</p>
</div>
{r.active_ingredient && (
<span className="recent-tag">{r.active_ingredient}</span>
)}
</div>
<button
className="recent-btn"
onClick={(e) => {
e.stopPropagation();
setSelectedMedicine(r);
}}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
Encontrar cerca
</button>
</div>
))}
</div>
</section>
)}
</>
)}
{searchQuery && !selectedMedicine && (
<MedicineResults
medicines={medicines}
onSelect={(m) => {
saveToRecent(m);
setSelectedMedicine(m);
}}
query={searchQuery}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
)}
{selectedMedicine && (
<div className="selected-medicine-section">
<div className="medicine-info">
<h2>{selectedMedicine.name}</h2>
<div className="medicine-details">
<span><strong>Ingrediente Activo:</strong> {selectedMedicine.active_ingredient}</span>
<span><strong>Dosis:</strong> {selectedMedicine.dosage}</span>
<span><strong>Forma:</strong> {selectedMedicine.form}</span>
</div>
<button
className="back-button"
onClick={() => {
setSelectedMedicine(null);
setPharmacies([]);
}}
>
Volver a búsqueda
</button>
</div>
{pharmacies.length > 0 && (
<div className="pharmacy-controls">
<button
className={`sort-distance-button ${sortByDistance ? 'active' : ''}`}
onClick={handleSortByDistance}
disabled={locating}
>
{locating
? '📍 Localizando…'
: sortByDistance
? '📍 Ordenado por distancia · Reset'
: hasSavedCoords
? '📍 Ordenar por ubicación guardada'
: '📍 Ordenar por distancia'}
</button>
{sortByDistance && positionSource === 'profile' && (
<span className="location-source">Usando tu dirección guardada</span>
)}
{locationError && (
<span className="location-error">{locationError}</span>
)}
</div>
)}
<PharmacyMap pharmacies={displayedPharmacies} />
<PharmacyList
pharmacies={displayedPharmacies}
loading={loading}
userPosition={sortByDistance ? userPosition : null}
medicine={selectedMedicine}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
</div>
)}
</div>
</div>
);
}
export default SearchView;