More changes than expected. Mobile version improvements & PWA
Build & Push Docker Images / test-backend (push) Successful in 44s
Build & Push Docker Images / test-frontend (push) Successful in 52s
Build & Push Docker Images / build-backend (push) Failing after 34s
Build & Push Docker Images / build-frontend (push) Failing after 30s

This commit is contained in:
Ichitux
2026-05-20 22:28:17 +02:00
parent 7b288d33cb
commit 2eff93e66a
118 changed files with 13780 additions and 209 deletions
+2 -1
View File
@@ -2,7 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0f766e" />
<title>FarmaFinder | Find Your Medicine</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+3449 -62
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -20,6 +20,7 @@
"@vitejs/plugin-react": "^4.2.1",
"jsdom": "^24.0.0",
"vite": "^5.0.8",
"vite-plugin-pwa": "^1.3.0",
"vitest": "^1.6.0"
}
}
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" fill="#2563eb"/>
<g fill="#ffffff">
<rect x="216" y="160" width="80" height="192" rx="20"/>
<rect x="160" y="216" width="192" height="80" rx="20"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 268 B

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="96" fill="#2563eb"/>
<g fill="#ffffff">
<rect x="216" y="120" width="80" height="272" rx="20"/>
<rect x="120" y="216" width="272" height="80" rx="20"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 276 B

+191 -3
View File
@@ -42,6 +42,26 @@
box-shadow: inset 0 0 0 1px var(--border);
}
.auth-btn {
background: transparent;
border: none;
color: var(--primary);
padding: 0.55rem 1rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.82rem;
font-weight: 600;
transition: background 0.2s ease;
white-space: nowrap;
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
.auth-btn:hover {
background: var(--surface-muted);
}
.app-header {
text-align: center;
margin-bottom: 4rem;
@@ -179,6 +199,53 @@
transform: translateX(-3px);
}
.pharmacy-controls {
display: flex;
align-items: center;
gap: 0.85rem;
margin: 1.5rem 0 0.5rem;
flex-wrap: wrap;
}
.sort-distance-button {
background: var(--surface);
color: var(--text-main);
border: 1px solid var(--border);
padding: 0.65rem 1.2rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.9rem;
font-weight: 600;
transition: background 0.2s, border-color 0.2s, color 0.2s;
}
.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: #fff;
}
.sort-distance-button:disabled {
opacity: 0.6;
cursor: progress;
}
.location-error {
color: #b91c1c;
font-size: 0.85rem;
}
.location-source {
color: var(--primary);
font-size: 0.85rem;
font-weight: 500;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@@ -195,7 +262,7 @@
@media (max-width: 768px) {
.app {
padding: 2rem 1rem;
padding: 1.5rem 1rem calc(5rem + env(safe-area-inset-bottom));
}
.app-header h1 {
@@ -214,8 +281,129 @@
font-size: 1.65rem;
}
.view-switcher {
position: fixed;
left: 0.75rem;
right: 0.75rem;
bottom: calc(0.75rem + env(safe-area-inset-bottom));
z-index: 100;
width: auto;
max-width: 32rem;
margin: 0 auto;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--surface);
box-shadow:
0 10px 30px rgba(28, 25, 23, 0.12),
0 2px 6px rgba(28, 25, 23, 0.06);
padding: 0.5rem;
overflow: visible;
justify-content: space-around;
align-items: stretch;
gap: 0.25rem;
}
.view-switcher button {
padding: 0.65rem 1.15rem;
font-size: 0.85rem;
flex: 1;
flex-direction: column;
align-items: center;
justify-content: flex-start;
gap: 0.2rem;
padding: 0.4rem 0.3rem 0.45rem;
border-radius: 14px;
font-size: 0.72rem;
font-weight: 500;
color: var(--text-muted);
background: transparent;
position: relative;
overflow: visible;
}
.view-switcher button:hover {
background: transparent;
}
.view-switcher button .nav-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.65rem;
height: 1.65rem;
border-radius: 999px;
font-size: 1.05rem;
line-height: 1;
transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1),
background 0.2s ease,
box-shadow 0.2s ease,
width 0.2s ease,
height 0.2s ease;
}
.view-switcher button .nav-label {
font-size: 0.7rem;
line-height: 1;
max-width: none;
color: inherit;
transition: color 0.2s ease, font-weight 0.2s ease;
}
.view-switcher button.active {
background: transparent;
box-shadow: none;
color: var(--text-main);
}
.view-switcher button.active .nav-icon {
width: 2.7rem;
height: 2.7rem;
background: var(--surface);
color: var(--primary);
font-size: 1.3rem;
border: 1px solid var(--border);
box-shadow:
0 0 0 5px var(--surface),
0 10px 22px rgba(15, 118, 110, 0.22),
0 4px 8px rgba(28, 25, 23, 0.08);
transform: translateY(-1.1rem);
margin-bottom: -0.6rem;
}
.view-switcher button.active .nav-label {
font-weight: 700;
color: var(--text-main);
}
.auth-btn {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
gap: 0.2rem;
padding: 0.4rem 0.3rem 0.45rem;
border-radius: 14px;
color: var(--text-muted);
font-size: 0.72rem;
font-weight: 500;
background: transparent;
}
.auth-btn:hover {
background: transparent;
}
.auth-btn .nav-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.65rem;
height: 1.65rem;
font-size: 1.05rem;
line-height: 1;
}
.auth-btn .nav-label {
font-size: 0.7rem;
line-height: 1;
}
}
+96 -13
View File
@@ -1,29 +1,112 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import './App.css';
import PublicView from './views/PublicView';
import AdminView from './views/AdminView';
import ProfileView from './views/ProfileView';
import LoginModal from './components/LoginModal';
import SavedNotifications from './components/SavedNotifications';
function App() {
const [view, setView] = useState('public'); // 'public' or 'admin'
const [view, setView] = useState('public');
const [currentUser, setCurrentUser] = useState(null);
const [authChecked, setAuthChecked] = useState(false);
const [showLogin, setShowLogin] = useState(false);
const [showSaved, setShowSaved] = useState(false);
useEffect(() => {
fetch('/api/auth/check')
.then(r => r.json())
.then(data => { if (data.authenticated) setCurrentUser(data.user); })
.catch(() => {})
.finally(() => setAuthChecked(true));
}, []);
function handleLogin(user) {
setCurrentUser(user);
setShowLogin(false);
}
async function handleLogout() {
await fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
setCurrentUser(null);
setView('public');
}
function handleProfileSaved(updated) {
setCurrentUser(prev => ({ ...prev, ...updated }));
}
const isAdmin = Boolean(currentUser?.is_admin);
let activeView;
if (view === 'profile' && currentUser) {
activeView = (
<ProfileView
currentUser={currentUser}
onProfileSaved={handleProfileSaved}
onShowSaved={() => setShowSaved(true)}
onLogout={handleLogout}
/>
);
} else if (view === 'admin' && isAdmin) {
activeView = <AdminView />;
} else {
activeView = (
<PublicView
currentUser={currentUser}
onLoginRequest={() => setShowLogin(true)}
/>
);
}
return (
<div className="app">
<div className="view-switcher">
<button
<nav className="view-switcher" aria-label="Primary">
<button
className={view === 'public' ? 'active' : ''}
onClick={() => setView('public')}
>
🔍 Public Search
<span className="nav-icon">🔍</span>
<span className="nav-label">Search</span>
</button>
<button
className={view === 'admin' ? 'active' : ''}
onClick={() => setView('admin')}
>
Admin Panel
</button>
</div>
{isAdmin && (
<button
className={view === 'admin' ? 'active' : ''}
onClick={() => setView('admin')}
>
<span className="nav-icon"></span>
<span className="nav-label">Admin</span>
</button>
)}
{authChecked && currentUser && (
<button
className={view === 'profile' ? 'active' : ''}
onClick={() => setView('profile')}
>
<span className="nav-icon">👤</span>
<span className="nav-label">Profile</span>
</button>
)}
{authChecked && !currentUser && (
<button className="auth-btn" onClick={() => setShowLogin(true)}>
<span className="nav-icon"></span>
<span className="nav-label">Login</span>
</button>
)}
</nav>
{view === 'public' ? <PublicView /> : <AdminView />}
{activeView}
{showLogin && (
<LoginModal
onLogin={handleLogin}
onClose={() => setShowLogin(false)}
/>
)}
{showSaved && currentUser && (
<SavedNotifications onClose={() => setShowSaved(false)} />
)}
</div>
);
}
+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('Password must be at least 8 characters');
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' ? 'Could not create account' : 'Login failed'));
} else {
onLogin(data.user);
}
} catch {
setError('Network error — try again');
} 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}
>
Sign in
</button>
<button
type="button"
role="tab"
aria-selected={isRegister}
className={`modal-tab${isRegister ? ' is-active' : ''}`}
onClick={() => setMode('register')}
disabled={loading}
>
Create account
</button>
</div>
<h2 id="modal-title">{isRegister ? 'Create your account' : 'Welcome back'}</h2>
<p className="modal-sub">
{isRegister
? 'Save your address and get notified when medicines arrive.'
: 'Sign in to manage your profile and notifications.'}
</p>
<form onSubmit={handleSubmit} noValidate>
<div className="modal-field">
<label htmlFor="modal-username">Username</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 characters: letters, digits, or underscore.</p>
)}
</div>
<div className="modal-field">
<label htmlFor="modal-password">Password</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">At least 8 characters.</p>
)}
</div>
{error && <p className="modal-error">{error}</p>}
<div className="modal-actions">
<button
type="button"
className="modal-cancel"
onClick={onClose}
disabled={loading}
>
Cancel
</button>
<button
type="submit"
className="modal-submit"
disabled={loading || !username.trim() || !password}
>
{loading
? (isRegister ? 'Creating…' : 'Signing in…')
: (isRegister ? 'Create account' : 'Sign in')}
</button>
</div>
</form>
</div>
</div>
);
}
export default LoginModal;
+82 -11
View File
@@ -19,23 +19,98 @@
box-shadow: 0 1px 3px rgba(28, 25, 23, 0.04);
}
.medicine-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 28px rgba(28, 25, 23, 0.08);
border-color: var(--primary);
@media (hover: hover) {
.medicine-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 28px rgba(28, 25, 23, 0.08);
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(--text-main);
margin-bottom: 0.75rem;
font-size: 1.2rem;
font-weight: 700;
letter-spacing: -0.01em;
transition: color 0.2s;
flex: 1;
margin: 0;
}
.medicine-card:hover h3 {
color: var(--primary);
.notify-bell {
background: var(--surface-muted, #f5f5f4);
border: 1px solid var(--border, #e7e5e4);
border-radius: 999px;
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;
}
@media (hover: hover) {
.notify-bell:hover:not(:disabled) {
border-color: var(--primary, #2563eb);
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, #2563eb);
border-color: var(--primary, #2563eb);
}
.notify-bell--locked {
opacity: 0.55;
}
@media (hover: hover) {
.notify-bell--locked:hover:not(:disabled) {
border-color: var(--text-muted, #78716c);
transform: scale(1.05);
}
}
.notify-error {
margin-top: 0.5rem;
font-size: 0.78rem;
color: #b91c1c;
}
@media (hover: hover) {
.medicine-card:hover h3 {
color: var(--primary);
}
.medicine-card:hover .view-pharmacies::after {
transform: translateX(4px);
}
}
.medicine-card-body {
@@ -73,10 +148,6 @@
transition: transform 0.2s;
}
.medicine-card:hover .view-pharmacies::after {
transform: translateX(4px);
}
.no-results {
text-align: center;
padding: 2.75rem 1.5rem;
+95 -19
View File
@@ -1,7 +1,13 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import './MedicineResults.css';
import {
pushSupported,
isSubscribedLocally,
subscribeToPush,
unsubscribeFromPush,
} from '../utils/notifications.js';
function MedicineResults({ medicines, onSelect, query }) {
function MedicineResults({ medicines, onSelect, query, currentUser, onLoginRequest }) {
if (medicines.length === 0 && query.length >= 2) {
return (
<div className="no-results">
@@ -13,26 +19,96 @@ function MedicineResults({ medicines, onSelect, query }) {
return (
<div className="medicine-results">
{medicines.map((medicine) => (
<div
key={medicine.id}
className="medicine-card"
onClick={() => onSelect(medicine)}
>
<div className="medicine-card-header">
<h3>{medicine.name}</h3>
</div>
<div className="medicine-card-body">
<p><strong>Active Ingredient:</strong> {medicine.active_ingredient}</p>
<p><strong>Dosage:</strong> {medicine.dosage} <strong>Form:</strong> {medicine.form}</p>
</div>
<div className="medicine-card-footer">
<span className="view-pharmacies">View pharmacies </span>
</div>
</div>
<MedicineCard
key={medicine.nregistro || medicine.id}
medicine={medicine}
onSelect={onSelect}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
))}
</div>
);
}
export default MedicineResults;
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('Notifications need iOS 16.4+ and this site installed as an app (Share → Add to Home Screen).');
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 || 'Could not update subscription');
} 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
? 'Login to enable notifications'
: subscribed
? 'Stop notifications for this medicine'
: 'Notify me when this medicine becomes available'
}
title={
!currentUser
? 'Login to enable notifications'
: subscribed
? 'Notifications on — click to turn off'
: 'Notify me when this medicine is added to a pharmacy'
}
>
{subscribed && currentUser ? '🔔' : '🔕'}
</button>
</div>
<div className="medicine-card-body">
<p><strong>Active Ingredient:</strong> {medicine.active_ingredient}</p>
<p><strong>Dosage:</strong> {medicine.dosage} <strong>Form:</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">View pharmacies </span>
</div>
</div>
);
}
export default MedicineResults;
+122 -6
View File
@@ -28,22 +28,112 @@
box-shadow: 0 1px 3px rgba(28, 25, 23, 0.04);
}
.pharmacy-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 28px rgba(28, 25, 23, 0.08);
border-color: var(--primary);
@media (hover: hover) {
.pharmacy-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 28px rgba(28, 25, 23, 0.08);
border-color: var(--primary);
}
}
.pharmacy-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 1rem;
}
.pharmacy-header h4 {
color: var(--text-main);
font-weight: 700;
margin-bottom: 1rem;
margin: 0;
font-size: 1.1rem;
transition: color 0.2s;
flex: 1;
}
.pharmacy-card:hover .pharmacy-header h4 {
.pharmacy-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.notify-bell {
background: var(--surface-muted, #f5f5f4);
border: 1px solid var(--border, #e7e5e4);
border-radius: 999px;
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;
}
@media (hover: hover) {
.notify-bell:hover:not(:disabled) {
border-color: var(--primary, #2563eb);
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, #2563eb);
border-color: var(--primary, #2563eb);
}
.notify-bell--locked {
opacity: 0.55;
}
@media (hover: hover) {
.notify-bell--locked:hover:not(:disabled) {
border-color: var(--text-muted, #78716c);
transform: scale(1.05);
}
}
.notify-error {
margin-top: 0.5rem;
font-size: 0.78rem;
color: #b91c1c;
}
.pharmacy-distance {
flex-shrink: 0;
background: rgba(37, 99, 235, 0.1);
color: var(--primary);
font-size: 0.78rem;
font-weight: 700;
padding: 0.3rem 0.7rem;
border-radius: 999px;
letter-spacing: 0.02em;
white-space: nowrap;
}
@media (hover: hover) {
.pharmacy-card:hover .pharmacy-header h4 {
color: var(--primary);
}
}
.pharmacy-details {
@@ -60,6 +150,32 @@
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: 999px;
background: currentColor;
}
.pharmacy-hours--open {
color: var(--accent, #047857);
}
.pharmacy-hours--closed {
color: var(--text-muted);
}
.pharmacy-pricing {
display: flex;
justify-content: space-between;
+134 -26
View File
@@ -1,7 +1,15 @@
import React from 'react';
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 }) {
function PharmacyList({ pharmacies, loading, userPosition, medicine, currentUser, onLoginRequest }) {
if (loading) {
return (
<div className="loading-pharmacies">
@@ -24,33 +32,133 @@ function PharmacyList({ pharmacies, loading }) {
Available at {pharmacies.length} {pharmacies.length === 1 ? 'pharmacy' : 'pharmacies'}
</h3>
<div className="pharmacy-grid">
{pharmacies.map((pharmacy) => (
<div key={pharmacy.id} className="pharmacy-card">
<div className="pharmacy-header">
<h4>🏥 {pharmacy.name}</h4>
</div>
<div className="pharmacy-details">
<p className="pharmacy-address">📍 {pharmacy.address}</p>
{pharmacy.phone && (
<p className="pharmacy-phone">📞 {pharmacy.phone}</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 ? '✓ In Stock' : pharmacy.stock > 0 ? `⚠ Low Stock (${pharmacy.stock})` : '✗ Out of Stock'}
</span>
)}
</div>
</div>
</div>
))}
{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('Notifications need iOS 16.4+ and this site installed as an app (Share → Add to Home Screen).');
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 || 'Could not update subscription');
} 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
? 'Login to enable notifications'
: subscribed
? 'Stop notifications for this pharmacy'
: 'Notify me when this medicine arrives at this pharmacy'
}
title={
!currentUser
? 'Login to enable notifications'
: subscribed
? 'Notifications on for this pharmacy — click to turn off'
: 'Notify me when this medicine arrives at this pharmacy'
}
>
{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 ? '✓ In Stock' : pharmacy.stock > 0 ? `⚠ Low Stock (${pharmacy.stock})` : '✗ Out of Stock'}
</span>
)}
</div>
</div>
</div>
);
}
export default PharmacyList;
@@ -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: rgba(37, 99, 235, 0.08);
color: var(--primary, #2563eb);
font-size: 0.75rem;
font-weight: 600;
width: fit-content;
}
.saved-notifications-chip--pharmacy {
background: rgba(4, 120, 87, 0.1);
color: var(--accent, #047857);
}
.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 || 'Could not load saved notifications');
} 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 || 'Could not remove notification');
} 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>🔔 Saved Notifications</h2>
<button className="saved-notifications-close" onClick={onClose} aria-label="Close">×</button>
</div>
<div className="saved-notifications-body">
{loading && <p className="saved-notifications-status">Loading</p>}
{!loading && error && <p className="saved-notifications-error">{error}</p>}
{!loading && !error && items.length === 0 && (
<p className="saved-notifications-empty">
No saved notifications yet. Tap the 🔕 bell on an out-of-stock pharmacy to get notified when it's restocked.
</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 || `Pharmacy #${item.pharmacy_id}`}
</span>
{item.pharmacy_address && (
<span className="saved-notifications-address">{item.pharmacy_address}</span>
)}
</>
) : (
<span className="saved-notifications-chip">
Any pharmacy
</span>
)}
</div>
</div>
<button
type="button"
className="saved-notifications-remove"
onClick={() => handleDelete(item)}
disabled={busyId === key}
aria-label="Remove notification"
>
{busyId === key ? '' : 'Remove'}
</button>
</li>
);
})}
</ul>
)}
</div>
</div>
</div>
);
}
export default SavedNotifications;
@@ -78,6 +78,83 @@
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,
@@ -1,5 +1,47 @@
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) {
@@ -59,6 +101,7 @@ function PharmacyManagement() {
latitude: '',
longitude: '',
});
const [hoursDraft, setHoursDraft] = useState(() => emptyHoursDraft());
const [cityQuery, setCityQuery] = useState('');
const [cityLookupLoading, setCityLookupLoading] = useState(false);
@@ -251,6 +294,7 @@ function PharmacyManagement() {
...formData,
latitude: formData.latitude ? parseFloat(formData.latitude) : null,
longitude: formData.longitude ? parseFloat(formData.longitude) : null,
opening_hours: draftToHours(hoursDraft),
};
if (editingPharmacy) {
@@ -299,6 +343,7 @@ function PharmacyManagement() {
latitude: pharmacy.latitude ?? '',
longitude: pharmacy.longitude ?? '',
});
setHoursDraft(hoursToDraft(pharmacy.opening_hours));
setShowForm(true);
};
@@ -329,10 +374,15 @@ function PharmacyManagement() {
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);
@@ -571,6 +621,42 @@ function PharmacyManagement() {
</div>
</div>
<fieldset className="hours-editor">
<legend>Opening hours</legend>
<p className="hours-editor-hint">Leave a day checked as <em>Closed</em> if the pharmacy doesn't open that day.</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 })}
/>
Closed
</label>
<input
type="time"
value={d.open}
disabled={d.closed}
onChange={(e) => updateDay(day, { open: e.target.value })}
aria-label={`${DAY_LABEL[day]} opens at`}
/>
<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]} closes at`}
/>
</div>
);
})}
</fieldset>
<div className="form-actions">
<button type="submit" className="btn-primary" disabled={saving}>
{saving ? 'Saving...' : editingPharmacy ? 'Update' : 'Add'} Pharmacy
@@ -1,6 +1,12 @@
import React, { useState, useEffect } from 'react';
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('');
@@ -10,12 +16,27 @@ function PharmacyMedicineLink() {
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();
}, []);
@@ -172,14 +193,27 @@ function PharmacyMedicineLink() {
setMedicineResults([]);
};
const selectedPharmacyObj = pharmacies.find(p => p.id === parseInt(formData.pharmacy_id));
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>Link Medicine to Pharmacy</h2>
@@ -187,22 +221,53 @@ function PharmacyMedicineLink() {
<form className="admin-form" onSubmit={handleSubmit}>
<div className="form-group">
<label>Pharmacy *</label>
<select
value={formData.pharmacy_id}
<input
ref={pharmacyInputRef}
type="text"
value={pharmacyQuery}
onChange={(e) => {
const pharmacy = pharmacies.find(p => p.id === parseInt(e.target.value));
setSelectedPharmacy(pharmacy);
setFormData({ ...formData, pharmacy_id: e.target.value });
setPharmacyQuery(e.target.value);
if (selectedPharmacy) {
setSelectedPharmacy(null);
setFormData(prev => ({ ...prev, pharmacy_id: '' }));
}
setPharmacyDropdownOpen(true);
}}
required
>
<option value="">Select a pharmacy</option>
{pharmacies.map((pharmacy) => (
<option key={pharmacy.id} value={pharmacy.id}>
{pharmacy.name} - {pharmacy.address}
</option>
))}
</select>
onFocus={() => setPharmacyDropdownOpen(true)}
onBlur={() => setTimeout(() => setPharmacyDropdownOpen(false), 150)}
placeholder={pharmacies.length ? `Search ${pharmacies.length} pharmacies by name or address…` : 'Loading pharmacies…'}
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 pharmacies match "{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}>
Change pharmacy
</button>
</div>
)}
</div>
<div className="form-group">
+9 -2
View File
@@ -34,6 +34,11 @@
box-sizing: border-box;
}
html, body {
overscroll-behavior: none;
overflow-x: hidden;
}
body {
font-family: 'Outfit', system-ui, sans-serif;
color: var(--text-main);
@@ -44,11 +49,13 @@ body {
background-size: cover;
background-position: center;
background-attachment: fixed;
min-height: 100vh;
min-height: 100svh;
min-height: 100dvh;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#root {
min-height: 100vh;
min-height: 100svh;
min-height: 100dvh;
}
+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: 'FarmaFinder', body: event.data.text() };
}
}
const title = data.title || 'FarmaFinder';
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);
})
);
});
+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('Geolocation not supported by this browser'));
return;
}
if (typeof window !== 'undefined' && window.isSecureContext === false) {
reject(new Error('Geolocation requires HTTPS (or 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: 'Sunday',
mon: 'Monday',
tue: 'Tuesday',
wed: 'Wednesday',
thu: 'Thursday',
fri: 'Friday',
sat: 'Saturday',
};
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 `tomorrow at ${openStr}`;
return `${DAY_LABELS[day]} at ${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 ? `Closed · Opens ${next}` : 'Closed' };
}
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: `Closed · Opens at ${range[0]}` };
}
if (nowMins >= closeMins) {
const next = findNextOpen(hours, now);
return { status: 'closed', label: next ? `Closed · Opens ${next}` : 'Closed' };
}
return { status: 'open', label: `Open · Closes at ${range[1]}` };
}
export function emptyHours() {
return { sun: null, mon: null, tue: null, wed: null, thu: null, fri: null, sat: null };
}
+128
View File
@@ -0,0 +1,128 @@
const STORAGE_KEY = 'farmafinder.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');
if (!res.ok) {
const message = res.status === 503
? 'Push notifications are not configured on the server yet'
: `Could not fetch VAPID key (HTTP ${res.status})`;
throw new Error(message);
}
const { publicKey } = await res.json();
if (!publicKey) throw new Error('Server returned an empty VAPID key');
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('Push notifications are not supported in this browser');
}
if (window.isSecureContext === false) {
throw new Error('Push notifications require HTTPS (or localhost)');
}
const reg = await navigator.serviceWorker.ready;
let sub = await reg.pushManager.getSubscription();
if (sub) return sub;
if (Notification.permission === 'denied') {
throw new Error('Notification permission was denied — enable it in browser settings');
}
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',
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(`Subscribe failed (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',
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));
}
+260
View File
@@ -0,0 +1,260 @@
.profile-view {
width: 100%;
max-width: 640px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: fadeInUp 0.5s ease-out;
}
.profile-header {
display: flex;
align-items: center;
gap: 1.1rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.4rem 1.5rem;
box-shadow: var(--glass-shadow);
}
.profile-avatar {
width: 3.5rem;
height: 3.5rem;
border-radius: 50%;
background: var(--primary-faint);
color: var(--primary);
font-size: 1.8rem;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.profile-info h2 {
margin: 0;
font-size: 1.4rem;
font-weight: 700;
color: var(--text-main);
letter-spacing: -0.01em;
}
.profile-role {
margin: 0.25rem 0 0;
font-size: 0.85rem;
color: var(--text-muted);
}
.profile-pill {
color: var(--primary);
font-weight: 600;
}
.profile-section {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.4rem 1.5rem;
box-shadow: var(--glass-shadow);
}
.profile-section h3 {
margin: 0 0 0.35rem;
font-size: 1.05rem;
font-weight: 700;
color: var(--text-main);
}
.profile-section-sub {
margin: 0 0 1.1rem;
color: var(--text-muted);
font-size: 0.88rem;
line-height: 1.45;
}
.profile-form {
display: flex;
flex-direction: column;
gap: 0.95rem;
}
.profile-field {
display: flex;
flex-direction: column;
gap: 0.35rem;
flex: 1;
min-width: 0;
}
.profile-field label {
font-size: 0.78rem;
font-weight: 600;
color: var(--text-muted);
letter-spacing: 0.02em;
}
.profile-field input {
padding: 0.65rem 0.85rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--surface-muted);
color: var(--text-main);
font-size: 0.95rem;
outline: none;
transition: border-color 0.15s ease, background 0.15s ease;
width: 100%;
}
.profile-field input:focus {
border-color: var(--primary);
background: var(--surface);
}
.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-muted);
border: 1px solid var(--border);
color: var(--text-main);
padding: 0.55rem 1rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.83rem;
font-weight: 600;
transition: background 0.15s, border-color 0.15s, color 0.15s;
}
.profile-btn-secondary:hover:not(:disabled) {
border-color: var(--primary);
color: var(--primary);
}
.profile-btn-secondary:disabled {
opacity: 0.6;
cursor: progress;
}
.profile-feedback {
margin: 0;
font-size: 0.85rem;
padding: 0.55rem 0.75rem;
border-radius: var(--radius-sm);
line-height: 1.4;
}
.profile-feedback--ok {
background: var(--primary-faint);
color: var(--primary);
border: 1px solid var(--primary-ring);
}
.profile-feedback--err {
background: rgba(185, 28, 28, 0.08);
color: #b91c1c;
border: 1px solid rgba(185, 28, 28, 0.2);
}
.profile-actions {
display: flex;
justify-content: flex-end;
margin-top: 0.2rem;
}
.profile-btn-primary {
background: var(--primary);
color: #fff;
border: none;
padding: 0.65rem 1.6rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.9rem;
font-weight: 700;
transition: background 0.15s, opacity 0.15s;
}
.profile-btn-primary:hover:not(:disabled) {
background: var(--primary-hover);
}
.profile-btn-primary:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.profile-link-row {
display: flex;
align-items: center;
gap: 0.85rem;
width: 100%;
padding: 0.8rem 0.5rem;
background: transparent;
border: none;
border-bottom: 1px solid var(--border);
cursor: pointer;
text-align: left;
font-size: 0.95rem;
color: var(--text-main);
transition: background 0.12s ease;
}
.profile-link-row:last-child {
border-bottom: none;
}
.profile-link-row:hover {
background: var(--surface-muted);
}
.profile-link-row-icon {
font-size: 1.1rem;
width: 1.5rem;
text-align: center;
}
.profile-link-row-label {
flex: 1;
font-weight: 500;
}
.profile-link-row-chevron {
color: var(--text-muted);
font-size: 1.2rem;
line-height: 1;
}
.profile-link-row--danger {
color: #b91c1c;
}
.profile-link-row--danger:hover {
background: rgba(185, 28, 28, 0.06);
}
@media (max-width: 540px) {
.profile-field-row {
flex-direction: column;
gap: 0.95rem;
}
.profile-header {
padding: 1.1rem 1.1rem;
}
.profile-section {
padding: 1.1rem 1.1rem;
}
}
+222
View File
@@ -0,0 +1,222 @@
import React, { useEffect, useState } from 'react';
import './ProfileView.css';
import { getUserPosition } from '../utils/geo';
function ProfileView({ currentUser, onProfileSaved, onShowSaved, onLogout }) {
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 || `Save failed (HTTP ${res.status})`);
}
const updated = await res.json();
onProfileSaved?.(updated);
setFeedback({ type: 'ok', text: 'Profile saved.' });
} catch (err) {
setFeedback({ type: 'err', text: err.message || 'Save failed' });
} 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: 'Got your current location — remember to Save.' });
} catch (err) {
let msg = err && err.message ? err.message : 'Could not get location';
if (err && typeof err.code === 'number') {
if (err.code === 1) msg = 'Location permission denied — allow it in your browser settings.';
else if (err.code === 2) msg = 'Location unavailable — check OS location services.';
else if (err.code === 3) msg = 'Location request timed out — try again.';
}
setFeedback({ type: 'err', text: msg });
} finally {
setLocating(false);
}
}
async function handleGeocode() {
const q = address.trim();
if (!q) {
setFeedback({ type: 'err', text: 'Enter an address first.' });
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 || `Lookup failed (HTTP ${res.status})`);
}
const data = await res.json();
setLatitude(String(data.lat));
setLongitude(String(data.lon));
setFeedback({
type: 'ok',
text: `Located: ${data.displayName} — remember to Save.`,
});
} catch (err) {
setFeedback({ type: 'err', text: err.message || 'Lookup failed' });
} finally {
setGeocoding(false);
}
}
const hasSavedCoords =
currentUser?.latitude != null && currentUser?.longitude != null;
return (
<div className="profile-view">
<header className="profile-header">
<div className="profile-avatar" aria-hidden="true">👤</div>
<div className="profile-info">
<h2>{currentUser?.username}</h2>
<p className="profile-role">
{currentUser?.is_admin ? 'Administrator' : 'Member'}
{hasSavedCoords && <span className="profile-pill"> · Location saved</span>}
</p>
</div>
</header>
<section className="profile-section">
<h3>Your location</h3>
<p className="profile-section-sub">
Save your address so "Sort by distance" uses it without asking the browser every time.
</p>
<form onSubmit={handleSave} className="profile-form">
<div className="profile-field">
<label htmlFor="profile-address">Address</label>
<input
id="profile-address"
type="text"
placeholder="123 Main St, Madrid, Spain"
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">Latitude</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">Longitude</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 ? 'Finding…' : '📍 Find from address'}
</button>
<button
type="button"
className="profile-btn-secondary"
onClick={handleUseLocation}
disabled={locating || saving}
>
{locating ? 'Locating…' : '🛰️ Use my current location'}
</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 ? 'Saving…' : 'Save profile'}
</button>
</div>
</form>
</section>
<section className="profile-section">
<h3>Account</h3>
<button type="button" className="profile-link-row" onClick={onShowSaved}>
<span className="profile-link-row-icon">🔔</span>
<span className="profile-link-row-label">Saved notifications</span>
<span className="profile-link-row-chevron" aria-hidden="true"></span>
</button>
<button
type="button"
className="profile-link-row profile-link-row--danger"
onClick={onLogout}
>
<span className="profile-link-row-icon"></span>
<span className="profile-link-row-label">Logout</span>
<span className="profile-link-row-chevron" aria-hidden="true"></span>
</button>
</section>
</div>
);
}
export default ProfileView;
+98 -8
View File
@@ -1,16 +1,22 @@
import React, { useState, useEffect } from 'react';
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 { haversineKm, getUserPosition } from '../utils/geo';
function PublicView() {
function PublicView({ 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); // 'profile' | 'browser'
const [sortByDistance, setSortByDistance] = useState(false);
const [locating, setLocating] = useState(false);
const [locationError, setLocationError] = useState('');
useEffect(() => {
const searchMedicines = async () => {
@@ -59,6 +65,61 @@ function PublicView() {
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 = 'Location permission denied — allow it in your browser settings';
else if (err.code === 2) msg = 'Location unavailable — check OS location services / WiFi';
else if (err.code === 3) msg = 'Location request timed out — try again';
else msg = `Geolocation error (code ${err.code})`;
} else {
msg = err && err.message ? err.message : 'Could not get your location';
}
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 (
<>
<header className="app-header">
@@ -67,7 +128,7 @@ function PublicView() {
</header>
<main className="app-main">
<SearchBar
<SearchBar
value={searchQuery}
onChange={setSearchQuery}
placeholder="Search for a medicine..."
@@ -76,10 +137,12 @@ function PublicView() {
{loading && <div className="loading">Searching...</div>}
{searchQuery && !selectedMedicine && (
<MedicineResults
<MedicineResults
medicines={medicines}
onSelect={setSelectedMedicine}
query={searchQuery}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
)}
@@ -92,7 +155,7 @@ function PublicView() {
<span><strong>Dosage:</strong> {selectedMedicine.dosage}</span>
<span><strong>Form:</strong> {selectedMedicine.form}</span>
</div>
<button
<button
className="back-button"
onClick={() => {
setSelectedMedicine(null);
@@ -103,10 +166,38 @@ function PublicView() {
</button>
</div>
<PharmacyMap pharmacies={pharmacies} />
{pharmacies.length > 0 && (
<div className="pharmacy-controls">
<button
className={`sort-distance-button ${sortByDistance ? 'active' : ''}`}
onClick={handleSortByDistance}
disabled={locating}
>
{locating
? '📍 Locating…'
: sortByDistance
? '📍 Sorted by distance · Reset'
: hasSavedCoords
? '📍 Sort by your saved location'
: '📍 Sort by distance'}
</button>
{sortByDistance && positionSource === 'profile' && (
<span className="location-source">Using your saved address</span>
)}
{locationError && (
<span className="location-error">{locationError}</span>
)}
</div>
)}
<PharmacyMap pharmacies={displayedPharmacies} />
<PharmacyList
pharmacies={pharmacies}
pharmacies={displayedPharmacies}
loading={loading}
userPosition={sortByDistance ? userPosition : null}
medicine={selectedMedicine}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
</div>
)}
@@ -116,4 +207,3 @@ function PublicView() {
}
export default PublicView;
+31 -2
View File
@@ -1,15 +1,44 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [react()],
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
strategies: 'injectManifest',
srcDir: 'src',
filename: 'sw.js',
injectRegister: 'auto',
devOptions: {
enabled: true,
type: 'module',
navigateFallback: 'index.html',
},
manifest: {
name: 'FarmaFinder',
short_name: 'FarmaFinder',
description: 'Find pharmacies that stock the medicine you need',
theme_color: '#0f766e',
background_color: '#ffffff',
display: 'standalone',
start_url: '/',
icons: [
{ src: '/icon.svg', sizes: '192x192', type: 'image/svg+xml', purpose: 'any' },
{ src: '/icon.svg', sizes: '512x512', type: 'image/svg+xml', purpose: 'any' },
{ src: '/icon-mask.svg', sizes: '512x512', type: 'image/svg+xml', purpose: 'maskable' },
],
},
}),
],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.js'],
globals: true,
},
server: {
allowedHosts: ['localhost', 'oligocarpous-bilaterally-keiko.ngrok-free.dev'],
allowedHosts: ['localhost', 'farmacias.hacecalor.net'],
port: 3000,
proxy: {
'/api': {