diff --git a/.env.server.example b/.env.server.example new file mode 100644 index 0000000..ebfb8d4 --- /dev/null +++ b/.env.server.example @@ -0,0 +1,5 @@ +# Copia questo file in .env.server (git-ignorato) e compila i valori. +# deploy.sh lo usa in locale per l'istantanea degli orari e lo copia sul +# server come .env (permessi 600) per il servizio "orari". +GOOGLE_PLACES_API_KEY= +GOOGLE_PLACE_ID= diff --git a/.gitignore b/.gitignore index c06adcb..a9fe088 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .env .env.* !.env.example +!.env.server.example # OS .DS_Store diff --git a/CLAUDE.md b/CLAUDE.md index a281143..2eb64ec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,8 @@ Stack: Astro (static) — see `docs/adr/0003-stack-astro-statico.md`. Node.js re - Dev: `npm run dev` (http://localhost:4321) - Build: `npm run build` (output in `dist/`) - Preview build: `npm run preview` -- Deploy: `./deploy.sh` (Docker on the a75 server, see `docs/runbooks/deploy.md`) +- Deploy: `./deploy.sh` (Docker on the a75 server, needs `.env.server`, see `docs/runbooks/deploy.md`) +- Opening hours come from Google Business Profile (ADR 0005): do not hard-code them - Test / Lint / Typecheck: not set up yet (`npm run check` needs `@astrojs/check`) - Design proposals: `python3 -m http.server 4173 --directory design` diff --git a/deploy.sh b/deploy.sh index a3da292..1901759 100755 --- a/deploy.sh +++ b/deploy.sh @@ -13,8 +13,20 @@ TARGET_PLATFORM="linux/amd64" # server x86_64 (verificato con uname -m) cd "$(dirname "$0")" -# Il sito non ha bisogno di variabili d'ambiente: il .env locale contiene solo -# il token Gitea e NON va mai copiato sul server. +# Il .env locale contiene solo il token Gitea e NON va mai copiato sul server. +# Le variabili del server (chiave Places API e Place ID, ADR 0005) stanno in +# .env.server, git-ignorato, copiato sul server come .env. +if [[ ! -f .env.server ]]; then + echo "Errore: .env.server non trovato (vedi .env.server.example)." + exit 1 +fi + +# Istantanea degli orari dalla scheda Google, usata dalla build (tabella in +# Dove siamo, dati strutturati, testo orari). Se Google non risponde si +# prosegue con l'istantanea precedente. +echo "→ Lettura orari dalla scheda Google..." +(set -a; source .env.server; set +a; node scripts/orari-google.mjs --out src/data/orari-google.json) \ + || echo " ⚠ orari non aggiornati, uso l'istantanea esistente" echo "→ Build di verifica in locale..." npm run build @@ -25,6 +37,8 @@ docker buildx build --platform "$TARGET_PLATFORM" -t "$IMAGE_TAG" --load . echo "→ Preparazione cartella e compose su $SERVER..." ssh "$SSH_USER@$SERVER" "mkdir -p '$APP_DIR'" rsync -az docker-compose.yml "$SSH_USER@$SERVER:$APP_DIR/docker-compose.yml" +rsync -az --delete scripts/ "$SSH_USER@$SERVER:$APP_DIR/scripts/" +rsync -az --chmod=F600 .env.server "$SSH_USER@$SERVER:$APP_DIR/.env" echo "→ Trasferimento immagine..." docker save "$IMAGE_TAG" | gzip | ssh "$SSH_USER@$SERVER" "gunzip | docker load" @@ -34,12 +48,17 @@ ssh "$SSH_USER@$SERVER" " set -e cd '$APP_DIR' docker compose up -d + docker compose restart orari # rilegge script e chiave aggiornati docker compose ps " echo "→ Verifica interna (dalla rete a75)..." ssh "$SSH_USER@$SERVER" "docker exec nginx-app-1 curl -s -o /dev/null -w 'HTTP %{http_code}\n' http://officinezuliani-site:3000/" || true +echo "→ Verifica orari letti da Google..." +sleep 5 +ssh "$SSH_USER@$SERVER" "cd '$APP_DIR' && docker compose logs --tail 3 orari" || true + echo "→ Pulizia layer immagine inutilizzati..." ssh "$SSH_USER@$SERVER" "docker image prune -f" || true diff --git a/docker-compose.yml b/docker-compose.yml index 028cd21..d446127 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,6 +11,28 @@ services: # sulla rete Docker condivisa "a75" come officinezuliani-site:3000. networks: - a75 + volumes: + # orari.json scritto dal servizio "orari" (sola lettura per nginx) + - orari-dati:/usr/share/nginx/html/dati:ro + + orari: + # Legge gli orari dalla scheda Google Business Profile (Places API) ogni + # 6 ore e li scrive in orari.json (ADR 0005). La chiave sta solo nel .env + # del server, copiato da deploy.sh a partire da .env.server locale. + image: node:22-alpine + container_name: officinezuliani-orari + restart: always + env_file: + - .env + command: ["node", "/app/orari-google.mjs", "--out", "/dati/orari.json", "--ogni", "6"] + volumes: + - ./scripts:/app:ro + - orari-dati:/dati + networks: + - a75 + +volumes: + orari-dati: networks: a75: diff --git a/docker/nginx.conf b/docker/nginx.conf index 3283a29..3959003 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -33,6 +33,12 @@ server { expires 30d; } + # Orari letti da Google (servizio "orari"): sempre rivalidati + location /dati/ { + add_header Cache-Control "no-cache"; + add_header X-Robots-Tag "noindex" always; + } + gzip on; gzip_types text/css application/javascript application/json image/svg+xml application/xml text/plain; diff --git a/docs/adr/0005-orari-da-google-places.md b/docs/adr/0005-orari-da-google-places.md new file mode 100644 index 0000000..3f7c3ea --- /dev/null +++ b/docs/adr/0005-orari-da-google-places.md @@ -0,0 +1,19 @@ +# ADR 0005: Opening hours from the Google Business Profile via Places API + +## Status +Accepted (2026-11-04) + +## Context +Opening hours were hard-coded in the site. The client keeps them up to date on the Google Business Profile listing "Officine Zuliani E. di Peresani A. Tosoni B. & C. S.A.S.", including special closures (holidays, vacations). Having one source avoids mismatches between site and Google (also a local-SEO signal). + +## Decision +- Read hours with **Places API (New)** Place Details (`regularOpeningHours`, `currentOpeningHours`, `businessStatus`) using an API key restricted to Places API. The Business Profile API was rejected: owner OAuth and Google approval are overkill for reading hours. +- `scripts/orari-google.mjs` normalizes the response to the site format: `settimana` (days grouped by identical time ranges) and `prossimiGiorni` (actual ranges for the next 7 days, special closures included). On any error it leaves the existing file untouched. +- **Build time:** `deploy.sh` runs the script and writes `src/data/orari-google.json` (committed snapshot). The build uses it for the hours text, the table on /dove-siamo and the `openingHoursSpecification` JSON-LD. If it is missing, `src/data/orari.ts` falls back to hard-coded hours. +- **Runtime:** a second container `officinezuliani-orari` (`node:22-alpine`, no custom image) runs the same script every 6 hours and writes `orari.json` to a shared volume served by nginx at `/dati/orari.json`. The "open now" sign fetches it in the browser and redraws bars and status; if the fetch fails, the build-time hours stay. +- The key is never in the repository or in the browser: local `.env.server` (git-ignored) → copied by `deploy.sh` to the server as `.env` (mode 600). + +## Consequences +- The client edits hours only on Google; the sign follows within 6 hours, without a deploy. The /dove-siamo table and JSON-LD update at the next deploy. +- About 120 Place Details requests per month: expected to stay within Google Maps Platform free monthly usage, but a billing account is required — check the current price list. +- If Google returns no regular hours, nothing is overwritten (no blank sign). diff --git a/docs/context/module-map.md b/docs/context/module-map.md index 70b736b..c1de510 100644 --- a/docs/context/module-map.md +++ b/docs/context/module-map.md @@ -4,7 +4,9 @@ - `src/pages/` → site pages: `index`, `officina`, `servizi`, `dove-siamo`, `contatti`, plus `sitemap.xml` - `src/layouts/Base.astro` → HTML shell, meta/OG, canonical, AutoRepair JSON-LD, header/footer, reveal script - `src/components/` → `Insegna` (open-now sign + weekly hours), `ServiziLista`, `Marchi`, `Faq` (+ FAQPage JSON-LD), `BloccoContatti`, `StripFoto` (3-photo strip) -- `src/data/officina.ts` → single source of business data (NAP, hours, services, FAQ) +- `src/data/officina.ts` → single source of business data (NAP, legal name, services, FAQ) +- `src/data/orari.ts` → opening hours: Google snapshot `orari-google.json` or fallback (ADR 0005) +- `scripts/orari-google.mjs` → reads hours from Places API (deploy + `orari` container on the server) - `src/styles/global.css` → design tokens and shared styles (ADR 0002) - `public/` → favicon, robots.txt, partner logos - `src/assets/home/`, `src/assets/officina/` → page photos (demonstrative, AI-generated; optimized by astro:assets via `StripFoto`) @@ -16,4 +18,4 @@ - `.claude/launch.json` → preview configs: `sito` (Astro dev, 4321), `proposte` (4173) ## Important flows -- Opening hours: defined once in `src/data/officina.ts` → rendered as bars (Insegna), table (dove-siamo), JSON-LD (Base) +- Opening hours: Google Business Profile → Places API → `orari-google.json` (build: text, table, JSON-LD) and `/dati/orari.json` (runtime: Insegna "open now", special closures) diff --git a/docs/handoffs/2026-11-04-orari-google.md b/docs/handoffs/2026-11-04-orari-google.md new file mode 100644 index 0000000..6fbb9ea --- /dev/null +++ b/docs/handoffs/2026-11-04-orari-google.md @@ -0,0 +1,29 @@ +# Handoff + +## Issue +None (explicit user instruction: read opening hours from the Google Business Profile via Places API) + +## Goal +Make Google Business Profile the single source of opening hours. + +## Status +in-progress — code done; waiting for the API key in `.env.server` to look up the Place ID, take the first snapshot and deploy + +## What changed +- `scripts/orari-google.mjs` (Places API → site format; `--cerca` to find the Place ID) +- `src/data/orari.ts` (snapshot or fallback, `orariTesto` generated), `officina.ts` uses it; legal name added (footer + `legalName`) +- Insegna reads `/dati/orari.json` at runtime, handles special closures, redraws bars +- `docker-compose.yml`: `orari` service + shared volume; nginx `/dati/` no-cache; `deploy.sh` snapshot + `.env.server` transfer +- ADR 0005, runbook, module map, CLAUDE.md + +## Tests +- Run: script with a stubbed Places response (regular hours + holiday + half day) → correct `settimana` / `prossimiGiorni` +- Run: Insegna with a test `/dati/orari.json` (today closed) → "Chiuso ora · Riapriamo venerdì alle 8:00"; without file → build hours +- Not run: real Places API call (no key yet), server container + +## Risks / open questions +- Billing account required on Google Cloud; check free usage on the current price list +- Restrict the key to Places API (New) only + +## Suggested next step +- Fill `.env.server`, run `--cerca`, set `GOOGLE_PLACE_ID`, `./deploy.sh`, commit the snapshot diff --git a/docs/runbooks/deploy.md b/docs/runbooks/deploy.md index 00d86f9..d0b6254 100644 --- a/docs/runbooks/deploy.md +++ b/docs/runbooks/deploy.md @@ -8,7 +8,12 @@ Hosting: Docker on the a75 server, same flow as cam85 (`docs/adr/0004-hosting-do ``` It builds locally, builds the amd64 image, loads it on `217.76.62.220`, runs `docker compose up -d` in `/home/ubuntu/officinezuliani` and checks `http://officinezuliani-site:3000/` from the Nginx Proxy Manager container. -Requirements: SSH key access as `root@217.76.62.220`, Docker with buildx, Node/npm. +Requirements: SSH key access as `root@217.76.62.220`, Docker with buildx, Node/npm, and a local `.env.server` (copy `.env.server.example`) with `GOOGLE_PLACES_API_KEY` and `GOOGLE_PLACE_ID`. + +## Opening hours from Google (ADR 0005) +- Find the Place ID once: `set -a; source .env.server; set +a; node scripts/orari-google.mjs --cerca "Officine Zuliani Udine"` +- Each deploy refreshes `src/data/orari-google.json` (commit it with the deploy) +- On the server, container `officinezuliani-orari` refreshes `/dati/orari.json` every 6 hours: `docker compose logs orari` shows the last updates ## Publish a hostname (one-time, Nginx Proxy Manager UI) 1. DNS: A record of the hostname → `217.76.62.220` @@ -25,7 +30,8 @@ docker run --rm -p 8089:3000 officinezuliani-web:latest # http://localhost:808 Check out the previous good commit and run `./deploy.sh` again. ## Server layout -- `/home/ubuntu/officinezuliani/docker-compose.yml` (copied by deploy.sh) +- `/home/ubuntu/officinezuliani/docker-compose.yml`, `scripts/`, `.env` (from `.env.server`, mode 600) — all copied by deploy.sh +- Volume `orari-dati` shared by `orari` (writes) and `web` (`/dati/`, read-only) - Container `officinezuliani-site` on network `a75`, port 3000, no host ports ## Hostnames diff --git a/scripts/orari-google.mjs b/scripts/orari-google.mjs new file mode 100644 index 0000000..744c07c --- /dev/null +++ b/scripts/orari-google.mjs @@ -0,0 +1,133 @@ +#!/usr/bin/env node +// Legge gli orari di apertura dalla scheda Google Business Profile tramite +// Places API (New) e li salva nel formato usato dal sito (ADR 0005). +// +// Uso: +// node scripts/orari-google.mjs --cerca "Officine Zuliani Udine" → trova il Place ID +// node scripts/orari-google.mjs --out src/data/orari-google.json → aggiorna una volta +// node scripts/orari-google.mjs --out /dati/orari.json --ogni 6 → ripete ogni 6 ore (server) +// +// Variabili d'ambiente: GOOGLE_PLACES_API_KEY, GOOGLE_PLACE_ID. +// Se Google non risponde o i dati non sono validi, il file esistente NON viene toccato. + +import { writeFileSync, renameSync, mkdirSync } from 'node:fs'; +import { dirname } from 'node:path'; + +const API = 'https://places.googleapis.com/v1'; +const chiave = process.env.GOOGLE_PLACES_API_KEY; +const placeId = process.env.GOOGLE_PLACE_ID; + +const arg = (nome) => { + const i = process.argv.indexOf(nome); + return i > -1 ? process.argv[i + 1] : undefined; +}; + +const log = (...m) => console.log(new Date().toISOString(), ...m); + +if (!chiave) { + console.error('Manca GOOGLE_PLACES_API_KEY'); + process.exit(1); +} + +async function cerca(testo) { + const r = await fetch(`${API}/places:searchText`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Api-Key': chiave, + 'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress', + }, + body: JSON.stringify({ textQuery: testo, languageCode: 'it' }), + }); + if (!r.ok) throw new Error(`Places API ${r.status}: ${await r.text()}`); + const { places = [] } = await r.json(); + for (const p of places) console.log(`${p.id} ${p.displayName?.text} — ${p.formattedAddress}`); + if (!places.length) console.log('Nessun risultato'); +} + +const min = (t) => (t?.hour ?? 0) * 60 + (t?.minute ?? 0); + +/** Periodi Google → fasce per giorno (0 = domenica). Un periodo senza "close" = aperto 24 ore. */ +function fascePerGiorno(periodi = []) { + const perGiorno = new Map(); + const aggiungi = (chiave, fascia) => perGiorno.set(chiave, [...(perGiorno.get(chiave) ?? []), fascia]); + for (const p of periodi) { + const fine = !p.close ? 24 * 60 : p.close.day !== p.open.day ? 24 * 60 : min(p.close); + const chiaveGiorno = p.open.date + ? `${p.open.date.year}-${String(p.open.date.month).padStart(2, '0')}-${String(p.open.date.day).padStart(2, '0')}` + : p.open.day; + aggiungi(chiaveGiorno, [min(p.open), fine]); + } + for (const f of perGiorno.values()) f.sort((a, b) => a[0] - b[0]); + return perGiorno; +} + +/** Raggruppa i giorni con le stesse fasce: [{ giorni: [1,2,3,4,5], fasce: [[480,720], …] }]. */ +function settimana(perGiorno) { + const gruppi = new Map(); + for (let g = 0; g < 7; g++) { + const f = perGiorno.get(g); + if (!f) continue; + const k = JSON.stringify(f); + gruppi.set(k, { giorni: [...(gruppi.get(k)?.giorni ?? []), g], fasce: f }); + } + return [...gruppi.values()]; +} + +/** Date dei prossimi 7 giorni (ora di Roma), per segnare come chiusi i giorni senza periodi. */ +function prossimeDate() { + const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Rome' }); + return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(Date.now() + i * 864e5))); +} + +async function aggiorna(out) { + if (!placeId) throw new Error('Manca GOOGLE_PLACE_ID'); + const r = await fetch(`${API}/places/${placeId}?languageCode=it`, { + headers: { + 'X-Goog-Api-Key': chiave, + 'X-Goog-FieldMask': 'regularOpeningHours,currentOpeningHours,businessStatus', + }, + }); + if (!r.ok) throw new Error(`Places API ${r.status}: ${await r.text()}`); + const dati = await r.json(); + + const regolari = settimana(fascePerGiorno(dati.regularOpeningHours?.periods)); + if (!regolari.length) throw new Error('Nessun orario regolare nella scheda: file non aggiornato'); + + const correnti = fascePerGiorno(dati.currentOpeningHours?.periods); + const prossimiGiorni = {}; + if (dati.currentOpeningHours) for (const d of prossimeDate()) prossimiGiorni[d] = correnti.get(d) ?? []; + + const risultato = { + fonte: 'google', + aggiornato: new Date().toISOString(), + statoAttivita: dati.businessStatus ?? null, + settimana: regolari, + prossimiGiorni, + }; + + mkdirSync(dirname(out), { recursive: true }); + const tmp = `${out}.tmp`; + writeFileSync(tmp, `${JSON.stringify(risultato, null, 2)}\n`); + renameSync(tmp, out); // scrittura atomica: nginx non legge mai un file a metà + log(`Orari aggiornati in ${out}`); +} + +const testo = arg('--cerca'); +const out = arg('--out'); +const ogni = Number(arg('--ogni')); + +if (testo) { + await cerca(testo); +} else if (out && ogni > 0) { + // Servizio sul server: aggiorna subito, poi ogni N ore. Un errore non ferma il ciclo. + for (;;) { + try { await aggiorna(out); } catch (e) { log('Errore:', e.message); } + await new Promise((r) => setTimeout(r, ogni * 3600e3)); + } +} else if (out) { + try { await aggiorna(out); } catch (e) { log('Errore:', e.message); process.exit(1); } +} else { + console.error('Specificare --cerca "testo" oppure --out [--ogni ]'); + process.exit(1); +} diff --git a/src/components/Insegna.astro b/src/components/Insegna.astro index e14761f..aa0d22a 100644 --- a/src/components/Insegna.astro +++ b/src/components/Insegna.astro @@ -1,15 +1,19 @@ --- // Insegna smaltata con stato "aperto ora" e barre degli orari settimanali. -// Le barre sono generate in HTML; lo script calcola solo lo stato con l'ora di Roma. +// Le barre vengono generate in HTML con gli orari della build; nel browser lo +// script legge /dati/orari.json (aggiornato dal server dalla scheda Google, ADR 0005), +// ridisegna le barre e calcola lo stato con l'ora di Roma, incluse le chiusure +// straordinarie. Se il file non è disponibile restano gli orari della build. import { officina } from '../data/officina'; +import { orari, fasceDelGiorno } from '../data/orari'; const nomi = ['D', 'L', 'M', 'M', 'G', 'V', 'S']; const ordine = [1, 2, 3, 4, 5, 6, 0]; const inizio = 7 * 60, fine = 19 * 60 + 30; // scala verticale delle barre -const pct = (v: number) => (((v - inizio) / (fine - inizio)) * 100).toFixed(1); -const fasceDi = (g: number) => officina.orari.filter((o) => o.giorni.includes(g)).flatMap((o) => o.fasce); +const pct = (v: number) => Math.max(0, Math.min(100, ((v - inizio) / (fine - inizio)) * 100)); +const stileBarra = ([a, b]: [number, number]) => `top:${pct(a).toFixed(1)}%;height:${(pct(b) - pct(a)).toFixed(1)}%`; --- -