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
+15 -1
View File
@@ -6,7 +6,21 @@
"Bash(npm test *)",
"Bash(npx vitest *)",
"Bash(./node_modules/.bin/vitest run *)",
"Bash(git -C /home/f80ans0/Projects/Webs/FarmaFinder remote -v)"
"Bash(git -C /home/f80ans0/Projects/Webs/FarmaFinder remote -v)",
"Bash(grep -E \"^\\(express|sqlite3|bcrypt|axios|cors|redis|connect-sqlite3|express-session|express-rate-limit\\)$\")",
"Bash(grep -E \"^\\(react-leaflet|leaflet\\)$\")",
"Bash(grep -E \"^\\(connect-sqlite3|express-rate-limit\\)$\")",
"Bash(node --check server.js)",
"Bash(node --input-type=module -e ' *)",
"Bash(node *)",
"Bash(kill 1043357 1043372 1043383 1043384 1043416 1043417 1043457 1043463 1043479 1061932)",
"Bash(NODE_OPTIONS=--experimental-vm-modules npx jest)",
"Bash(npx vite *)",
"Bash(curl -sL -o /tmp/ref-nav.png \"https://theuistudio.com/blog/wp-content/uploads/2025/09/image-8.png\")",
"WebFetch(domain:dev.to)",
"Bash(command -v npx node java)",
"Bash(npx --version)",
"Bash(npx cap *)"
]
}
}
+1
View File
@@ -1,5 +1,6 @@
node_modules/
dist/
dev-dist/
build/
*.sqlite
*.sqlite3
+5
View File
@@ -2,6 +2,8 @@
* Shared helpers: OSM tags → single-line address, element → pharmacy row.
*/
import { parseOsmOpeningHours } from './opening-hours-osm.js';
export function buildAddressFromOsmTags(tags) {
if (!tags || typeof tags !== 'object') return '';
if (tags['addr:full'] && String(tags['addr:full']).trim()) {
@@ -47,11 +49,14 @@ export function osmElementToPharmacy(el) {
const phone =
tags.phone || tags['contact:phone'] || tags['contact:mobile'] || tags['contact:whatsapp'] || null;
const opening_hours = parseOsmOpeningHours(tags.opening_hours);
return {
name,
address: address || null,
phone: phone ? String(phone).trim() : null,
latitude: Number.isFinite(lat) ? lat : null,
longitude: Number.isFinite(lon) ? lon : null,
opening_hours: opening_hours || null,
};
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Parse a subset of the OSM opening_hours format into FarmaFinder's internal
* shape: { mon: ["09:00", "21:00"], ..., sun: null }.
*
* Supports the patterns commonly seen on amenity=pharmacy nodes:
* "24/7"
* "Mo-Fr 09:00-21:00"
* "Mo-Fr 09:00-21:00; Sa 09:00-14:00; Su closed"
* "Mo,We,Fr 09:00-14:00"
* "Mo-Fr 09:00-13:30,16:30-20:00" (split shifts: opens first, closes last)
*
* Public-holiday rules (PH/SH) and weeknumber/date filters are ignored.
* Returns null if no usable rule was found.
*
* @param {string} input
* @returns {{mon: string[]|null, tue: string[]|null, wed: string[]|null, thu: string[]|null, fri: string[]|null, sat: string[]|null, sun: string[]|null}|null}
*/
export function parseOsmOpeningHours(input) {
if (!input || typeof input !== 'string') return null;
const cleaned = input.trim().replace(/\s+/g, ' ');
if (!cleaned) return null;
const result = { mon: null, tue: null, wed: null, thu: null, fri: null, sat: null, sun: null };
if (/^24\s*\/\s*7$/i.test(cleaned)) {
for (const k of Object.keys(result)) result[k] = ['00:00', '24:00'];
return result;
}
const rules = cleaned.split(';').map(r => r.trim()).filter(Boolean);
let anySet = false;
for (const rule of rules) {
const ruleNoComment = rule.replace(/\([^)]*\)/g, '').trim();
if (!ruleNoComment) continue;
const lower = ruleNoComment.toLowerCase();
if (lower === 'closed' || lower === 'off') continue;
const tokens = ruleNoComment.split(/\s+/);
const dayPart = tokens.shift();
const timePart = tokens.join(' ').trim();
if (!dayPart) continue;
const days = expandDayPart(dayPart);
if (!days.length) continue;
if (!timePart || /^(off|closed)$/i.test(timePart)) {
for (const d of days) result[d] = null;
anySet = true;
continue;
}
const range = collapseTimeRanges(timePart);
if (!range) continue;
for (const d of days) result[d] = range;
anySet = true;
}
return anySet ? result : null;
}
const DAY_CODE_TO_KEY = { mo: 'mon', tu: 'tue', we: 'wed', th: 'thu', fr: 'fri', sa: 'sat', su: 'sun' };
const DAY_ORDER = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
function expandDayPart(dayPart) {
const out = new Set();
for (const segment of dayPart.split(',')) {
const seg = segment.trim();
if (!seg) continue;
if (/^(ph|sh)(-(ph|sh))?$/i.test(seg)) continue;
const rangeMatch = seg.match(/^([A-Za-z]{2})-([A-Za-z]{2})$/);
if (rangeMatch) {
const a = DAY_CODE_TO_KEY[rangeMatch[1].toLowerCase()];
const b = DAY_CODE_TO_KEY[rangeMatch[2].toLowerCase()];
if (!a || !b) continue;
const ai = DAY_ORDER.indexOf(a);
const bi = DAY_ORDER.indexOf(b);
if (ai === -1 || bi === -1) continue;
if (ai <= bi) {
for (let i = ai; i <= bi; i++) out.add(DAY_ORDER[i]);
} else {
for (let i = ai; i < DAY_ORDER.length; i++) out.add(DAY_ORDER[i]);
for (let i = 0; i <= bi; i++) out.add(DAY_ORDER[i]);
}
continue;
}
const single = DAY_CODE_TO_KEY[seg.toLowerCase()];
if (single) out.add(single);
}
return [...out];
}
function collapseTimeRanges(timePart) {
const matches = [...timePart.matchAll(/(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})/g)];
if (matches.length === 0) return null;
const first = matches[0];
const last = matches[matches.length - 1];
const open = `${first[1].padStart(2, '0')}:${first[2]}`;
const close = `${last[3].padStart(2, '0')}:${last[4]}`;
return [open, close];
}
+5
View File
@@ -0,0 +1,5 @@
{
"name": "farma-finder-api-sources",
"private": true,
"type": "module"
}
+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+54
View File
@@ -0,0 +1,54 @@
apply plugin: 'com.android.application'
android {
namespace "net.hacecalor.farmafinder"
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "net.hacecalor.farmafinder"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
+19
View File
@@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
+41
View File
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1,5 @@
package net.hacecalor.farmafinder;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">FarmaFinder</string>
<string name="title_activity_main">FarmaFinder</string>
<string name="package_name">net.hacecalor.farmafinder</string>
<string name="custom_url_scheme">net.hacecalor.farmafinder</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+29
View File
@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.2.1'
classpath 'com.google.gms:google-services:4.4.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
+3
View File
@@ -0,0 +1,3 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 22
compileSdkVersion = 34
targetSdkVersion = 34
androidxActivityVersion = '1.8.0'
androidxAppCompatVersion = '1.6.1'
androidxCoordinatorLayoutVersion = '1.2.0'
androidxCoreVersion = '1.12.0'
androidxFragmentVersion = '1.6.2'
coreSplashScreenVersion = '1.0.1'
androidxWebkitVersion = '1.9.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.1.5'
androidxEspressoCoreVersion = '3.5.1'
cordovaAndroidVersion = '10.1.1'
}
+6
View File
@@ -5,3 +5,9 @@ FARMACIAS_WEBHOOK_URL=
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
# Web Push (VAPID). Generate with:
# node -e "import('web-push').then(w => console.log(w.default.generateVAPIDKeys()))"
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
VAPID_SUBJECT=mailto:admin@example.com
@@ -0,0 +1,87 @@
import { parseOsmOpeningHours } from '../../API/opening-hours-osm.js';
describe('parseOsmOpeningHours', () => {
test('returns null for empty / non-string input', () => {
expect(parseOsmOpeningHours('')).toBeNull();
expect(parseOsmOpeningHours(null)).toBeNull();
expect(parseOsmOpeningHours(undefined)).toBeNull();
expect(parseOsmOpeningHours(123)).toBeNull();
});
test('24/7 → every day 00:0024:00', () => {
expect(parseOsmOpeningHours('24/7')).toEqual({
mon: ['00:00', '24:00'],
tue: ['00:00', '24:00'],
wed: ['00:00', '24:00'],
thu: ['00:00', '24:00'],
fri: ['00:00', '24:00'],
sat: ['00:00', '24:00'],
sun: ['00:00', '24:00'],
});
});
test('Mo-Fr 09:00-21:00 → weekdays set, weekend null', () => {
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00');
expect(result.mon).toEqual(['09:00', '21:00']);
expect(result.fri).toEqual(['09:00', '21:00']);
expect(result.sat).toBeNull();
expect(result.sun).toBeNull();
});
test('Multiple rules separated by semicolons', () => {
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00; Sa 09:00-14:00; Su closed');
expect(result.mon).toEqual(['09:00', '21:00']);
expect(result.fri).toEqual(['09:00', '21:00']);
expect(result.sat).toEqual(['09:00', '14:00']);
expect(result.sun).toBeNull();
});
test('Comma-separated day list', () => {
const result = parseOsmOpeningHours('Mo,We,Fr 10:00-14:00');
expect(result.mon).toEqual(['10:00', '14:00']);
expect(result.tue).toBeNull();
expect(result.wed).toEqual(['10:00', '14:00']);
expect(result.thu).toBeNull();
expect(result.fri).toEqual(['10:00', '14:00']);
});
test('Split shifts collapsed to first-open / last-close', () => {
const result = parseOsmOpeningHours('Mo-Fr 09:00-13:30,16:30-20:00');
expect(result.mon).toEqual(['09:00', '20:00']);
expect(result.fri).toEqual(['09:00', '20:00']);
});
test('Wrap-around day range Sa-Mo', () => {
const result = parseOsmOpeningHours('Sa-Mo 10:00-18:00');
expect(result.sat).toEqual(['10:00', '18:00']);
expect(result.sun).toEqual(['10:00', '18:00']);
expect(result.mon).toEqual(['10:00', '18:00']);
expect(result.tue).toBeNull();
});
test('Public-holiday rules are ignored', () => {
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00; PH off');
expect(result.mon).toEqual(['09:00', '21:00']);
});
test('Parenthetical comments are stripped', () => {
const result = parseOsmOpeningHours('Mo-Fr 09:00-14:00 (verano)');
expect(result.mon).toEqual(['09:00', '14:00']);
});
test('"off" applies null to those days', () => {
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00; Sa off');
expect(result.sat).toBeNull();
expect(result.mon).toEqual(['09:00', '21:00']);
});
test('Returns null when nothing parses', () => {
expect(parseOsmOpeningHours('see website')).toBeNull();
expect(parseOsmOpeningHours('?')).toBeNull();
});
test('Single-digit hours get zero-padded', () => {
const result = parseOsmOpeningHours('Mo 9:00-18:00');
expect(result.mon).toEqual(['09:00', '18:00']);
});
});
+1 -1
View File
@@ -27,7 +27,7 @@ beforeAll(async () => {
const hash = await bcrypt.hash('testpass', 10)
await new Promise((resolve, reject) => {
db.run(
'INSERT INTO users (username, password_hash) VALUES (?, ?)',
'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, 1)',
['testadmin', hash],
(err) => (err ? reject(err) : resolve())
)
+31 -3
View File
@@ -3,6 +3,8 @@
* Default URL: FARMACIAS_WEBHOOK_URL env or the project webhook.
*/
import { parseOsmOpeningHours } from '../API/opening-hours-osm.js';
export const DEFAULT_FARMACIAS_WEBHOOK =
process.env.FARMACIAS_WEBHOOK_URL ||
'https://n8n.hacecalor.net/webhook/farmacias';
@@ -120,9 +122,33 @@ export function normalizePharmacyRecord(raw) {
phone: phone || null,
latitude,
longitude,
opening_hours: extractOpeningHours(raw),
};
}
function extractOpeningHours(raw) {
if (!raw || typeof raw !== 'object') return null;
const direct = raw.opening_hours;
if (direct && typeof direct === 'object' && !Array.isArray(direct)) {
return direct;
}
const candidates = [
direct,
raw.openingHours,
raw.horario,
raw.hours,
raw.tags?.opening_hours,
raw.properties?.opening_hours,
];
for (const c of candidates) {
if (typeof c === 'string' && c.trim()) {
const parsed = parseOsmOpeningHours(c);
if (parsed) return parsed;
}
}
return null;
}
/** n8n often returns [{ json: { ... } }, ...] */
function unwrapN8nItemArray(arr) {
if (!Array.isArray(arr) || arr.length === 0) return arr || [];
@@ -209,7 +235,7 @@ export async function importPharmaciesFromRows(dbGet, dbRun, rows) {
continue;
}
const { name, address, phone, latitude, longitude } = normalized;
const { name, address, phone, latitude, longitude, opening_hours } = normalized;
try {
const existing = await dbGet(
@@ -221,9 +247,11 @@ export async function importPharmaciesFromRows(dbGet, dbRun, rows) {
continue;
}
const openingHoursValue = opening_hours ? JSON.stringify(opening_hours) : null;
await dbRun(
'INSERT INTO pharmacies (name, address, phone, latitude, longitude) VALUES (?, ?, ?, ?, ?)',
[name, address, phone || null, latitude, longitude]
'INSERT INTO pharmacies (name, address, phone, latitude, longitude, opening_hours) VALUES (?, ?, ?, ?, ?, ?)',
[name, address, phone || null, latitude, longitude, openingHoursValue]
);
inserted++;
} catch (err) {
+135 -1
View File
@@ -17,7 +17,8 @@
"express-rate-limit": "^8.5.2",
"express-session": "^1.17.3",
"redis": "^4.6.0",
"sqlite3": "^5.1.6"
"sqlite3": "^5.1.6",
"web-push": "^3.6.7"
},
"devDependencies": {
"jest": "^29.7.0",
@@ -1489,6 +1490,18 @@
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"dev": true
},
"node_modules/asn1.js": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz",
"integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==",
"license": "MIT",
"dependencies": {
"bn.js": "^4.0.0",
"inherits": "^2.0.1",
"minimalistic-assert": "^1.0.0",
"safer-buffer": "^2.1.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -1711,6 +1724,12 @@
"readable-stream": "^3.4.0"
}
},
"node_modules/bn.js": {
"version": "4.12.3",
"resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.3.tgz",
"integrity": "sha512-fGTi3gxV/23FTYdAoUtLYp6qySe2KE3teyZitipKNRuVYcBkoP/bB3guXN/XVKUe9mxCHXnc9C4ocyz8OmgN0g==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.4",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz",
@@ -1826,6 +1845,12 @@
"ieee754": "^1.1.13"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"license": "BSD-3-Clause"
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -2370,6 +2395,15 @@
"node": ">= 0.4"
}
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@@ -3116,6 +3150,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/http_ece": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz",
"integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==",
"license": "MIT",
"engines": {
"node": ">=16"
}
},
"node_modules/http-cache-semantics": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
@@ -4199,6 +4242,27 @@
"node": ">=6"
}
},
"node_modules/jwa": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"license": "MIT",
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jws": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
"license": "MIT",
"dependencies": {
"jwa": "^2.0.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/kleur": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz",
@@ -4426,6 +4490,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/minimalistic-assert": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
"integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==",
"license": "ISC"
},
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -6176,6 +6246,70 @@
"makeerror": "1.0.12"
}
},
"node_modules/web-push": {
"version": "3.6.7",
"resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz",
"integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==",
"license": "MPL-2.0",
"dependencies": {
"asn1.js": "^5.3.0",
"http_ece": "1.2.0",
"https-proxy-agent": "^7.0.0",
"jws": "^4.0.0",
"minimist": "^1.2.5"
},
"bin": {
"web-push": "src/cli.js"
},
"engines": {
"node": ">= 16"
}
},
"node_modules/web-push/node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/web-push/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/web-push/node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/web-push/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+4 -3
View File
@@ -5,8 +5,8 @@
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"start": "node --env-file-if-exists=.env server.js",
"dev": "node --env-file-if-exists=.env --watch server.js",
"seed": "node seed.js",
"create-admin": "node create-admin.js",
"migrate": "node migrate.js",
@@ -26,7 +26,8 @@
"express-rate-limit": "^8.5.2",
"express-session": "^1.17.3",
"redis": "^4.6.0",
"sqlite3": "^5.1.6"
"sqlite3": "^5.1.6",
"web-push": "^3.6.7"
},
"devDependencies": {
"jest": "^29.7.0",
+517 -25
View File
@@ -8,6 +8,7 @@ import session from 'express-session';
import connectSqlite3 from 'connect-sqlite3';
import bcrypt from 'bcrypt';
import rateLimit from 'express-rate-limit';
import webpush from 'web-push';
import { searchMedicines, getMedicineDetails } from './cima-service.js';
import { runFarmaciaWebhookImport, DEFAULT_FARMACIAS_WEBHOOK, importPharmaciesFromRows } from './farmacias-webhook-import.js';
import { fetchPharmaciesExternal } from '../API/index.js';
@@ -18,6 +19,18 @@ const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3001;
// Trust the reverse proxy in front of us (Docker/Traefik/nginx/Cloudflare) so
// req.ip and X-Forwarded-For are honored. Configurable via TRUST_PROXY:
// - unset/"1" → trust exactly one hop (typical single reverse proxy)
// - "loopback" → only trust 127.0.0.1
// - "true" → trust any proxy (only behind a trusted network)
// - any other value is passed through verbatim (number of hops or IP list)
const trustProxyEnv = process.env.TRUST_PROXY ?? '1';
if (trustProxyEnv === 'true') app.set('trust proxy', true);
else if (trustProxyEnv === 'false') app.set('trust proxy', false);
else if (/^\d+$/.test(trustProxyEnv)) app.set('trust proxy', Number(trustProxyEnv));
else app.set('trust proxy', trustProxyEnv);
// Configure CORS with credentials
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
@@ -47,6 +60,18 @@ app.use(session(sessionConfig));
const searchLimiter = rateLimit({ windowMs: 60_000, max: 30, standardHeaders: true, legacyHeaders: false });
const loginLimiter = rateLimit({ windowMs: 60_000, max: 5, standardHeaders: true, legacyHeaders: false });
const registerLimiter = rateLimit({ windowMs: 60 * 60_000, max: 10, standardHeaders: true, legacyHeaders: false });
const geocodeLimiter = rateLimit({ windowMs: 60_000, max: 10, standardHeaders: true, legacyHeaders: false });
const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY || '';
const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY || '';
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || 'mailto:admin@example.com';
const PUSH_ENABLED = Boolean(VAPID_PUBLIC_KEY && VAPID_PRIVATE_KEY);
if (PUSH_ENABLED) {
webpush.setVapidDetails(VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY);
} else if (process.env.NODE_ENV !== 'test') {
console.warn('[push] VAPID keys not configured — push notifications disabled');
}
// Database setup
const dbPath = process.env.DATABASE_PATH || path.join(__dirname, 'database.sqlite');
@@ -65,6 +90,28 @@ function dbRun(sql, params = []) {
const dbAll = promisify(db.all.bind(db));
const dbGet = promisify(db.get.bind(db));
// Accept opening_hours as either an object or a JSON string from the client
// and return a TEXT value (or null) safe to persist.
function serializeOpeningHours(value) {
if (value == null || value === '') return null;
if (typeof value === 'string') {
try {
JSON.parse(value);
return value;
} catch {
return null;
}
}
if (typeof value === 'object') {
try {
return JSON.stringify(value);
} catch {
return null;
}
}
return null;
}
// Initialize database tables
async function initDatabase() {
try {
@@ -76,10 +123,18 @@ async function initDatabase() {
address TEXT NOT NULL,
phone TEXT,
latitude REAL,
longitude REAL
longitude REAL,
opening_hours TEXT
)
`);
// Add opening_hours to pre-existing pharmacies tables (no-op if already present)
try {
await dbRun(`ALTER TABLE pharmacies ADD COLUMN opening_hours TEXT`);
} catch (e) {
if (!/duplicate column/i.test(e.message)) throw e;
}
// Create junction table for pharmacy-medicine relationships
// Ahora usa nregistro (número de registro de CIMA) en lugar de medicine_id local
await dbRun(`
@@ -107,6 +162,47 @@ async function initDatabase() {
)
`);
await dbRun(`
CREATE TABLE IF NOT EXISTS push_subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
medicine_nregistro TEXT NOT NULL,
medicine_name TEXT,
endpoint TEXT NOT NULL,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(medicine_nregistro, endpoint)
)
`);
await dbRun(`CREATE INDEX IF NOT EXISTS idx_push_subscriptions_med ON push_subscriptions(medicine_nregistro)`);
await dbRun(`
CREATE TABLE IF NOT EXISTS push_subscriptions_pharmacy (
id INTEGER PRIMARY KEY AUTOINCREMENT,
medicine_nregistro TEXT NOT NULL,
medicine_name TEXT,
pharmacy_id INTEGER NOT NULL,
endpoint TEXT NOT NULL,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(medicine_nregistro, pharmacy_id, endpoint)
)
`);
await dbRun(`CREATE INDEX IF NOT EXISTS idx_push_subs_pharm ON push_subscriptions_pharmacy(medicine_nregistro, pharmacy_id)`);
// Add is_admin to users table if not yet present (migration for existing DBs)
try { await dbRun('ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0'); } catch {}
// Profile fields on users (migration for existing DBs)
try { await dbRun('ALTER TABLE users ADD COLUMN address TEXT'); } catch {}
try { await dbRun('ALTER TABLE users ADD COLUMN latitude REAL'); } catch {}
try { await dbRun('ALTER TABLE users ADD COLUMN longitude REAL'); } catch {}
// Add user_id to push tables if not yet present (migration for existing DBs)
try { await dbRun('ALTER TABLE push_subscriptions ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL'); } catch {}
try { await dbRun('ALTER TABLE push_subscriptions_pharmacy ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL'); } catch {}
console.log('Database initialized successfully');
} catch (error) {
console.error('Error initializing database:', error);
@@ -147,6 +243,7 @@ app.get('/api/medicines/:medicineId/pharmacies', async (req, res) => {
p.phone,
p.latitude,
p.longitude,
p.opening_hours,
pm.price,
pm.stock
FROM pharmacies p
@@ -203,6 +300,17 @@ const requireAuth = (req, res, next) => {
return res.status(401).json({ error: 'Authentication required' });
};
// Middleware to check if user is an admin
const requireAdmin = (req, res, next) => {
if (req.session && req.session.userId && req.session.isAdmin) {
return next();
}
if (req.session && req.session.userId) {
return res.status(403).json({ error: 'Admin access required' });
}
return res.status(401).json({ error: 'Authentication required' });
};
// ========== AUTHENTICATION ROUTES ==========
// Login endpoint
@@ -234,12 +342,17 @@ app.post('/api/auth/login', loginLimiter, async (req, res) => {
// Create session
req.session.userId = user.id;
req.session.username = user.username;
req.session.isAdmin = Boolean(user.is_admin);
res.json({
message: 'Login successful',
user: {
id: user.id,
username: user.username
username: user.username,
is_admin: Boolean(user.is_admin),
address: user.address || null,
latitude: user.latitude,
longitude: user.longitude,
}
});
} catch (error) {
@@ -248,6 +361,52 @@ app.post('/api/auth/login', loginLimiter, async (req, res) => {
}
});
// Register a new user (non-admin) and start a session
app.post('/api/auth/register', registerLimiter, async (req, res) => {
try {
const { username, password } = req.body || {};
const u = String(username || '').trim();
const p = String(password || '');
if (!/^[A-Za-z0-9_]{3,32}$/.test(u)) {
return res.status(400).json({ error: 'Username must be 332 characters: letters, digits, or underscore' });
}
if (p.length < 8) {
return res.status(400).json({ error: 'Password must be at least 8 characters' });
}
const existing = await dbGet('SELECT id FROM users WHERE username = ?', [u]);
if (existing) {
return res.status(409).json({ error: 'Username already taken' });
}
const passwordHash = await bcrypt.hash(p, 10);
const result = await dbRun(
'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, 0)',
[u, passwordHash]
);
req.session.userId = result.lastID;
req.session.username = u;
req.session.isAdmin = false;
res.status(201).json({
message: 'Registered',
user: {
id: result.lastID,
username: u,
is_admin: false,
address: null,
latitude: null,
longitude: null,
}
});
} catch (error) {
console.error('Error during registration:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Logout endpoint
app.post('/api/auth/logout', (req, res) => {
req.session.destroy((err) => {
@@ -259,18 +418,127 @@ app.post('/api/auth/logout', (req, res) => {
});
});
// Check authentication status
app.get('/api/auth/check', (req, res) => {
// Check authentication status — reads fresh user record so profile fields stay current
app.get('/api/auth/check', async (req, res) => {
try {
if (req.session && req.session.userId) {
res.json({
const user = await dbGet(
'SELECT id, username, is_admin, address, latitude, longitude FROM users WHERE id = ?',
[req.session.userId]
);
if (!user) {
req.session.destroy(() => {});
return res.json({ authenticated: false });
}
return res.json({
authenticated: true,
user: {
id: req.session.userId,
username: req.session.username
id: user.id,
username: user.username,
is_admin: Boolean(user.is_admin),
address: user.address || null,
latitude: user.latitude,
longitude: user.longitude,
}
});
} else {
}
res.json({ authenticated: false });
} catch (error) {
console.error('Error checking auth:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Current user's profile
app.get('/api/users/me', requireAuth, async (req, res) => {
try {
const user = await dbGet(
'SELECT id, username, is_admin, address, latitude, longitude FROM users WHERE id = ?',
[req.session.userId]
);
if (!user) return res.status(404).json({ error: 'Not found' });
res.json({
id: user.id,
username: user.username,
is_admin: Boolean(user.is_admin),
address: user.address || null,
latitude: user.latitude,
longitude: user.longitude,
});
} catch (error) {
console.error('Error loading profile:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Update the current user's address + coordinates
app.put('/api/users/me', requireAuth, async (req, res) => {
try {
const { address, latitude, longitude } = req.body || {};
const addr =
address == null || String(address).trim() === ''
? null
: String(address).trim().slice(0, 500);
let lat = null;
let lon = null;
if (latitude !== '' && latitude != null) {
lat = typeof latitude === 'number' ? latitude : parseFloat(latitude);
if (!Number.isFinite(lat) || lat < -90 || lat > 90) {
return res.status(400).json({ error: 'Invalid latitude' });
}
}
if (longitude !== '' && longitude != null) {
lon = typeof longitude === 'number' ? longitude : parseFloat(longitude);
if (!Number.isFinite(lon) || lon < -180 || lon > 180) {
return res.status(400).json({ error: 'Invalid longitude' });
}
}
await dbRun(
'UPDATE users SET address = ?, latitude = ?, longitude = ? WHERE id = ?',
[addr, lat, lon, req.session.userId]
);
const user = await dbGet(
'SELECT id, username, is_admin, address, latitude, longitude FROM users WHERE id = ?',
[req.session.userId]
);
res.json({
id: user.id,
username: user.username,
is_admin: Boolean(user.is_admin),
address: user.address || null,
latitude: user.latitude,
longitude: user.longitude,
});
} catch (error) {
console.error('Error updating profile:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Geocode for any authenticated user (rate-limited). Same impl as /api/admin/geocode.
app.get('/api/geocode', requireAuth, geocodeLimiter, async (req, res) => {
const q = (req.query.q || '').trim();
if (!q) return res.status(400).json({ error: 'Query parameter q is required' });
try {
const result = await nominatimSearchFirstHit(q);
if (!result.ok) return res.status(result.status).json({ error: result.error });
const lat = parseFloat(result.hit.lat);
const lon = parseFloat(result.hit.lon);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
return res.status(502).json({ error: 'Geocoder result missing coordinates' });
}
res.json({
lat,
lon,
displayName: result.hit.display_name || q,
matchedQuery: result.triedQuery,
});
} catch (err) {
console.error('Geocode error:', err);
res.status(500).json({ error: err.message || 'Geocode failed' });
}
});
@@ -355,7 +623,7 @@ async function nominatimSearchFirstHit(originalQuery) {
}
// Geocode city → lat, lon, radius (OpenStreetMap Nominatim; admin-only, low volume)
app.get('/api/admin/geocode', requireAuth, async (req, res) => {
app.get('/api/admin/geocode', requireAdmin, async (req, res) => {
const q = (req.query.q || '').trim();
if (!q) {
return res.status(400).json({ error: 'Query parameter q is required' });
@@ -395,9 +663,9 @@ app.get('/api/admin/geocode', requireAuth, async (req, res) => {
});
// Add a new pharmacy
app.post('/api/admin/pharmacies', requireAuth, async (req, res) => {
app.post('/api/admin/pharmacies', requireAdmin, async (req, res) => {
try {
const { name, address, phone, latitude, longitude } = req.body;
const { name, address, phone, latitude, longitude, opening_hours } = req.body;
if (!name || !address) {
return res.status(400).json({ error: 'Name and address are required' });
@@ -413,9 +681,11 @@ app.post('/api/admin/pharmacies', requireAuth, async (req, res) => {
return res.status(400).json({ error: 'A pharmacy with this name and address already exists' });
}
const openingHoursValue = serializeOpeningHours(opening_hours);
const result = await dbRun(
'INSERT INTO pharmacies (name, address, phone, latitude, longitude) VALUES (?, ?, ?, ?, ?)',
[name.trim(), address.trim(), phone ? phone.trim() : null, latitude || null, longitude || null]
'INSERT INTO pharmacies (name, address, phone, latitude, longitude, opening_hours) VALUES (?, ?, ?, ?, ?, ?)',
[name.trim(), address.trim(), phone ? phone.trim() : null, latitude || null, longitude || null, openingHoursValue]
);
if (!result || result.lastID === undefined) {
@@ -443,18 +713,20 @@ app.post('/api/admin/pharmacies', requireAuth, async (req, res) => {
});
// Update a pharmacy
app.put('/api/admin/pharmacies/:id', requireAuth, async (req, res) => {
app.put('/api/admin/pharmacies/:id', requireAdmin, async (req, res) => {
try {
const pharmacyId = parseInt(req.params.id);
const { name, address, phone, latitude, longitude } = req.body;
const { name, address, phone, latitude, longitude, opening_hours } = req.body;
if (!name || !address) {
return res.status(400).json({ error: 'Name and address are required' });
}
const openingHoursValue = serializeOpeningHours(opening_hours);
await dbRun(
'UPDATE pharmacies SET name = ?, address = ?, phone = ?, latitude = ?, longitude = ? WHERE id = ?',
[name, address, phone || null, latitude || null, longitude || null, pharmacyId]
'UPDATE pharmacies SET name = ?, address = ?, phone = ?, latitude = ?, longitude = ?, opening_hours = ? WHERE id = ?',
[name, address, phone || null, latitude || null, longitude || null, openingHoursValue, pharmacyId]
);
const updatedPharmacy = await dbGet(
@@ -474,7 +746,7 @@ app.put('/api/admin/pharmacies/:id', requireAuth, async (req, res) => {
});
// Delete a pharmacy
app.delete('/api/admin/pharmacies/:id', requireAuth, async (req, res) => {
app.delete('/api/admin/pharmacies/:id', requireAdmin, async (req, res) => {
try {
const pharmacyId = parseInt(req.params.id);
@@ -493,7 +765,7 @@ app.delete('/api/admin/pharmacies/:id', requireAuth, async (req, res) => {
// Import pharmacies from webhook (e.g. n8n).
// Body: { "url"?: string, "lat"?, "lon"|"lng"?, "radio"? } — lat/lon/radio add ?lat=&lon=&radio= (metres)
app.post('/api/admin/pharmacies/import-webhook', requireAuth, async (req, res) => {
app.post('/api/admin/pharmacies/import-webhook', requireAdmin, async (req, res) => {
try {
const body = req.body && typeof req.body === 'object' ? req.body : {};
const url =
@@ -525,7 +797,7 @@ app.post('/api/admin/pharmacies/import-webhook', requireAuth, async (req, res) =
});
// Import from OpenStreetMap (Overpass), or a JSON open-data URL — see /API
app.post('/api/admin/pharmacies/import-external', requireAuth, async (req, res) => {
app.post('/api/admin/pharmacies/import-external', requireAdmin, async (req, res) => {
try {
const body = req.body && typeof req.body === 'object' ? req.body : {};
const source = body.source;
@@ -566,7 +838,7 @@ app.post('/api/admin/pharmacies/import-external', requireAuth, async (req, res)
});
// Search medicines from CIMA API (para el admin)
app.get('/api/admin/medicines', requireAuth, async (req, res) => {
app.get('/api/admin/medicines', requireAdmin, async (req, res) => {
try {
const query = req.query.q || '';
@@ -585,7 +857,7 @@ app.get('/api/admin/medicines', requireAuth, async (req, res) => {
});
// Get medicines for a specific pharmacy (usando nregistro)
app.get('/api/admin/pharmacies/:pharmacyId/medicines', requireAuth, async (req, res) => {
app.get('/api/admin/pharmacies/:pharmacyId/medicines', requireAdmin, async (req, res) => {
try {
const pharmacyId = parseInt(req.params.pharmacyId);
@@ -610,7 +882,7 @@ app.get('/api/admin/pharmacies/:pharmacyId/medicines', requireAuth, async (req,
});
// Add medicine to a pharmacy (or update if exists) usando nregistro de CIMA
app.post('/api/admin/pharmacy-medicines', requireAuth, async (req, res) => {
app.post('/api/admin/pharmacy-medicines', requireAdmin, async (req, res) => {
try {
const { pharmacy_id, medicine_nregistro, medicine_name, price, stock } = req.body;
@@ -644,6 +916,15 @@ app.post('/api/admin/pharmacy-medicines', requireAuth, async (req, res) => {
[pharmacy_id, medicine_nregistro]
);
if (!existing) {
const pharmacy = await dbGet('SELECT id, name FROM pharmacies WHERE id = ?', [pharmacy_id]);
sendPushForMedicine({
medicine_nregistro,
medicine_name: medicine_name || relationship?.medicine_name || null,
pharmacy,
}).catch(err => console.error('[push] fanout error:', err));
}
res.status(201).json(relationship);
} catch (error) {
console.error('Error adding medicine to pharmacy:', error);
@@ -652,7 +933,7 @@ app.post('/api/admin/pharmacy-medicines', requireAuth, async (req, res) => {
});
// Update pharmacy-medicine relationship
app.put('/api/admin/pharmacy-medicines/:id', requireAuth, async (req, res) => {
app.put('/api/admin/pharmacy-medicines/:id', requireAdmin, async (req, res) => {
try {
const id = parseInt(req.params.id);
const { price, stock } = req.body;
@@ -679,7 +960,7 @@ app.put('/api/admin/pharmacy-medicines/:id', requireAuth, async (req, res) => {
});
// Delete pharmacy-medicine relationship
app.delete('/api/admin/pharmacy-medicines/:id', requireAuth, async (req, res) => {
app.delete('/api/admin/pharmacy-medicines/:id', requireAdmin, async (req, res) => {
try {
const id = parseInt(req.params.id);
await dbRun('DELETE FROM pharmacy_medicines WHERE id = ?', [id]);
@@ -690,6 +971,217 @@ app.delete('/api/admin/pharmacy-medicines/:id', requireAuth, async (req, res) =>
}
});
// Push notifications
app.get('/api/notifications/vapid-public-key', (req, res) => {
if (!PUSH_ENABLED) {
return res.status(503).json({ error: 'Push notifications are not configured on this server' });
}
res.json({ publicKey: VAPID_PUBLIC_KEY });
});
app.post('/api/notifications/subscribe', requireAuth, async (req, res) => {
try {
if (!PUSH_ENABLED) {
return res.status(503).json({ error: 'Push notifications are not configured on this server' });
}
const { medicine_nregistro, medicine_name, subscription, pharmacy_id } = req.body || {};
const endpoint = subscription?.endpoint;
const p256dh = subscription?.keys?.p256dh;
const auth = subscription?.keys?.auth;
const userId = req.session.userId;
if (!medicine_nregistro || !endpoint || !p256dh || !auth) {
return res.status(400).json({ error: 'medicine_nregistro and a full PushSubscription are required' });
}
if (pharmacy_id) {
const existing = await dbGet(
'SELECT id FROM push_subscriptions_pharmacy WHERE medicine_nregistro = ? AND pharmacy_id = ? AND endpoint = ?',
[medicine_nregistro, pharmacy_id, endpoint]
);
if (existing) {
await dbRun(
'UPDATE push_subscriptions_pharmacy SET medicine_name = ?, p256dh = ?, auth = ?, user_id = ? WHERE id = ?',
[medicine_name || null, p256dh, auth, userId, existing.id]
);
} else {
await dbRun(
'INSERT INTO push_subscriptions_pharmacy (medicine_nregistro, medicine_name, pharmacy_id, endpoint, p256dh, auth, user_id) VALUES (?, ?, ?, ?, ?, ?, ?)',
[medicine_nregistro, medicine_name || null, pharmacy_id, endpoint, p256dh, auth, userId]
);
}
} else {
const existing = await dbGet(
'SELECT id FROM push_subscriptions WHERE medicine_nregistro = ? AND endpoint = ?',
[medicine_nregistro, endpoint]
);
if (existing) {
await dbRun(
'UPDATE push_subscriptions SET medicine_name = ?, p256dh = ?, auth = ?, user_id = ? WHERE id = ?',
[medicine_name || null, p256dh, auth, userId, existing.id]
);
} else {
await dbRun(
'INSERT INTO push_subscriptions (medicine_nregistro, medicine_name, endpoint, p256dh, auth, user_id) VALUES (?, ?, ?, ?, ?, ?)',
[medicine_nregistro, medicine_name || null, endpoint, p256dh, auth, userId]
);
}
}
res.status(201).json({ ok: true });
} catch (error) {
console.error('Error subscribing to push:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.delete('/api/notifications/unsubscribe', requireAuth, async (req, res) => {
try {
const { medicine_nregistro, endpoint, pharmacy_id } = req.body || {};
if (!endpoint) {
return res.status(400).json({ error: 'endpoint is required' });
}
if (pharmacy_id) {
await dbRun(
'DELETE FROM push_subscriptions_pharmacy WHERE medicine_nregistro = ? AND pharmacy_id = ? AND endpoint = ?',
[medicine_nregistro, pharmacy_id, endpoint]
);
} else if (medicine_nregistro) {
await dbRun(
'DELETE FROM push_subscriptions WHERE medicine_nregistro = ? AND endpoint = ?',
[medicine_nregistro, endpoint]
);
} else {
await dbRun('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
}
res.status(204).end();
} catch (error) {
console.error('Error unsubscribing from push:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// List the current user's saved notifications across all their devices
app.get('/api/notifications/mine', requireAuth, async (req, res) => {
try {
const userId = req.session.userId;
const globalRows = await dbAll(
`SELECT id, medicine_nregistro, medicine_name, created_at
FROM push_subscriptions
WHERE user_id = ?
ORDER BY created_at DESC`,
[userId]
);
const pharmacyRows = await dbAll(
`SELECT ps.id, ps.medicine_nregistro, ps.medicine_name, ps.pharmacy_id,
ps.created_at, p.name AS pharmacy_name, p.address AS pharmacy_address
FROM push_subscriptions_pharmacy ps
LEFT JOIN pharmacies p ON p.id = ps.pharmacy_id
WHERE ps.user_id = ?
ORDER BY ps.created_at DESC`,
[userId]
);
res.json({
global: globalRows.map(r => ({ ...r, scope: 'global' })),
pharmacy: pharmacyRows.map(r => ({ ...r, scope: 'pharmacy' })),
});
} catch (error) {
console.error('Error listing user notifications:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Delete one of the user's saved notifications by row id + scope
app.delete('/api/notifications/mine', requireAuth, async (req, res) => {
try {
const userId = req.session.userId;
const { scope, id } = req.body || {};
const rowId = Number(id);
if (!Number.isInteger(rowId) || rowId <= 0) {
return res.status(400).json({ error: 'id must be a positive integer' });
}
if (scope === 'pharmacy') {
await dbRun(
'DELETE FROM push_subscriptions_pharmacy WHERE id = ? AND user_id = ?',
[rowId, userId]
);
} else if (scope === 'global') {
await dbRun(
'DELETE FROM push_subscriptions WHERE id = ? AND user_id = ?',
[rowId, userId]
);
} else {
return res.status(400).json({ error: "scope must be 'global' or 'pharmacy'" });
}
res.status(204).end();
} catch (error) {
console.error('Error deleting user notification:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
async function sendPushForMedicine({ medicine_nregistro, medicine_name, pharmacy }) {
if (!PUSH_ENABLED) return { sent: 0, failed: 0, pruned: 0 };
const globalSubs = await dbAll(
'SELECT id, endpoint, p256dh, auth FROM push_subscriptions WHERE medicine_nregistro = ?',
[medicine_nregistro]
);
const pharmacySubs = pharmacy?.id ? await dbAll(
'SELECT id, endpoint, p256dh, auth FROM push_subscriptions_pharmacy WHERE medicine_nregistro = ? AND pharmacy_id = ?',
[medicine_nregistro, pharmacy.id]
) : [];
// Deduplicate by endpoint; pharmacy-specific overrides global so one notification per browser
const endpointMap = new Map();
for (const sub of (globalSubs || [])) endpointMap.set(sub.endpoint, { ...sub, _pharmSub: false });
for (const sub of (pharmacySubs || [])) endpointMap.set(sub.endpoint, { ...sub, _pharmSub: true });
const subs = [...endpointMap.values()];
if (subs.length === 0) return { sent: 0, failed: 0, pruned: 0 };
const payload = JSON.stringify({
title: 'Medicine available',
body: `${medicine_name || medicine_nregistro} is now available at ${pharmacy?.name || 'a pharmacy near you'}`,
url: `/?nregistro=${encodeURIComponent(medicine_nregistro)}`,
medicine_nregistro,
medicine_name: medicine_name || null,
pharmacy_id: pharmacy?.id ?? null,
pharmacy_name: pharmacy?.name ?? null,
});
let sent = 0;
let failed = 0;
let pruned = 0;
await Promise.all(subs.map(async (sub) => {
try {
await webpush.sendNotification(
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
payload
);
sent++;
} catch (err) {
failed++;
const status = err?.statusCode;
if (status === 404 || status === 410) {
try {
const deleteQuery = sub._pharmSub
? 'DELETE FROM push_subscriptions_pharmacy WHERE id = ?'
: 'DELETE FROM push_subscriptions WHERE id = ?';
await dbRun(deleteQuery, [sub.id]);
pruned++;
} catch {}
} else {
console.error('[push] send failed:', status, err?.body || err?.message);
}
}
}));
return { sent, failed, pruned };
}
export { app, initDatabase, db };
if (process.env.NODE_ENV !== 'test') {
+22
View File
@@ -0,0 +1,22 @@
{
"appId": "net.hacecalor.farmafinder",
"appName": "FarmaFinder",
"webDir": "frontend/dist",
"server": {
"androidScheme": "https"
},
"ios": {
"contentInset": "always"
},
"android": {
"allowMixedContent": false
},
"plugins": {
"SplashScreen": {
"launchShowDuration": 1200,
"backgroundColor": "#0f766e",
"showSpinner": false,
"androidSplashResourceName": "splash"
}
}
}
+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;
}
}
+90 -7
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">
<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>
{isAdmin && (
<button
className={view === 'admin' ? 'active' : ''}
onClick={() => setView('admin')}
>
Admin Panel
<span className="nav-icon"></span>
<span className="nav-label">Admin</span>
</button>
</div>
)}
{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;
+76 -5
View File
@@ -19,25 +19,100 @@
box-shadow: 0 1px 3px rgba(28, 25, 23, 0.04);
}
@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;
}
.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 {
margin-bottom: 1.35rem;
}
@@ -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;
+117 -1
View File
@@ -28,23 +28,113 @@
box-shadow: 0 1px 3px rgba(28, 25, 23, 0.04);
}
@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-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 {
display: flex;
@@ -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;
+116 -8
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,16 +32,120 @@ 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">
{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>
@@ -46,11 +158,7 @@ function PharmacyList({ pharmacies, loading }) {
</div>
</div>
</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
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); }}
>
<option value="">Select a pharmacy</option>
{pharmacies.map((pharmacy) => (
<option key={pharmacy.id} value={pharmacy.id}>
{pharmacy.name} - {pharmacy.address}
</option>
))}
</select>
<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;
+95 -5
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">
@@ -80,6 +141,8 @@ function PublicView() {
medicines={medicines}
onSelect={setSelectedMedicine}
query={searchQuery}
currentUser={currentUser}
onLoginRequest={onLoginRequest}
/>
)}
@@ -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': {
+13
View File
@@ -0,0 +1,13 @@
App/build
App/Pods
App/output
App/App/public
DerivedData
xcuserdata
# Cordova plugins for Capacitor
capacitor-cordova-ios-plugins
# Generated Config files
App/App/capacitor.config.json
App/App/config.xml
+408
View File
@@ -0,0 +1,408 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 48;
objects = {
/* Begin PBXBuildFile section */
2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; };
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; };
504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; };
504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; };
504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = "<group>"; };
50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = "<group>"; };
504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; };
504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
504EC3011FED79650016851F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */ = {
isa = PBXGroup;
children = (
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
504EC2FB1FED79650016851F = {
isa = PBXGroup;
children = (
504EC3061FED79650016851F /* App */,
504EC3051FED79650016851F /* Products */,
7F8756D8B27F46E3366F6CEA /* Pods */,
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */,
);
sourceTree = "<group>";
};
504EC3051FED79650016851F /* Products */ = {
isa = PBXGroup;
children = (
504EC3041FED79650016851F /* App.app */,
);
name = Products;
sourceTree = "<group>";
};
504EC3061FED79650016851F /* App */ = {
isa = PBXGroup;
children = (
50379B222058CBB4000EE86E /* capacitor.config.json */,
504EC3071FED79650016851F /* AppDelegate.swift */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
504EC3101FED79650016851F /* LaunchScreen.storyboard */,
504EC3131FED79650016851F /* Info.plist */,
2FAD9762203C412B000D30F8 /* config.xml */,
50B271D01FEDC1A000F3C39B /* public */,
);
path = App;
sourceTree = "<group>";
};
7F8756D8B27F46E3366F6CEA /* Pods */ = {
isa = PBXGroup;
children = (
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */,
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */,
);
name = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
504EC3031FED79650016851F /* App */ = {
isa = PBXNativeTarget;
buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */;
buildPhases = (
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */,
504EC3001FED79650016851F /* Sources */,
504EC3011FED79650016851F /* Frameworks */,
504EC3021FED79650016851F /* Resources */,
9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = App;
productName = App;
productReference = 504EC3041FED79650016851F /* App.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
504EC2FC1FED79650016851F /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0920;
LastUpgradeCheck = 0920;
TargetAttributes = {
504EC3031FED79650016851F = {
CreatedOnToolsVersion = 9.2;
LastSwiftMigration = 1100;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */;
compatibilityVersion = "Xcode 8.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 504EC2FB1FED79650016851F;
packageReferences = (
);
productRefGroup = 504EC3051FED79650016851F /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
504EC3031FED79650016851F /* App */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
504EC3021FED79650016851F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */,
50B271D11FEDC1A000F3C39B /* public in Resources */,
504EC30F1FED79650016851F /* Assets.xcassets in Resources */,
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,
504EC30D1FED79650016851F /* Main.storyboard in Resources */,
2FAD9763203C412B000D30F8 /* config.xml in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-App-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-App/Pods-App-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
504EC3001FED79650016851F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
504EC30B1FED79650016851F /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
504EC30C1FED79650016851F /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
504EC3101FED79650016851F /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
504EC3111FED79650016851F /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
504EC3141FED79650016851F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
504EC3151FED79650016851F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
504EC3171FED79650016851F /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 1.0;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = net.hacecalor.farmafinder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
504EC3181FED79650016851F /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.hacecalor.farmafinder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = {
isa = XCConfigurationList;
buildConfigurations = (
504EC3141FED79650016851F /* Debug */,
504EC3151FED79650016851F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */ = {
isa = XCConfigurationList;
buildConfigurations = (
504EC3171FED79650016851F /* Debug */,
504EC3181FED79650016851F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 504EC2FC1FED79650016851F /* Project object */;
}
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
+49
View File
@@ -0,0 +1,49 @@
import UIKit
import Capacitor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Called when the app was launched with a url. Feel free to add additional processing here,
// but if you want the App API to support tracking app url opens, make sure to keep this call
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// Called when the app was launched with an activity, including Universal Links.
// Feel free to add additional processing here, but if you want the App API to support
// tracking app url opens, make sure to keep this call
return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

@@ -0,0 +1,14 @@
{
"images" : [
{
"filename" : "AppIcon-512@2x.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}

Some files were not shown because too many files have changed in this diff Show More