Files
officinazuliani/scripts/orari-google.mjs
T
andrearuffiniandClaude Opus 5.5 a651519dbe 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>
2026-11-04 16:13:35 +01:00

134 lines
5.0 KiB
JavaScript

#!/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);
}