feat: read opening hours from Google Business Profile
Places API script normalizes regular and special hours; build uses a snapshot, an orari sidecar refreshes /dati/orari.json every 6 hours for the open-now sign. Adds the company legal name. Key stays in .env.server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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=
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
!.env.server.example
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
@@ -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)
|
- Dev: `npm run dev` (http://localhost:4321)
|
||||||
- Build: `npm run build` (output in `dist/`)
|
- Build: `npm run build` (output in `dist/`)
|
||||||
- Preview build: `npm run preview`
|
- 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`)
|
- Test / Lint / Typecheck: not set up yet (`npm run check` needs `@astrojs/check`)
|
||||||
- Design proposals: `python3 -m http.server 4173 --directory design`
|
- Design proposals: `python3 -m http.server 4173 --directory design`
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,20 @@ TARGET_PLATFORM="linux/amd64" # server x86_64 (verificato con uname -m)
|
|||||||
|
|
||||||
cd "$(dirname "$0")"
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
# Il sito non ha bisogno di variabili d'ambiente: il .env locale contiene solo
|
# Il .env locale contiene solo il token Gitea e NON va mai copiato sul server.
|
||||||
# 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..."
|
echo "→ Build di verifica in locale..."
|
||||||
npm run build
|
npm run build
|
||||||
@@ -25,6 +37,8 @@ docker buildx build --platform "$TARGET_PLATFORM" -t "$IMAGE_TAG" --load .
|
|||||||
echo "→ Preparazione cartella e compose su $SERVER..."
|
echo "→ Preparazione cartella e compose su $SERVER..."
|
||||||
ssh "$SSH_USER@$SERVER" "mkdir -p '$APP_DIR'"
|
ssh "$SSH_USER@$SERVER" "mkdir -p '$APP_DIR'"
|
||||||
rsync -az docker-compose.yml "$SSH_USER@$SERVER:$APP_DIR/docker-compose.yml"
|
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..."
|
echo "→ Trasferimento immagine..."
|
||||||
docker save "$IMAGE_TAG" | gzip | ssh "$SSH_USER@$SERVER" "gunzip | docker load"
|
docker save "$IMAGE_TAG" | gzip | ssh "$SSH_USER@$SERVER" "gunzip | docker load"
|
||||||
@@ -34,12 +48,17 @@ ssh "$SSH_USER@$SERVER" "
|
|||||||
set -e
|
set -e
|
||||||
cd '$APP_DIR'
|
cd '$APP_DIR'
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
|
docker compose restart orari # rilegge script e chiave aggiornati
|
||||||
docker compose ps
|
docker compose ps
|
||||||
"
|
"
|
||||||
|
|
||||||
echo "→ Verifica interna (dalla rete a75)..."
|
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
|
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..."
|
echo "→ Pulizia layer immagine inutilizzati..."
|
||||||
ssh "$SSH_USER@$SERVER" "docker image prune -f" || true
|
ssh "$SSH_USER@$SERVER" "docker image prune -f" || true
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,28 @@ services:
|
|||||||
# sulla rete Docker condivisa "a75" come officinezuliani-site:3000.
|
# sulla rete Docker condivisa "a75" come officinezuliani-site:3000.
|
||||||
networks:
|
networks:
|
||||||
- a75
|
- 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:
|
networks:
|
||||||
a75:
|
a75:
|
||||||
|
|||||||
@@ -33,6 +33,12 @@ server {
|
|||||||
expires 30d;
|
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 on;
|
||||||
gzip_types text/css application/javascript application/json image/svg+xml application/xml text/plain;
|
gzip_types text/css application/javascript application/json image/svg+xml application/xml text/plain;
|
||||||
|
|
||||||
|
|||||||
@@ -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).
|
||||||
@@ -4,7 +4,9 @@
|
|||||||
- `src/pages/` → site pages: `index`, `officina`, `servizi`, `dove-siamo`, `contatti`, plus `sitemap.xml`
|
- `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/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/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)
|
- `src/styles/global.css` → design tokens and shared styles (ADR 0002)
|
||||||
- `public/` → favicon, robots.txt, partner logos
|
- `public/` → favicon, robots.txt, partner logos
|
||||||
- `src/assets/home/`, `src/assets/officina/` → page photos (demonstrative, AI-generated; optimized by astro:assets via `StripFoto`)
|
- `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)
|
- `.claude/launch.json` → preview configs: `sito` (Astro dev, 4321), `proposte` (4173)
|
||||||
|
|
||||||
## Important flows
|
## 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)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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.
|
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)
|
## Publish a hostname (one-time, Nginx Proxy Manager UI)
|
||||||
1. DNS: A record of the hostname → `217.76.62.220`
|
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.
|
Check out the previous good commit and run `./deploy.sh` again.
|
||||||
|
|
||||||
## Server layout
|
## 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
|
- Container `officinezuliani-site` on network `a75`, port 3000, no host ports
|
||||||
|
|
||||||
## Hostnames
|
## Hostnames
|
||||||
|
|||||||
@@ -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 <file> [--ogni <ore>]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
@@ -1,15 +1,19 @@
|
|||||||
---
|
---
|
||||||
// Insegna smaltata con stato "aperto ora" e barre degli orari settimanali.
|
// 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 { officina } from '../data/officina';
|
||||||
|
import { orari, fasceDelGiorno } from '../data/orari';
|
||||||
|
|
||||||
const nomi = ['D', 'L', 'M', 'M', 'G', 'V', 'S'];
|
const nomi = ['D', 'L', 'M', 'M', 'G', 'V', 'S'];
|
||||||
const ordine = [1, 2, 3, 4, 5, 6, 0];
|
const ordine = [1, 2, 3, 4, 5, 6, 0];
|
||||||
const inizio = 7 * 60, fine = 19 * 60 + 30; // scala verticale delle barre
|
const inizio = 7 * 60, fine = 19 * 60 + 30; // scala verticale delle barre
|
||||||
const pct = (v: number) => (((v - inizio) / (fine - inizio)) * 100).toFixed(1);
|
const pct = (v: number) => Math.max(0, Math.min(100, ((v - inizio) / (fine - inizio)) * 100));
|
||||||
const fasceDi = (g: number) => officina.orari.filter((o) => o.giorni.includes(g)).flatMap((o) => o.fasce);
|
const stileBarra = ([a, b]: [number, number]) => `top:${pct(a).toFixed(1)}%;height:${(pct(b) - pct(a)).toFixed(1)}%`;
|
||||||
---
|
---
|
||||||
<aside class="insegna su" data-orari={JSON.stringify(officina.orari)} aria-label="Orari di apertura">
|
<aside class="insegna su" data-orari={JSON.stringify(orari)} aria-label="Orari di apertura">
|
||||||
<div class="stato"><i></i><span data-stato>Orari di apertura</span></div>
|
<div class="stato"><i></i><span data-stato>Orari di apertura</span></div>
|
||||||
<p data-sub>{officina.orariTesto}</p>
|
<p data-sub>{officina.orariTesto}</p>
|
||||||
<div class="settimana">
|
<div class="settimana">
|
||||||
@@ -17,7 +21,7 @@ const fasceDi = (g: number) => officina.orari.filter((o) => o.giorni.includes(g)
|
|||||||
<div class="giorno" data-giorno={g}>
|
<div class="giorno" data-giorno={g}>
|
||||||
{nomi[g]}
|
{nomi[g]}
|
||||||
<div class="barra">
|
<div class="barra">
|
||||||
{fasceDi(g).map(([a, b]) => <span style={`top:${pct(a)}%;height:${(+pct(b) - +pct(a)).toFixed(1)}%`} />)}
|
{fasceDelGiorno(orari.settimana, g).map((f) => <span style={stileBarra(f)} />)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -26,37 +30,71 @@ const fasceDi = (g: number) => officina.orari.filter((o) => o.giorni.includes(g)
|
|||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
type Orari = { giorni: number[]; fasce: [number, number][] }[];
|
import { fasceDelGiorno, type OrariDati, type Fascia } from '../data/orari';
|
||||||
const el = document.querySelector<HTMLElement>('.insegna');
|
|
||||||
if (el) {
|
|
||||||
const orari: Orari = JSON.parse(el.dataset.orari || '[]');
|
|
||||||
// Ora corrente a Udine, indipendente dal fuso del visitatore
|
|
||||||
const parti = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/Rome', weekday: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(new Date());
|
|
||||||
const p = (t: string) => parti.find((x) => x.type === t)?.value ?? '';
|
|
||||||
const g = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(p('weekday'));
|
|
||||||
const m = +p('hour') * 60 + +p('minute');
|
|
||||||
const fasce = (d: number) => orari.filter((o) => o.giorni.includes(d)).flatMap((o) => o.fasce);
|
|
||||||
const hhmm = (v: number) => `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`;
|
|
||||||
const giorniNome = ['domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato'];
|
|
||||||
|
|
||||||
el.querySelector(`[data-giorno="${g}"]`)?.classList.add('oggi');
|
const el = document.querySelector<HTMLElement>('.insegna');
|
||||||
const aperta = fasce(g).find(([a, b]) => m >= a && m < b);
|
|
||||||
const stato = el.querySelector('[data-stato]')!, sub = el.querySelector('[data-sub]')!;
|
const inizio = 7 * 60, fine = 19 * 60 + 30;
|
||||||
|
const pct = (v: number) => Math.max(0, Math.min(100, ((v - inizio) / (fine - inizio)) * 100));
|
||||||
|
const hhmm = (v: number) => `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`;
|
||||||
|
const giorniNome = ['domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato'];
|
||||||
|
|
||||||
|
// Data e ora correnti a Udine, indipendenti dal fuso del visitatore
|
||||||
|
function adessoRoma(offsetGiorni = 0) {
|
||||||
|
const d = new Date(Date.now() + offsetGiorni * 864e5);
|
||||||
|
const parti = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/Rome', weekday: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(d);
|
||||||
|
const p = (t: string) => parti.find((x) => x.type === t)?.value ?? '';
|
||||||
|
return {
|
||||||
|
giorno: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(p('weekday')),
|
||||||
|
minuti: +p('hour') * 60 + +p('minute'),
|
||||||
|
data: new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Rome' }).format(d), // AAAA-MM-GG
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function aggiorna(insegna: HTMLElement, dati: OrariDati) {
|
||||||
|
// Fasce effettive: prima le eccezioni di Google (ferie, festivi), poi la settimana tipo
|
||||||
|
const fasce = (offset: number): Fascia[] => {
|
||||||
|
const { giorno, data } = adessoRoma(offset);
|
||||||
|
return dati.prossimiGiorni?.[data] ?? fasceDelGiorno(dati.settimana, giorno);
|
||||||
|
};
|
||||||
|
|
||||||
|
insegna.querySelectorAll<HTMLElement>('[data-giorno]').forEach((g) => {
|
||||||
|
const barra = g.querySelector('.barra')!;
|
||||||
|
barra.replaceChildren(...fasceDelGiorno(dati.settimana, +g.dataset.giorno!).map(([a, b]) => {
|
||||||
|
const s = document.createElement('span');
|
||||||
|
s.style.top = `${pct(a).toFixed(1)}%`;
|
||||||
|
s.style.height = `${(pct(b) - pct(a)).toFixed(1)}%`;
|
||||||
|
return s;
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
const { giorno, minuti } = adessoRoma();
|
||||||
|
insegna.querySelectorAll('.oggi').forEach((x) => x.classList.remove('oggi'));
|
||||||
|
insegna.querySelector(`[data-giorno="${giorno}"]`)?.classList.add('oggi');
|
||||||
|
|
||||||
|
const stato = insegna.querySelector('[data-stato]')!, sub = insegna.querySelector('[data-sub]')!;
|
||||||
|
const aperta = fasce(0).find(([a, b]) => minuti >= a && minuti < b);
|
||||||
|
insegna.classList.toggle('chiuso', !aperta);
|
||||||
if (aperta) {
|
if (aperta) {
|
||||||
stato.textContent = 'Aperto ora';
|
stato.textContent = 'Aperto ora';
|
||||||
sub.textContent = `Chiudiamo alle ${hhmm(aperta[1])}`;
|
sub.textContent = `Chiudiamo alle ${hhmm(aperta[1])}`;
|
||||||
} else {
|
return;
|
||||||
el.classList.add('chiuso');
|
|
||||||
stato.textContent = 'Chiuso ora';
|
|
||||||
const oggiDopo = fasce(g).find(([a]) => a > m);
|
|
||||||
if (oggiDopo) sub.textContent = `Riapriamo alle ${hhmm(oggiDopo[0])}`;
|
|
||||||
else {
|
|
||||||
for (let i = 1; i <= 7; i++) {
|
|
||||||
const d = (g + i) % 7, f = fasce(d)[0];
|
|
||||||
if (f) { sub.textContent = `Riapriamo ${i === 1 ? 'domani' : giorniNome[d]} alle ${hhmm(f[0])}`; break; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
stato.textContent = 'Chiuso ora';
|
||||||
|
const oggiDopo = fasce(0).find(([a]) => a > minuti);
|
||||||
|
if (oggiDopo) { sub.textContent = `Riapriamo alle ${hhmm(oggiDopo[0])}`; return; }
|
||||||
|
for (let i = 1; i <= 14; i++) {
|
||||||
|
const f = fasce(i)[0];
|
||||||
|
if (f) { sub.textContent = `Riapriamo ${i === 1 ? 'domani' : giorniNome[adessoRoma(i).giorno]} alle ${hhmm(f[0])}`; return; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (el) {
|
||||||
|
aggiorna(el, JSON.parse(el.dataset.orari || '{}'));
|
||||||
|
fetch('/dati/orari.json', { cache: 'no-cache' })
|
||||||
|
.then((r) => (r.ok ? r.json() : null))
|
||||||
|
.then((dati: OrariDati | null) => { if (dati?.settimana?.length) aggiorna(el, dati); })
|
||||||
|
.catch(() => {}); // senza file restano gli orari della build
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -71,7 +109,7 @@ const fasceDi = (g: number) => officina.orari.filter((o) => o.giorni.includes(g)
|
|||||||
.settimana{display:grid;grid-template-columns:repeat(7,1fr);gap:6px;margin-top:24px}
|
.settimana{display:grid;grid-template-columns:repeat(7,1fr);gap:6px;margin-top:24px}
|
||||||
.giorno{font:600 12px/1 var(--display);text-align:center;color:#C9D6E6}
|
.giorno{font:600 12px/1 var(--display);text-align:center;color:#C9D6E6}
|
||||||
.barra{height:64px;border-radius:6px;background:rgba(255,255,255,.08);margin-top:6px;position:relative;overflow:hidden}
|
.barra{height:64px;border-radius:6px;background:rgba(255,255,255,.08);margin-top:6px;position:relative;overflow:hidden}
|
||||||
.barra span{position:absolute;left:0;right:0;background:var(--segnale);border-radius:3px}
|
.barra :global(span){position:absolute;left:0;right:0;background:var(--segnale);border-radius:3px}
|
||||||
.giorno.oggi{color:var(--segnale)}
|
.giorno.oggi{color:var(--segnale)}
|
||||||
.giorno.oggi .barra{outline:2px solid var(--segnale)}
|
.giorno.oggi .barra{outline:2px solid var(--segnale)}
|
||||||
.tel{display:block;margin-top:22px;font:800 30px/1 var(--display);text-decoration:none;color:var(--segnale)}
|
.tel{display:block;margin-top:22px;font:800 30px/1 var(--display);text-decoration:none;color:var(--segnale)}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
// Dati dell'attività: unica fonte per pagine, contatti e dati strutturati (JSON-LD).
|
// Dati dell'attività: unica fonte per pagine, contatti e dati strutturati (JSON-LD).
|
||||||
// Da verificare col cliente: nome ufficiale, apertura il sabato (vedi docs/analisi).
|
// Gli orari stanno in ./orari.ts (letti dalla scheda Google Business Profile).
|
||||||
|
import { orari, orariTesto } from './orari';
|
||||||
|
|
||||||
export const officina = {
|
export const officina = {
|
||||||
nome: 'Officine Zuliani',
|
nome: 'Officine Zuliani',
|
||||||
|
ragioneSociale: 'Officine Zuliani E. di Peresani A. Tosoni B. & C. S.A.S.',
|
||||||
sito: 'https://www.officinezulianiudine.it',
|
sito: 'https://www.officinezulianiudine.it',
|
||||||
indirizzo: {
|
indirizzo: {
|
||||||
via: 'Viale Venezia 446',
|
via: 'Viale Venezia 446',
|
||||||
@@ -16,11 +18,8 @@ export const officina = {
|
|||||||
email: 'autogas.udine@libero.it',
|
email: 'autogas.udine@libero.it',
|
||||||
piva: '02026960308',
|
piva: '02026960308',
|
||||||
mappa: 'https://maps.google.com/?q=Viale+Venezia+446+Udine',
|
mappa: 'https://maps.google.com/?q=Viale+Venezia+446+Udine',
|
||||||
// Giorni: 0 = domenica … 6 = sabato. Orari in minuti dalla mezzanotte, ora di Roma.
|
orari: orari.settimana,
|
||||||
orari: [
|
orariTesto: orariTesto(orari.settimana),
|
||||||
{ giorni: [1, 2, 3, 4, 5], fasce: [[8 * 60, 12 * 60], [14 * 60, 18 * 60 + 30]] },
|
|
||||||
] as { giorni: number[]; fasce: [number, number][] }[],
|
|
||||||
orariTesto: 'Lun–Ven 8:00–12:00 · 14:00–18:30',
|
|
||||||
reti: ['Rete Bosch AutoCrew', 'Assistenza ufficiale BRC', 'Installatore Prins'],
|
reti: ['Rete Bosch AutoCrew', 'Assistenza ufficiale BRC', 'Installatore Prins'],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// Orari di apertura (ADR 0005).
|
||||||
|
// Fonte: scheda Google Business Profile, letta tramite Places API da
|
||||||
|
// scripts/orari-google.mjs. Ad ogni deploy lo script salva un'istantanea in
|
||||||
|
// src/data/orari-google.json, usata qui al momento della build; sul server lo
|
||||||
|
// stesso script aggiorna /dati/orari.json, che l'insegna legge dal browser.
|
||||||
|
// Se l'istantanea manca si usano gli orari di riserva qui sotto.
|
||||||
|
|
||||||
|
/** Giorni: 0 = domenica … 6 = sabato. Fasce in minuti dalla mezzanotte, ora di Roma. */
|
||||||
|
export type Fascia = [number, number];
|
||||||
|
export type Settimana = { giorni: number[]; fasce: Fascia[] }[];
|
||||||
|
export type OrariDati = {
|
||||||
|
fonte: 'google' | 'riserva';
|
||||||
|
aggiornato: string | null;
|
||||||
|
settimana: Settimana;
|
||||||
|
/** Fasce effettive dei prossimi giorni (chiusure e orari speciali inclusi), chiave AAAA-MM-GG. */
|
||||||
|
prossimiGiorni: Record<string, Fascia[]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const riserva: OrariDati = {
|
||||||
|
fonte: 'riserva',
|
||||||
|
aggiornato: null,
|
||||||
|
settimana: [{ giorni: [1, 2, 3, 4, 5], fasce: [[8 * 60, 12 * 60], [14 * 60, 18 * 60 + 30]] }],
|
||||||
|
prossimiGiorni: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const istantanea = Object.values(
|
||||||
|
import.meta.glob<OrariDati>('./orari-google.json', { eager: true, import: 'default' }),
|
||||||
|
)[0];
|
||||||
|
|
||||||
|
export const orari: OrariDati = istantanea?.settimana?.length ? istantanea : riserva;
|
||||||
|
|
||||||
|
export const fasceDelGiorno = (settimana: Settimana, giorno: number): Fascia[] =>
|
||||||
|
settimana.filter((o) => o.giorni.includes(giorno)).flatMap((o) => o.fasce);
|
||||||
|
|
||||||
|
const hhmm = (m: number) => `${Math.floor(m / 60)}:${String(m % 60).padStart(2, '0')}`;
|
||||||
|
const abbr = ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'];
|
||||||
|
|
||||||
|
/** Es. "Lun–Ven 8:00–12:00 · 14:00–18:30". Giorni consecutivi con gli stessi orari vengono raggruppati. */
|
||||||
|
export function orariTesto(settimana: Settimana): string {
|
||||||
|
const ordine = [1, 2, 3, 4, 5, 6, 0];
|
||||||
|
const chiave = (g: number) => fasceDelGiorno(settimana, g).map(([a, b]) => `${hhmm(a)}–${hhmm(b)}`).join(' · ');
|
||||||
|
const gruppi: { da: number; a: number; testo: string }[] = [];
|
||||||
|
for (const g of ordine) {
|
||||||
|
const t = chiave(g);
|
||||||
|
if (!t) continue;
|
||||||
|
const ultimo = gruppi.at(-1);
|
||||||
|
if (ultimo && ultimo.testo === t && ordine.indexOf(g) === ordine.indexOf(ultimo.a) + 1) ultimo.a = g;
|
||||||
|
else gruppi.push({ da: g, a: g, testo: t });
|
||||||
|
}
|
||||||
|
return gruppi.map((x) => `${abbr[x.da]}${x.a !== x.da ? `–${abbr[x.a]}` : ''} ${x.testo}`).join(' / ');
|
||||||
|
}
|
||||||
@@ -28,6 +28,7 @@ const schema = {
|
|||||||
'@type': 'AutoRepair',
|
'@type': 'AutoRepair',
|
||||||
'@id': `${officina.sito}/#officina`,
|
'@id': `${officina.sito}/#officina`,
|
||||||
name: officina.nome,
|
name: officina.nome,
|
||||||
|
legalName: officina.ragioneSociale,
|
||||||
url: `${officina.sito}/`,
|
url: `${officina.sito}/`,
|
||||||
telephone: officina.telefono.e164,
|
telephone: officina.telefono.e164,
|
||||||
email: officina.email,
|
email: officina.email,
|
||||||
@@ -90,7 +91,7 @@ const schema = {
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="site-footer"><div class="wrap">
|
<footer class="site-footer"><div class="wrap">
|
||||||
<span>{officina.nome} · {officina.indirizzo.via}, {officina.indirizzo.cap} {officina.indirizzo.citta} ({officina.indirizzo.provincia}) · P.IVA {officina.piva} · <a href={`mailto:${officina.email}`}>{officina.email}</a></span>
|
<span>{officina.ragioneSociale} · {officina.indirizzo.via}, {officina.indirizzo.cap} {officina.indirizzo.citta} ({officina.indirizzo.provincia}) · P.IVA {officina.piva} · <a href={`mailto:${officina.email}`}>{officina.email}</a></span>
|
||||||
<nav aria-label="Piè di pagina">{nav.map((n) => <a href={n.href}>{n.label}</a>)}</nav>
|
<nav aria-label="Piè di pagina">{nav.map((n) => <a href={n.href}>{n.label}</a>)}</nav>
|
||||||
</div></footer>
|
</div></footer>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user