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
+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;