# ALFALATOR ofertas — Arquitectura Técnica, PostGIS y Leaflet.js

Documento técnico de referencia para implementar el backend, la base de datos espacial y el cliente web/móvil de **ALFALATOR ofertas**.

---

## 1. Stack Recomendado

- **Frontend Web & Móvil:** React (Next.js o Vite + PWA / Capacitor) + Tailwind CSS + **Leaflet.js** + **Leaflet.markercluster**.
- **Backend API:** Node.js (Fastify o NestJS) con TypeScript y validación Zod.
- **Base de Datos:** **PostgreSQL 16 + PostGIS** (consultas espaciales por radio en metros/km) + extensión `pg_trgm` para búsqueda instantánea por texto parcial.

---

## 2. Estructura de Carpetas

```text
alfalator/
├── frontend/
│   ├── src/
│   │   ├── components/
│   │   │   ├── MapView.tsx            # Inicialización Leaflet + markercluster + geofencing
│   │   │   ├── SearchBar.tsx          # Buscador central con debounce
│   │   │   ├── StoreOffersDrawer.tsx  # Popup / sidebar de ofertas paginadas
│   │   │   └── admin/
│   │   │       ├── StoreManager.tsx   # CRUD de comercios y coordenadas
│   │   │       └── BulkUpload.tsx     # Carga masiva CSV/JSON
│   │   └── services/api.ts
├── backend/
│   ├── src/
│   │   ├── routes/
│   │   │   ├── offers.routes.ts       # GET /api/offers/search?q=leche&lat=...&lng=...&radius=5000&page=1
│   │   │   ├── stores.routes.ts       # GET /api/stores/:id/offers & CRUD admin
│   │   │   └── import.routes.ts       # POST /api/admin/bulk-upload (streaming CSV)
│   │   └── db/pool.ts
└── database/
    └── schema.sql                     # Tablas + índices PostGIS y trigramas
```

---

## 3. Esquema SQL Optimizado (PostgreSQL + PostGIS)

```sql
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- 1. Supermercados geolocalizados
CREATE TABLE stores (
  id          BIGSERIAL PRIMARY KEY,
  name        VARCHAR(150) NOT NULL,
  address     VARCHAR(255) NOT NULL,
  geom        GEOGRAPHY(Point, 4326) NOT NULL,
  is_active   BOOLEAN NOT NULL DEFAULT TRUE,
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_stores_geom ON stores USING GIST (geom);

-- 2. Catálogo maestro de productos (miles de registros)
CREATE TABLE products (
  id          BIGSERIAL PRIMARY KEY,
  sku         VARCHAR(64) UNIQUE NOT NULL,
  name        VARCHAR(200) NOT NULL,
  category    VARCHAR(80) NOT NULL,
  unit        VARCHAR(40) NOT NULL
);

CREATE INDEX idx_products_name_trgm ON products USING GIN (name gin_trgm_ops);

-- 3. Ofertas vigentes por comercio
CREATE TABLE store_offers (
  id              BIGSERIAL PRIMARY KEY,
  store_id        BIGINT NOT NULL REFERENCES stores(id) ON DELETE CASCADE,
  product_id      BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
  regular_price   NUMERIC(10, 2) NOT NULL,
  offer_price     NUMERIC(10, 2) NOT NULL,
  is_on_offer     BOOLEAN NOT NULL DEFAULT TRUE,
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE (store_id, product_id)
);

-- Índice compuesto para filtrar ofertas y ordenar por menor precio al instante
CREATE INDEX idx_offers_product_price
  ON store_offers (product_id, offer_price ASC)
  WHERE is_on_offer = TRUE;
```

### Consulta espacial + búsqueda indexada + paginación

```sql
SELECT
  s.id AS store_id,
  s.name AS store_name,
  ST_Y(s.geom::geometry) AS lat,
  ST_X(s.geom::geometry) AS lng,
  ROUND(ST_Distance(s.geom, ST_MakePoint($2, $1)::geography)) AS distance_m,
  p.name AS product_name,
  o.offer_price,
  o.regular_price,
  COUNT(*) OVER() AS total_count
FROM store_offers o
JOIN stores s ON s.id = o.store_id
JOIN products p ON p.id = o.product_id
WHERE o.is_on_offer = TRUE
  AND s.is_active = TRUE
  AND p.name ILIKE '%' || $3 || '%'
  AND ST_DWithin(s.geom, ST_MakePoint($2, $1)::geography, $4) -- radio en metros (ej. 5000)
ORDER BY o.offer_price ASC, distance_m ASC
LIMIT $5 OFFSET ($6 - 1) * $5;
```

---

## 4. Inicialización de Leaflet.js + MarkerCluster + Carga Paginada

```javascript
// Inicialización del mapa estilo Google Maps con geofencing
const map = L.map('map').setView([40.4168, -3.7038], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; OpenStreetMap'
}).addTo(map);

const clusterGroup = L.markerClusterGroup({
  chunkedLoading: true,
  maxClusterRadius: 50
}).addTo(map);

// Centrar automáticamente en la ubicación del usuario
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(({ coords }) => {
    map.setView([coords.latitude, coords.longitude], 14);
    loadPaginatedOffers({ query: 'Leche', lat: coords.latitude, lng: coords.longitude, page: 1 });
  });
}

// Carga paginada desde el servidor y actualización de marcadores
async function loadPaginatedOffers({ query, lat, lng, radius = 5000, page = 1 }) {
  const params = new URLSearchParams({ q: query, lat, lng, radius, page, limit: 20 });
  const res = await fetch(`/api/offers/search?${params}`);
  const { items, lowestPrice } = await res.json();

  clusterGroup.clearLayers();

  items.forEach((store) => {
    const isLowest = store.offer_price === lowestPrice;
    const icon = L.divIcon({
      className: isLowest ? 'pin-best-price' : 'pin-standard',
      html: `<span>${store.offer_price.toFixed(2)} €</span>`
    });

    const marker = L.marker([store.lat, store.lng], { icon });
    marker.on('click', () => openStoreSidebar(store.store_id));
    clusterGroup.addLayer(marker);
  });
}
```
