Initial commit.

This commit is contained in:
Paco Rodríguez 2026-11-15 00:26:44 +00:00
commit 02d53b6596
17 changed files with 2863 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
./tienda-flores
./tienda-flores-amd64
./tienda-flores-arm64
./ca-certificates.crt

9
Dockerfile Normal file
View file

@ -0,0 +1,9 @@
FROM scratch
COPY ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY tienda-flores /tienda-flores
EXPOSE 8080
ENTRYPOINT ["/tienda-flores"]
CMD ["-http-addr", ":8080", "-base-path", "/tienda"]

27
Makefile Normal file
View file

@ -0,0 +1,27 @@
BINARY_NAME=tienda-flores
IMAGE_NAME=mamavia.duckdns.org/paco/tienda-flores:latest
.PHONY: all fmt fmt-check test build build-amd64 build-arm64 clean
all: fmt test build
fmt:
gofmt -w .
fmt-check:
@test -z "$$(gofmt -l .)" || (echo "Unformatted files:" && gofmt -l . && exit 1)
test:
go test -v ./...
build:
CGO_ENABLED=0 go build -ldflags='-s -w' -o $(BINARY_NAME) ./cmd/tienda
build-amd64:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags='-s -w' -o $(BINARY_NAME)-amd64 ./cmd/tienda
build-arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags='-s -w' -o $(BINARY_NAME)-arm64 ./cmd/tienda
clean:
rm -f $(BINARY_NAME) $(BINARY_NAME)-amd64 $(BINARY_NAME)-arm64 ca-certificates.crt

75
cmd/tienda/main.go Normal file
View file

@ -0,0 +1,75 @@
package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
tienda "tienda-flores"
"tienda-flores/internal/fsclient"
"tienda-flores/internal/server"
)
func main() {
addr := flag.String("http-addr", envOrDefault("HTTP_ADDR", ":8080"), "HTTP listen address")
basePath := flag.String("base-path", envOrDefault("BASE_PATH", "/tienda"), "URL base path prefix")
fsURL := flag.String("fs-api-url", envOrDefault("FS_API_URL", "http://facturascripts.facturascripts.svc.cluster.local/api/3"), "FacturaScripts API v3 base URL")
fsToken := flag.String("fs-api-token", envOrDefault("FS_API_TOKEN", ""), "FacturaScripts API Token")
autoSeed := flag.Bool("auto-seed", envOrDefault("AUTO_SEED", "true") == "true", "Automatically seed initial flower catalog if FacturaScripts is empty")
flag.Parse()
client := fsclient.NewClient(*fsURL, *fsToken, 45*time.Second)
if *autoSeed && client.IsConfigured() {
go func() {
time.Sleep(2 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
_, prods, err := client.RefreshCatalog(ctx)
if err == nil && len(prods) == 0 {
n, seedErr := client.SeedInitialCatalog(ctx)
if seedErr == nil {
log.Printf("[tienda] catálogo inicial sembrado en FacturaScripts: %d productos florales", n)
}
}
}()
}
srv, err := server.NewServer(*basePath, client, tienda.EmbeddedTemplates)
if err != nil {
log.Fatalf("error iniciando servidor tienda-flores: %v", err)
}
httpServer := &http.Server{
Addr: *addr,
Handler: srv,
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
log.Printf("[tienda] Flora Atlántica escuchando en %s (ruta base: %s, ERP: %s)", *addr, *basePath, *fsURL)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("error en servidor HTTP: %v", err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = httpServer.Shutdown(ctx)
}
func envOrDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}

6
embed.go Normal file
View file

@ -0,0 +1,6 @@
package tienda
import "embed"
//go:embed all:templates
var EmbeddedTemplates embed.FS

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module tienda-flores
go 1.22

View file

@ -0,0 +1,200 @@
package fsclient
import "strings"
// DefaultBotanicalCatalog returns the initial families and ornamental flowers to seed into FacturaScripts.
func DefaultBotanicalCatalog() ([]Family, []Product) {
families := []Family{
{Code: "RAMOS", Description: "Ramos y Bouquets"},
{Code: "ORQUIDEAS", Description: "Orquídeas Ornamentales"},
{Code: "INTERIOR", Description: "Plantas de Interior"},
{Code: "CENTROS", Description: "Centros y Arreglos Florales"},
}
products := []Product{
{
ID: 1,
Reference: "FL-RAMO-ROSAS",
Name: "Bouquet Imperial de 12 Rosas Rojas y Eucalipto Cinerea",
Observations: "Ramo clásico artesanal de 12 rosas rojas de tallo largo seleccionadas en cultivo de altura, acompañadas de ramas aromáticas de eucalipto cinerea y envoltorio de lino botánico.",
PriceNet: 35.51,
PriceGross: 38.00,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 15,
FamilyCode: "RAMOS",
FamilyName: "Ramos y Bouquets",
ImageURL: "roses",
Badge: "Más vendido",
CareTips: "Cortar 2 cm los tallos en diagonal cada 48 h, cambiar el agua fresca y mantener alejado de corrientes o sol directo.",
},
{
ID: 2,
Reference: "FL-ORQ-PHAL",
Name: "Orquídea Phalaenopsis Blanca de Doble Vara en Maceta Cerámica",
Observations: "Ejemplar ornamental de Phalaenopsis grandiflora de doble vara florida con más de 14 botones y flores abiertas, presentada en cubremaceta de gres esmaltado artesanal.",
PriceNet: 30.37,
PriceGross: 32.50,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 12,
FamilyCode: "ORQUIDEAS",
FamilyName: "Orquídeas Ornamentales",
ImageURL: "orchid",
Badge: "Larga duración",
CareTips: "Luz abundante tamizada sin sol directo. Regar por inmersión durante 10 minutos cuando las raíces pasen de verde intenso a gris plateado.",
},
{
ID: 3,
Reference: "FL-RAMO-SILV",
Name: "Ramo Silvestre Provenzal de Lavanda, Paniculata y Olivo",
Observations: "Composición campestre de inspiración mediterránea con espigas de lavanda aromática, nube de paniculata blanca, manzanilla silvestre y brotes de olivo.",
PriceNet: 27.94,
PriceGross: 29.90,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 18,
FamilyCode: "RAMOS",
FamilyName: "Ramos y Bouquets",
ImageURL: "lavender",
Badge: "Aromático",
CareTips: "Apto tanto para agua fresca durante la primera semana como para secado natural colgado boca abajo en lugar ventilado.",
},
{
ID: 4,
Reference: "FL-MONSTERA",
Name: "Monstera Deliciosa (Costilla de Adán) Porte XL 70 cm",
Observations: "Planta ornamental tropical de hojas fenestradas de color verde esmeralda profundo. Cultivada en sustrato aireado con corteza de pino y perlita.",
PriceNet: 31.78,
PriceGross: 34.00,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 8,
FamilyCode: "INTERIOR",
FamilyName: "Plantas de Interior",
ImageURL: "monstera",
Badge: "Interior fácil",
CareTips: "Riego moderado dejando secar los primeros 4 cm de sustrato. Pulverizar las hojas con agua sin cal una vez por semana.",
},
{
ID: 5,
Reference: "FL-CENTRO-LIRIOS",
Name: "Centro Floral de Lilium Oriental Rosa, Astromelia y Ruscus",
Observations: "Centro de mesa elaborado sobre esponja floral biodegradable con lirios orientales perfumados, astromelias rosadas y follaje de ruscus italiano.",
PriceNet: 41.12,
PriceGross: 44.00,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 10,
FamilyCode: "CENTROS",
FamilyName: "Centros y Arreglos Florales",
ImageURL: "lily",
Badge: "Recién cortado",
CareTips: "Añadir medio vaso de agua fresca en el centro de la base cada dos días para mantener la esponja floral siempre húmeda.",
},
{
ID: 6,
Reference: "FL-PROTEA-TROP",
Name: "Arreglo Botánico Atlántida con Protea King y Ave del Paraíso",
Observations: "Arreglo arquitectónico de flora subtropical canaria y sudafricana protagonizado por Protea Cynaroides, Strelitzia reginae (Ave del Paraíso) y helecho cuero.",
PriceNet: 46.26,
PriceGross: 49.50,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 6,
FamilyCode: "CENTROS",
FamilyName: "Centros y Arreglos Florales",
ImageURL: "protea",
Badge: "Colección Canaria",
CareTips: "Flores de extraordinaria resistencia (hasta 3 semanas). Renovar el agua cada 3 días y retirar hojas sumergidas.",
},
{
ID: 7,
Reference: "FL-PEONIAS",
Name: "Bouquet Romántico de Peonías Sarah Bernhardt y Rosa Inglesa",
Observations: "Exquisito bouquet en tonos rosa empolvado y marfil con peonías dobles perfumadas, rosas de jardín tipo David Austin y ramas de pistacia.",
PriceNet: 42.99,
PriceGross: 46.00,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 9,
FamilyCode: "RAMOS",
FamilyName: "Ramos y Bouquets",
ImageURL: "peony",
Badge: "Edición Temporada",
CareTips: "Situar en el rincón más fresco del hogar; las peonías abren gradualmente sus pétalos durante los primeros 4 días.",
},
{
ID: 8,
Reference: "FL-SPATHI",
Name: "Spathiphyllum (Lirio de la Paz) en Cesto de Fibra Natural",
Observations: "Planta ornamental purificadora de aire con espatas blancas elegantes y follaje brillante, entregada en cesto trenzado a mano con forro impermeable.",
PriceNet: 22.90,
PriceGross: 24.50,
TaxCode: "IGIC7",
TaxRate: 7.0,
Stock: 14,
FamilyCode: "INTERIOR",
FamilyName: "Plantas de Interior",
ImageURL: "spathiphyllum",
Badge: "Purificadora",
CareTips: "Tolera zonas de media sombra. Mantener el sustrato ligeramente húmedo sin encharcar el fondo del cesto.",
},
}
return families, products
}
func parseBotanicalMetadata(ref, family, rawObs string) (obs, care, badge, imgKey string) {
obs = strings.TrimSpace(rawObs)
if idx := strings.Index(obs, "Cuidados:"); idx >= 0 {
care = strings.TrimSpace(obs[idx+len("Cuidados:"):])
obs = strings.TrimSpace(obs[:idx])
}
_, defaults := DefaultBotanicalCatalog()
for _, d := range defaults {
if strings.EqualFold(d.Reference, ref) {
if obs == "" {
obs = d.Observations
}
if care == "" {
care = d.CareTips
}
badge = d.Badge
imgKey = d.ImageURL
return obs, care, badge, imgKey
}
}
switch strings.ToUpper(strings.TrimSpace(family)) {
case "ORQUIDEAS":
imgKey = "orchid"
badge = "Orquídea Selecta"
if care == "" {
care = "Luz tamizada abundante y riego por inmersión cada 7-10 días."
}
case "INTERIOR":
imgKey = "monstera"
badge = "Planta Viva"
if care == "" {
care = "Riego moderado cuando seque la capa superficial del sustrato."
}
case "CENTROS":
imgKey = "lily"
badge = "Arreglo Artesanal"
if care == "" {
care = "Mantener la base hidratada con agua fresca cada 48 horas."
}
default:
imgKey = "roses"
badge = "Flor Fresca"
if care == "" {
care = "Cortar los tallos en diagonal y renovar el agua cada 2 días."
}
}
if obs == "" {
obs = "Ejemplar floral ornamental seleccionado y preparado artesanalmente en nuestro taller."
}
return obs, care, badge, imgKey
}

View file

@ -0,0 +1,687 @@
package fsclient
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// FlexFloat handles JSON numbers or strings returned by PHP PDO/FacturaScripts.
type FlexFloat float64
func (f *FlexFloat) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `" `)
if s == "" || s == "null" {
*f = 0
return nil
}
v, err := strconv.ParseFloat(s, 64)
if err != nil {
*f = 0
return nil
}
*f = FlexFloat(v)
return nil
}
// FlexInt handles JSON integers, floats, or strings returned by PHP PDO/FacturaScripts.
type FlexInt int
func (fi *FlexInt) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `" `)
if s == "" || s == "null" {
*fi = 0
return nil
}
if v, err := strconv.Atoi(s); err == nil {
*fi = FlexInt(v)
return nil
}
if vf, err := strconv.ParseFloat(s, 64); err == nil {
*fi = FlexInt(int(vf))
return nil
}
*fi = 0
return nil
}
// FlexBool handles JSON booleans, 0/1 numbers, or "true"/"1" strings.
type FlexBool bool
func (fb *FlexBool) UnmarshalJSON(b []byte) error {
s := strings.ToLower(strings.Trim(string(b), `" `))
switch s {
case "true", "1", "yes", "si", "sí":
*fb = true
default:
*fb = false
}
return nil
}
// Family represents a product category (Familia) in FacturaScripts.
type Family struct {
Code string `json:"codfamilia"`
Description string `json:"descripcion"`
}
// Product represents an ornamental flower/plant product from FacturaScripts.
type Product struct {
ID int `json:"idproducto"`
Reference string `json:"referencia"`
Name string `json:"descripcion"`
Observations string `json:"observaciones"`
PriceNet float64 `json:"precio"`
PriceGross float64 `json:"precio_iva"`
TaxCode string `json:"codimpuesto"`
TaxRate float64 `json:"iva"`
Stock int `json:"stockfis"`
FamilyCode string `json:"codfamilia"`
FamilyName string `json:"familia_nombre"`
ImageURL string `json:"imagen_url"`
Badge string `json:"badge"`
CareTips string `json:"cuidados"`
}
// CartItem represents an item in the customer's shopping cart.
type CartItem struct {
Product Product `json:"product"`
Quantity int `json:"quantity"`
}
// LineTotalGross returns the gross line total (with tax).
func (ci CartItem) LineTotalGross() float64 {
return ci.Product.PriceGross * float64(ci.Quantity)
}
// LineTotalNet returns the net line total (without tax).
func (ci CartItem) LineTotalNet() float64 {
return ci.Product.PriceNet * float64(ci.Quantity)
}
// CheckoutRequest holds customer and delivery data for creating an order in FacturaScripts.
type CheckoutRequest struct {
CustomerName string
CIFNIF string
Email string
Phone string
Address string
PostalCode string
City string
Province string
DeliveryDate string
Dedication string
Notes string
Items []CartItem
}
// OrderConfirmation holds the created FacturaScripts order details.
type OrderConfirmation struct {
OrderID int
OrderCode string
CustomerCode string
CustomerName string
TotalNet float64
TotalTax float64
ShippingCost float64
TotalGross float64
DeliveryDate string
Dedication string
Items []CartItem
CreatedAt time.Time
}
type fsRawProduct struct {
IDProducto FlexInt `json:"idproducto"`
Referencia string `json:"referencia"`
Descripcion string `json:"descripcion"`
Observaciones string `json:"observaciones"`
Precio FlexFloat `json:"precio"`
CodImpuesto string `json:"codimpuesto"`
StockFis FlexFloat `json:"stockfis"`
CodFamilia string `json:"codfamilia"`
SeVende FlexBool `json:"sevende"`
Bloqueado FlexBool `json:"bloqueado"`
Publico FlexBool `json:"publico"`
}
type fsRawImpuesto struct {
CodImpuesto string `json:"codimpuesto"`
IVA FlexFloat `json:"iva"`
}
type fsRawCliente struct {
CodCliente string `json:"codcliente"`
Nombre string `json:"nombre"`
RazonSocial string `json:"razonsocial"`
CIFNIF string `json:"cifnif"`
Email string `json:"email"`
}
// Client communicates with the FacturaScripts REST API v3 (/api/3/).
type Client struct {
baseURL string
apiToken string
httpClient *http.Client
cacheTTL time.Duration
mu sync.RWMutex
families []Family
products []Product
lastFetched time.Time
}
// NewClient creates a new FacturaScripts API v3 client.
func NewClient(baseURL, apiToken string, cacheTTL time.Duration) *Client {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if cacheTTL <= 0 {
cacheTTL = 45 * time.Second
}
return &Client{
baseURL: baseURL,
apiToken: strings.TrimSpace(apiToken),
httpClient: &http.Client{
Timeout: 12 * time.Second,
},
cacheTTL: cacheTTL,
}
}
// IsConfigured returns true if both URL and API token are configured.
func (c *Client) IsConfigured() bool {
return c.baseURL != "" && c.apiToken != ""
}
func (c *Client) doRequest(ctx context.Context, method, endpoint string, form url.Values) ([]byte, int, error) {
fullURL := c.baseURL + "/" + strings.TrimLeft(endpoint, "/")
var bodyReader io.Reader
if form != nil {
if method == http.MethodGet {
if strings.Contains(fullURL, "?") {
fullURL += "&" + form.Encode()
} else {
fullURL += "?" + form.Encode()
}
} else {
bodyReader = strings.NewReader(form.Encode())
}
}
req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
if err != nil {
return nil, 0, err
}
req.Header.Set("Token", c.apiToken)
req.Header.Set("Accept", "application/json")
if method != http.MethodGet && form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.StatusCode, err
}
return data, resp.StatusCode, nil
}
// InvalidateCache forces the next catalog read to fetch fresh data from FacturaScripts.
func (c *Client) InvalidateCache() {
c.mu.Lock()
c.lastFetched = time.Time{}
c.mu.Unlock()
}
// GetCatalog returns the list of families and products, refreshing from FacturaScripts when cache expires.
func (c *Client) GetCatalog(ctx context.Context) ([]Family, []Product, error) {
c.mu.RLock()
if !c.lastFetched.IsZero() && time.Since(c.lastFetched) < c.cacheTTL && len(c.products) > 0 {
fams := append([]Family(nil), c.families...)
prods := append([]Product(nil), c.products...)
c.mu.RUnlock()
return fams, prods, nil
}
c.mu.RUnlock()
return c.RefreshCatalog(ctx)
}
// RefreshCatalog fetches families, taxes, and products directly from FacturaScripts API v3.
func (c *Client) RefreshCatalog(ctx context.Context) ([]Family, []Product, error) {
if !c.IsConfigured() {
fams, prods := DefaultBotanicalCatalog()
return fams, prods, nil
}
// 1. Fetch families
famParams := url.Values{"limit": {"200"}}
famBytes, code, err := c.doRequest(ctx, http.MethodGet, "familias", famParams)
if err != nil || code >= 400 {
log.Printf("[fsclient] warning fetching familias (HTTP %d): %v", code, err)
c.mu.RLock()
if len(c.products) > 0 {
fams, prods := c.families, c.products
c.mu.RUnlock()
return fams, prods, fmt.Errorf("error consultando FacturaScripts (HTTP %d)", code)
}
c.mu.RUnlock()
fams, prods := DefaultBotanicalCatalog()
return fams, prods, fmt.Errorf("error consultando FacturaScripts: %v", err)
}
var rawFamilies []Family
_ = json.Unmarshal(famBytes, &rawFamilies)
familyMap := make(map[string]string, len(rawFamilies))
for _, f := range rawFamilies {
familyMap[f.Code] = f.Description
}
// 2. Fetch taxes (impuestos)
taxMap := map[string]float64{
"IVA21": 21.0,
"IVA10": 10.0,
"IVA4": 4.0,
"IVA0": 0.0,
"IGIC7": 7.0,
"IGIC3": 3.0,
"IGIC0": 0.0,
}
if taxBytes, taxCode, err := c.doRequest(ctx, http.MethodGet, "impuestos", url.Values{"limit": {"100"}}); err == nil && taxCode == http.StatusOK {
var rawTaxes []fsRawImpuesto
if json.Unmarshal(taxBytes, &rawTaxes) == nil {
for _, t := range rawTaxes {
taxMap[t.CodImpuesto] = float64(t.IVA)
}
}
}
// 3. Fetch products
prodBytes, prodCode, err := c.doRequest(ctx, http.MethodGet, "productos", url.Values{"limit": {"500"}})
if err != nil || prodCode >= 400 {
return nil, nil, fmt.Errorf("error obteniendo productos de FacturaScripts (HTTP %d): %v", prodCode, err)
}
var rawProds []fsRawProduct
if err := json.Unmarshal(prodBytes, &rawProds); err != nil {
return nil, nil, fmt.Errorf("error decodificando productos: %w", err)
}
var products []Product
usedFamilies := make(map[string]bool)
for _, rp := range rawProds {
if bool(rp.Bloqueado) || !bool(rp.SeVende) {
continue
}
taxRate, ok := taxMap[rp.CodImpuesto]
if !ok {
taxRate = 7.0 // IGIC general en Canarias (7%)
}
priceNet := float64(rp.Precio)
priceGross := roundCurrency(priceNet * (1.0 + taxRate/100.0))
famName := familyMap[rp.CodFamilia]
if famName == "" && rp.CodFamilia != "" {
famName = rp.CodFamilia
}
if rp.CodFamilia != "" {
usedFamilies[rp.CodFamilia] = true
}
obs, care, badge, imgURL := parseBotanicalMetadata(rp.Referencia, rp.CodFamilia, rp.Observaciones)
products = append(products, Product{
ID: int(rp.IDProducto),
Reference: rp.Referencia,
Name: rp.Descripcion,
Observations: obs,
PriceNet: priceNet,
PriceGross: priceGross,
TaxCode: rp.CodImpuesto,
TaxRate: taxRate,
Stock: int(rp.StockFis),
FamilyCode: rp.CodFamilia,
FamilyName: famName,
ImageURL: imgURL,
Badge: badge,
CareTips: care,
})
}
sort.Slice(products, func(i, j int) bool {
if products[i].FamilyCode != products[j].FamilyCode {
return products[i].FamilyCode < products[j].FamilyCode
}
return products[i].Reference < products[j].Reference
})
var activeFamilies []Family
for _, f := range rawFamilies {
if usedFamilies[f.Code] {
activeFamilies = append(activeFamilies, f)
}
}
sort.Slice(activeFamilies, func(i, j int) bool {
return activeFamilies[i].Description < activeFamilies[j].Description
})
c.mu.Lock()
c.families = activeFamilies
c.products = products
c.lastFetched = time.Now()
c.mu.Unlock()
return activeFamilies, products, nil
}
// SeedInitialCatalog creates the ornamental flower families and initial catalog in FacturaScripts if empty.
func (c *Client) SeedInitialCatalog(ctx context.Context) (int, error) {
if !c.IsConfigured() {
return 0, fmt.Errorf("FacturaScripts API no configurada")
}
fams, prods := DefaultBotanicalCatalog()
for _, f := range fams {
form := url.Values{
"codfamilia": {f.Code},
"descripcion": {f.Description},
}
_, _, _ = c.doRequest(ctx, http.MethodPost, "familias", form)
}
created := 0
for _, p := range prods {
obsFull := p.Observations
if p.CareTips != "" {
obsFull += "\nCuidados: " + p.CareTips
}
form := url.Values{
"referencia": {p.Reference},
"descripcion": {p.Name},
"observaciones": {obsFull},
"precio": {fmt.Sprintf("%.2f", p.PriceNet)},
"codimpuesto": {p.TaxCode},
"codfamilia": {p.FamilyCode},
"stockfis": {strconv.Itoa(p.Stock)},
"sevende": {"1"},
"secompra": {"1"},
"publico": {"1"},
"bloqueado": {"0"},
"nostock": {"0"},
}
_, code, err := c.doRequest(ctx, http.MethodPost, "productos", form)
if err == nil && (code == http.StatusOK || code == http.StatusCreated) {
created++
}
// Ensure initial stock in default warehouse (ALG) via stocks endpoint
stockForm := url.Values{
"referencia": {p.Reference},
"codalmacen": {"ALG"},
"cantidad": {strconv.Itoa(p.Stock)},
}
_, _, _ = c.doRequest(ctx, http.MethodPost, "stocks", stockForm)
}
c.InvalidateCache()
return created, nil
}
// CreateOrder registers or locates the customer in FacturaScripts and creates the sales order (PedidoCliente) and lines.
func (c *Client) CreateOrder(ctx context.Context, req CheckoutRequest) (*OrderConfirmation, error) {
if len(req.Items) == 0 {
return nil, fmt.Errorf("el carrito está vacío")
}
var totalNet, totalTax, totalGross float64
for _, it := range req.Items {
lineNet := it.LineTotalNet()
lineGross := it.LineTotalGross()
totalNet += lineNet
totalGross += lineGross
totalTax += (lineGross - lineNet)
}
totalNet = roundCurrency(totalNet)
totalTax = roundCurrency(totalTax)
totalGross = roundCurrency(totalGross)
shippingCost := 4.90
if totalGross >= 45.0 {
shippingCost = 0.0
}
grandTotal := roundCurrency(totalGross + shippingCost)
if !c.IsConfigured() {
return &OrderConfirmation{
OrderID: int(time.Now().Unix() % 10000),
OrderCode: fmt.Sprintf("PED-DEMO-%d", time.Now().Unix()%10000),
CustomerCode: "CLI-DEMO",
CustomerName: req.CustomerName,
TotalNet: totalNet,
TotalTax: totalTax,
ShippingCost: shippingCost,
TotalGross: grandTotal,
DeliveryDate: req.DeliveryDate,
Dedication: req.Dedication,
Items: req.Items,
CreatedAt: time.Now(),
}, nil
}
// 1. Find or create customer (Cliente) in FacturaScripts
codCliente, err := c.findOrCreateCustomer(ctx, req)
if err != nil {
return nil, fmt.Errorf("error registrando cliente en FacturaScripts: %w", err)
}
// 2. Build order notes (delivery date, dedication card, customer instructions)
var notesParts []string
notesParts = append(notesParts, "[Pedido Tienda Online Flores Ornamentales]")
if req.DeliveryDate != "" {
notesParts = append(notesParts, "Fecha entrega solicitada: "+req.DeliveryDate)
}
if req.Dedication != "" {
notesParts = append(notesParts, "Tarjeta dedicatoria: \""+req.Dedication+"\"")
}
if req.Notes != "" {
notesParts = append(notesParts, "Notas de entrega: "+req.Notes)
}
orderNotes := strings.Join(notesParts, " | ")
// 3. Create PedidoCliente header
pedForm := url.Values{
"codcliente": {codCliente},
"nombrecliente": {req.CustomerName},
"cifnif": {req.CIFNIF},
"direccion": {req.Address},
"codpostal": {req.PostalCode},
"ciudad": {req.City},
"provincia": {req.Province},
"codpais": {"ESP"},
"observaciones": {orderNotes},
}
pedBytes, pedCode, err := c.doRequest(ctx, http.MethodPost, "pedidoclientes", pedForm)
if err != nil || pedCode >= 400 {
return nil, fmt.Errorf("error creando pedido en FacturaScripts (HTTP %d): %s", pedCode, string(pedBytes))
}
idPedido, codigoPedido := extractOrderIDAndCode(pedBytes)
if idPedido == 0 {
return nil, fmt.Errorf("no se obtuvo idpedido de FacturaScripts: %s", string(pedBytes))
}
// 4. Create order lines (LineaPedidoCliente)
for _, item := range req.Items {
taxCode := item.Product.TaxCode
if taxCode == "" {
taxCode = "IGIC7"
}
lineForm := url.Values{
"idpedido": {strconv.Itoa(idPedido)},
"referencia": {item.Product.Reference},
"descripcion": {item.Product.Name},
"cantidad": {strconv.Itoa(item.Quantity)},
"pvpunitario": {fmt.Sprintf("%.2f", item.Product.PriceNet)},
"codimpuesto": {taxCode},
"iva": {fmt.Sprintf("%.2f", item.Product.TaxRate)},
}
_, _, _ = c.doRequest(ctx, http.MethodPost, "lineapedidoclientes", lineForm)
}
if shippingCost > 0 {
shipNet := roundCurrency(shippingCost / 1.07)
shipForm := url.Values{
"idpedido": {strconv.Itoa(idPedido)},
"descripcion": {"Transporte refrigerado y entrega floral a domicilio"},
"cantidad": {"1"},
"pvpunitario": {fmt.Sprintf("%.2f", shipNet)},
"codimpuesto": {"IGIC7"},
"iva": {"7.00"},
}
_, _, _ = c.doRequest(ctx, http.MethodPost, "lineapedidoclientes", shipForm)
totalNet = roundCurrency(totalNet + shipNet)
totalTax = roundCurrency(totalTax + (shippingCost - shipNet))
}
// 5. Update PedidoCliente header totals
updateForm := url.Values{
"neto": {fmt.Sprintf("%.2f", totalNet)},
"totaliva": {fmt.Sprintf("%.2f", totalTax)},
"total": {fmt.Sprintf("%.2f", grandTotal)},
}
_, _, _ = c.doRequest(ctx, http.MethodPut, fmt.Sprintf("pedidoclientes/%d", idPedido), updateForm)
c.InvalidateCache()
if codigoPedido == "" {
codigoPedido = fmt.Sprintf("PED-%d", idPedido)
}
return &OrderConfirmation{
OrderID: idPedido,
OrderCode: codigoPedido,
CustomerCode: codCliente,
CustomerName: req.CustomerName,
TotalNet: totalNet,
TotalTax: totalTax,
ShippingCost: shippingCost,
TotalGross: grandTotal,
DeliveryDate: req.DeliveryDate,
Dedication: req.Dedication,
Items: req.Items,
CreatedAt: time.Now(),
}, nil
}
func (c *Client) findOrCreateCustomer(ctx context.Context, req CheckoutRequest) (string, error) {
// Search existing customers
cliBytes, code, err := c.doRequest(ctx, http.MethodGet, "clientes", url.Values{"limit": {"200"}})
if err == nil && code == http.StatusOK {
var list []fsRawCliente
if json.Unmarshal(cliBytes, &list) == nil {
cleanNIF := strings.ToUpper(strings.TrimSpace(req.CIFNIF))
cleanMail := strings.ToLower(strings.TrimSpace(req.Email))
for _, cl := range list {
if cleanNIF != "" && strings.EqualFold(strings.TrimSpace(cl.CIFNIF), cleanNIF) {
return cl.CodCliente, nil
}
if cleanMail != "" && strings.EqualFold(strings.TrimSpace(cl.Email), cleanMail) {
return cl.CodCliente, nil
}
}
}
}
nif := strings.TrimSpace(req.CIFNIF)
if nif == "" {
nif = "00000000T"
}
cliForm := url.Values{
"nombre": {req.CustomerName},
"razonsocial": {req.CustomerName},
"cifnif": {nif},
"email": {req.Email},
"telefono1": {req.Phone},
"observaciones": {"Cliente registrado desde Tienda Online de Flores Ornamentales"},
}
respBytes, postCode, err := c.doRequest(ctx, http.MethodPost, "clientes", cliForm)
if err != nil || postCode >= 400 {
return "", fmt.Errorf("HTTP %d creando cliente: %s", postCode, string(respBytes))
}
codCliente := extractCustomerCode(respBytes)
if codCliente == "" {
return "", fmt.Errorf("respuesta sin codcliente: %s", string(respBytes))
}
// Register customer contact/address in FacturaScripts
contactForm := url.Values{
"codcliente": {codCliente},
"descripcion": {req.CustomerName},
"nombre": {req.CustomerName},
"email": {req.Email},
"telefono1": {req.Phone},
"direccion": {req.Address},
"codpostal": {req.PostalCode},
"ciudad": {req.City},
"provincia": {req.Province},
"codpais": {"ESP"},
}
_, _, _ = c.doRequest(ctx, http.MethodPost, "contactos", contactForm)
return codCliente, nil
}
func extractCustomerCode(b []byte) string {
var wrapper struct {
CodCliente string `json:"codcliente"`
Data struct {
CodCliente string `json:"codcliente"`
} `json:"data"`
}
if json.Unmarshal(b, &wrapper) == nil {
if wrapper.Data.CodCliente != "" {
return wrapper.Data.CodCliente
}
if wrapper.CodCliente != "" {
return wrapper.CodCliente
}
}
return ""
}
func extractOrderIDAndCode(b []byte) (int, string) {
var wrapper struct {
IDPedido FlexInt `json:"idpedido"`
Codigo string `json:"codigo"`
Data struct {
IDPedido FlexInt `json:"idpedido"`
Codigo string `json:"codigo"`
} `json:"data"`
}
if json.Unmarshal(b, &wrapper) == nil {
if wrapper.Data.IDPedido > 0 {
return int(wrapper.Data.IDPedido), wrapper.Data.Codigo
}
if wrapper.IDPedido > 0 {
return int(wrapper.IDPedido), wrapper.Codigo
}
}
return 0, ""
}
func roundCurrency(v float64) float64 {
return float64(int(v*100+0.5)) / 100.0
}

547
internal/server/handlers.go Normal file
View file

@ -0,0 +1,547 @@
package server
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"sort"
"strconv"
"strings"
"time"
"tienda-flores/internal/fsclient"
)
const cartCookieName = "tienda_flores_cart"
type CartView struct {
Items []fsclient.CartItem
TotalCount int
Subtotal float64
ShippingCost float64
TotalGross float64
FreeShipDiff float64
}
type Server struct {
basePath string
fsClient *fsclient.Client
tmpl *template.Template
mux *http.ServeMux
}
func NewServer(basePath string, fsClient *fsclient.Client, templatesFS fs.FS) (*Server, error) {
basePath = strings.TrimRight(strings.TrimSpace(basePath), "/")
funcMap := template.FuncMap{
"eur": func(v float64) string {
s := fmt.Sprintf("%.2f €", v)
return strings.Replace(s, ".", ",", 1)
},
"imgPath": func(bp, key string) string {
if strings.HasPrefix(key, "http://") || strings.HasPrefix(key, "https://") {
return key
}
return bp + "/img/" + key + ".svg"
},
"add": func(a, b int) int { return a + b },
"sub": func(a, b int) int { return a - b },
"dictCart": func(bp string, c CartView, oob bool) any {
return struct {
BasePath string
Cart CartView
OOB bool
}{
BasePath: bp,
Cart: c,
OOB: oob,
}
},
}
tmpl, err := template.New("").Funcs(funcMap).ParseFS(templatesFS, "templates/*.html")
if err != nil {
return nil, fmt.Errorf("parsing templates: %w", err)
}
s := &Server{
basePath: basePath,
fsClient: fsClient,
tmpl: tmpl,
mux: http.NewServeMux(),
}
s.registerRoutes()
return s, nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mux.ServeHTTP(w, r)
}
func (s *Server) registerRoutes() {
register := func(pattern string, handler http.HandlerFunc) {
s.mux.HandleFunc(pattern, handler)
if s.basePath != "" {
s.mux.HandleFunc(s.basePath+pattern, handler)
}
}
register("/", s.handleIndex)
register("/img/", s.handleIllustration)
register("/api/health", s.handleHealth)
register("/htmx/catalogo", s.handleHTMXCatalog)
register("/htmx/producto", s.handleHTMXProductModal)
register("/htmx/carrito", s.handleHTMXCartDrawer)
register("/htmx/carrito/add", s.handleHTMXCartAdd)
register("/htmx/carrito/update", s.handleHTMXCartUpdate)
register("/htmx/checkout-form", s.handleHTMXCheckoutForm)
register("/htmx/checkout", s.handleHTMXCheckoutSubmit)
register("/htmx/sync", s.handleHTMXSync)
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"status":"ok","service":"tienda-flores"}`))
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
families, products, syncErr := s.fsClient.GetCatalog(ctx)
cart := s.buildCartView(r, products)
data := struct {
BasePath string
Families []fsclient.Family
Products []fsclient.Product
SelectedFam string
Query string
OnlyInStock bool
Cart CartView
FSConnected bool
SyncWarning string
TomorrowDate string
}{
BasePath: s.basePath,
Families: families,
Products: products,
SelectedFam: "",
Query: "",
OnlyInStock: false,
Cart: cart,
FSConnected: s.fsClient.IsConfigured() && syncErr == nil,
TomorrowDate: time.Now().Add(24 * time.Hour).Format("2006-01-02"),
}
if syncErr != nil {
data.SyncWarning = syncErr.Error()
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := s.tmpl.ExecuteTemplate(w, "index.html", data); err != nil {
log.Printf("[tienda] template error: %v", err)
http.Error(w, "Error renderizando tienda", http.StatusInternalServerError)
}
}
func (s *Server) handleHTMXCatalog(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
fam := strings.TrimSpace(r.URL.Query().Get("familia"))
q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q")))
onlyStock := r.URL.Query().Get("stock") == "1" || r.URL.Query().Get("stock") == "on"
var filtered []fsclient.Product
for _, p := range products {
if fam != "" && !strings.EqualFold(p.FamilyCode, fam) {
continue
}
if onlyStock && p.Stock <= 0 {
continue
}
if q != "" {
match := strings.Contains(strings.ToLower(p.Name), q) ||
strings.Contains(strings.ToLower(p.Observations), q) ||
strings.Contains(strings.ToLower(p.Reference), q) ||
strings.Contains(strings.ToLower(p.FamilyName), q)
if !match {
continue
}
}
filtered = append(filtered, p)
}
data := struct {
BasePath string
Products []fsclient.Product
}{
BasePath: s.basePath,
Products: filtered,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "catalog_grid.html", data)
}
func (s *Server) handleHTMXProductModal(w http.ResponseWriter, r *http.Request) {
ref := strings.TrimSpace(r.URL.Query().Get("ref"))
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
var found *fsclient.Product
for i := range products {
if strings.EqualFold(products[i].Reference, ref) {
found = &products[i]
break
}
}
if found == nil {
http.Error(w, "Producto no encontrado", http.StatusNotFound)
return
}
data := struct {
BasePath string
Product fsclient.Product
}{
BasePath: s.basePath,
Product: *found,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "product_modal.html", data)
}
func (s *Server) handleHTMXCartDrawer(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
cart := s.buildCartView(r, products)
data := struct {
BasePath string
Cart CartView
OOB bool
}{
BasePath: s.basePath,
Cart: cart,
OOB: false,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "cart_drawer.html", data)
}
func (s *Server) handleHTMXCartAdd(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Método no permitido", http.StatusMethodNotAllowed)
return
}
_ = r.ParseForm()
ref := strings.TrimSpace(r.FormValue("ref"))
qty, _ := strconv.Atoi(r.FormValue("qty"))
if qty <= 0 {
qty = 1
}
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
cartMap := s.readCartCookie(r)
for _, p := range products {
if strings.EqualFold(p.Reference, ref) {
newQty := cartMap[p.Reference] + qty
if p.Stock > 0 && newQty > p.Stock {
newQty = p.Stock
}
if p.Stock > 0 {
cartMap[p.Reference] = newQty
}
break
}
}
s.writeCartCookie(w, cartMap)
cart := s.buildCartViewFromMap(cartMap, products)
data := struct {
BasePath string
Cart CartView
OOB bool
}{
BasePath: s.basePath,
Cart: cart,
OOB: true,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "cart_drawer.html", data)
}
func (s *Server) handleHTMXCartUpdate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Método no permitido", http.StatusMethodNotAllowed)
return
}
_ = r.ParseForm()
ref := strings.TrimSpace(r.FormValue("ref"))
delta, _ := strconv.Atoi(r.FormValue("delta"))
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
cartMap := s.readCartCookie(r)
if cur, exists := cartMap[ref]; exists {
next := cur + delta
if next <= 0 || delta == 0 {
delete(cartMap, ref)
} else {
for _, p := range products {
if strings.EqualFold(p.Reference, ref) && p.Stock > 0 && next > p.Stock {
next = p.Stock
}
}
cartMap[ref] = next
}
}
s.writeCartCookie(w, cartMap)
cart := s.buildCartViewFromMap(cartMap, products)
data := struct {
BasePath string
Cart CartView
OOB bool
}{
BasePath: s.basePath,
Cart: cart,
OOB: true,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "cart_drawer.html", data)
}
func (s *Server) handleHTMXCheckoutForm(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
cart := s.buildCartView(r, products)
data := struct {
BasePath string
Cart CartView
TomorrowDate string
ErrorMsg string
}{
BasePath: s.basePath,
Cart: cart,
TomorrowDate: time.Now().Add(24 * time.Hour).Format("2006-01-02"),
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "checkout_modal.html", data)
}
func (s *Server) handleHTMXCheckoutSubmit(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Método no permitido", http.StatusMethodNotAllowed)
return
}
_ = r.ParseForm()
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
_, products, _ := s.fsClient.GetCatalog(ctx)
cart := s.buildCartView(r, products)
if len(cart.Items) == 0 {
http.Error(w, "El carrito está vacío", http.StatusBadRequest)
return
}
req := fsclient.CheckoutRequest{
CustomerName: strings.TrimSpace(r.FormValue("nombre")),
CIFNIF: strings.TrimSpace(r.FormValue("cifnif")),
Email: strings.TrimSpace(r.FormValue("email")),
Phone: strings.TrimSpace(r.FormValue("telefono")),
Address: strings.TrimSpace(r.FormValue("direccion")),
PostalCode: strings.TrimSpace(r.FormValue("codpostal")),
City: strings.TrimSpace(r.FormValue("ciudad")),
Province: strings.TrimSpace(r.FormValue("provincia")),
DeliveryDate: strings.TrimSpace(r.FormValue("fecha_entrega")),
Dedication: strings.TrimSpace(r.FormValue("dedicatoria")),
Notes: strings.TrimSpace(r.FormValue("notas")),
Items: cart.Items,
}
if req.CustomerName == "" || req.Address == "" || req.Phone == "" {
data := struct {
BasePath string
Cart CartView
TomorrowDate string
ErrorMsg string
}{
BasePath: s.basePath,
Cart: cart,
TomorrowDate: time.Now().Add(24 * time.Hour).Format("2006-01-02"),
ErrorMsg: "Por favor, completa nombre, teléfono y dirección de entrega.",
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "checkout_modal.html", data)
return
}
conf, err := s.fsClient.CreateOrder(ctx, req)
if err != nil {
log.Printf("[tienda] error creando pedido en FacturaScripts: %v", err)
data := struct {
BasePath string
Cart CartView
TomorrowDate string
ErrorMsg string
}{
BasePath: s.basePath,
Cart: cart,
TomorrowDate: time.Now().Add(24 * time.Hour).Format("2006-01-02"),
ErrorMsg: "No se pudo registrar el pedido en FacturaScripts: " + err.Error(),
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "checkout_modal.html", data)
return
}
// Clear shopping cart cookie
s.writeCartCookie(w, map[string]int{})
data := struct {
BasePath string
Order *fsclient.OrderConfirmation
}{
BasePath: s.basePath,
Order: conf,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "order_success.html", data)
}
func (s *Server) handleHTMXSync(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
if r.URL.Query().Get("seed") == "1" {
_, _ = s.fsClient.SeedInitialCatalog(ctx)
}
s.fsClient.InvalidateCache()
_, products, _ := s.fsClient.RefreshCatalog(ctx)
if len(products) == 0 && s.fsClient.IsConfigured() {
_, _ = s.fsClient.SeedInitialCatalog(ctx)
_, products, _ = s.fsClient.RefreshCatalog(ctx)
}
data := struct {
BasePath string
Products []fsclient.Product
}{
BasePath: s.basePath,
Products: products,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = s.tmpl.ExecuteTemplate(w, "catalog_grid.html", data)
}
func (s *Server) readCartCookie(r *http.Request) map[string]int {
res := make(map[string]int)
c, err := r.Cookie(cartCookieName)
if err != nil || c.Value == "" {
return res
}
raw, err := base64.RawURLEncoding.DecodeString(c.Value)
if err != nil {
return res
}
_ = json.Unmarshal(raw, &res)
return res
}
func (s *Server) writeCartCookie(w http.ResponseWriter, cartMap map[string]int) {
b, _ := json.Marshal(cartMap)
val := base64.RawURLEncoding.EncodeToString(b)
path := s.basePath
if path == "" {
path = "/"
}
http.SetCookie(w, &http.Cookie{
Name: cartCookieName,
Value: val,
Path: path,
MaxAge: 86400 * 7,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
func (s *Server) buildCartView(r *http.Request, products []fsclient.Product) CartView {
return s.buildCartViewFromMap(s.readCartCookie(r), products)
}
func (s *Server) buildCartViewFromMap(cartMap map[string]int, products []fsclient.Product) CartView {
prodByRef := make(map[string]fsclient.Product, len(products))
for _, p := range products {
prodByRef[p.Reference] = p
}
var items []fsclient.CartItem
var totalCount int
var subtotal float64
var refs []string
for ref := range cartMap {
refs = append(refs, ref)
}
sort.Strings(refs)
for _, ref := range refs {
qty := cartMap[ref]
if qty <= 0 {
continue
}
p, ok := prodByRef[ref]
if !ok {
continue
}
if p.Stock > 0 && qty > p.Stock {
qty = p.Stock
}
ci := fsclient.CartItem{Product: p, Quantity: qty}
items = append(items, ci)
totalCount += qty
subtotal += ci.LineTotalGross()
}
shipping := 0.0
freeDiff := 0.0
if subtotal > 0 {
if subtotal < 45.0 {
shipping = 4.90
freeDiff = 45.0 - subtotal
}
}
return CartView{
Items: items,
TotalCount: totalCount,
Subtotal: subtotal,
ShippingCost: shipping,
TotalGross: subtotal + shipping,
FreeShipDiff: freeDiff,
}
}

View file

@ -0,0 +1,141 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
tienda "tienda-flores"
"tienda-flores/internal/fsclient"
)
func TestStorefrontAndFacturaScriptsIntegration(t *testing.T) {
var createdClient bool
var createdOrder bool
var createdLines int
mockFS := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Token") != "test-fs-token" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/familias"):
_ = json.NewEncoder(w).Encode([]map[string]any{
{"codfamilia": "RAMOS", "descripcion": "Ramos y Bouquets"},
{"codfamilia": "ORQUIDEAS", "descripcion": "Orquídeas Ornamentales"},
})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/impuestos"):
_ = json.NewEncoder(w).Encode([]map[string]any{
{"codimpuesto": "IVA10", "iva": 10.0},
})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/productos"):
_ = json.NewEncoder(w).Encode([]map[string]any{
{
"idproducto": 1,
"referencia": "FL-RAMO-ROSAS",
"descripcion": "Bouquet Imperial de 12 Rosas Rojas",
"observaciones": "Ramo artesanal de rosas rojas",
"precio": 34.55,
"codimpuesto": "IVA10",
"stockfis": 10,
"codfamilia": "RAMOS",
"sevende": true,
"bloqueado": false,
},
})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/clientes"):
_ = json.NewEncoder(w).Encode([]map[string]any{})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/clientes"):
createdClient = true
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": "Record updated correctly!",
"data": map[string]any{"codcliente": "000042"},
})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/contactos"):
_ = json.NewEncoder(w).Encode(map[string]any{"ok": "ok"})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/pedidoclientes"):
createdOrder = true
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": "Record updated correctly!",
"data": map[string]any{"idpedido": 105, "codigo": "PED2026A00105"},
})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/lineapedidoclientes"):
createdLines++
_ = json.NewEncoder(w).Encode(map[string]any{"ok": "ok"})
case r.Method == http.MethodPut && strings.Contains(r.URL.Path, "/pedidoclientes/105"):
_ = json.NewEncoder(w).Encode(map[string]any{"ok": "ok"})
default:
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{}`))
}
}))
defer mockFS.Close()
client := fsclient.NewClient(mockFS.URL+"/api/3", "test-fs-token", 10*time.Second)
srv, err := NewServer("/tienda", client, tienda.EmbeddedTemplates)
if err != nil {
t.Fatalf("NewServer failed: %v", err)
}
// 1. Verify main page renders products from FacturaScripts
req := httptest.NewRequest(http.MethodGet, "/tienda/", nil)
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200 on /tienda/, got %d", rec.Code)
}
if !strings.Contains(rec.Body.String(), "Bouquet Imperial de 12 Rosas Rojas") {
t.Fatalf("expected product name in storefront HTML")
}
// 2. Add 2 bouquets to cart
form := url.Values{"ref": {"FL-RAMO-ROSAS"}, "qty": {"2"}}
reqAdd := httptest.NewRequest(http.MethodPost, "/tienda/htmx/carrito/add", strings.NewReader(form.Encode()))
reqAdd.Header.Set("Content-Type", "application/x-www-form-urlencoded")
recAdd := httptest.NewRecorder()
srv.ServeHTTP(recAdd, reqAdd)
if recAdd.Code != http.StatusOK {
t.Fatalf("expected 200 on cart add, got %d", recAdd.Code)
}
cookies := recAdd.Result().Cookies()
if len(cookies) == 0 {
t.Fatalf("expected cart cookie to be set")
}
// 3. Submit checkout and verify FacturaScripts client + order creation
checkoutForm := url.Values{
"nombre": {"Elena Rodríguez"},
"cifnif": {"43123456A"},
"email": {"elena@example.com"},
"telefono": {"611223344"},
"direccion": {"Calle Herradores 24"},
"codpostal": {"38201"},
"ciudad": {"La Laguna"},
"provincia": {"Santa Cruz de Tenerife"},
"fecha_entrega": {"2026-11-15"},
"dedicatoria": {"¡Feliz aniversario!"},
}
reqChk := httptest.NewRequest(http.MethodPost, "/tienda/htmx/checkout", strings.NewReader(checkoutForm.Encode()))
reqChk.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for _, c := range cookies {
reqChk.AddCookie(c)
}
recChk := httptest.NewRecorder()
srv.ServeHTTP(recChk, reqChk)
if recChk.Code != http.StatusOK {
t.Fatalf("expected 200 on checkout, got %d: %s", recChk.Code, recChk.Body.String())
}
if !createdClient || !createdOrder || createdLines == 0 {
t.Fatalf("expected FacturaScripts API calls (client=%v, order=%v, lines=%d)", createdClient, createdOrder, createdLines)
}
if !strings.Contains(recChk.Body.String(), "PED2026A00105") {
t.Fatalf("expected FacturaScripts order code PED2026A00105 in confirmation response")
}
}

View file

@ -0,0 +1,176 @@
package server
import (
"net/http"
"strings"
)
func (s *Server) handleIllustration(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, s.basePath+"/img/"), ".svg")
key = strings.TrimPrefix(key, "/img/")
key = strings.TrimSuffix(key, ".svg")
w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8")
w.Header().Set("Cache-Control", "public, max-age=86400")
_, _ = w.Write([]byte(botanicalSVG(key)))
}
func botanicalSVG(key string) string {
switch strings.ToLower(strings.TrimSpace(key)) {
case "orchid":
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 320">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#f7f4ef"/>
<stop offset="100%" stop-color="#e8efe9"/>
</linearGradient>
</defs>
<rect width="400" height="320" fill="url(#bg)"/>
<circle cx="200" cy="145" r="105" fill="#dfeae2" opacity="0.65"/>
<!-- Maceta cerámica -->
<path d="M150 235 L250 235 L236 295 Q200 302 164 295 Z" fill="#d6cab8" stroke="#b5a58e" stroke-width="2"/>
<ellipse cx="200" cy="235" rx="50" ry="8" fill="#c2b39c"/>
<!-- Hojas basales -->
<path d="M195 235 Q130 215 115 245 Q150 260 198 238 Z" fill="#3a6b4c"/>
<path d="M205 235 Q270 215 285 245 Q250 260 202 238 Z" fill="#2e593e"/>
<!-- Varas arqueadas -->
<path d="M196 233 Q175 130 145 75" fill="none" stroke="#4a7c59" stroke-width="4" stroke-linecap="round"/>
<path d="M204 233 Q225 130 255 80" fill="none" stroke="#3d694b" stroke-width="4" stroke-linecap="round"/>
<!-- Flores Phalaenopsis -->
<g transform="translate(150,82)">
<ellipse cx="0" cy="-18" rx="16" ry="22" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="-22" cy="2" rx="22" ry="16" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="22" cy="2" rx="22" ry="16" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="-12" cy="20" rx="13" ry="17" fill="#fdfbf7" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="12" cy="20" rx="13" ry="17" fill="#fdfbf7" stroke="#e5dfd5" stroke-width="1.5"/>
<circle cx="0" cy="5" r="9" fill="#d97b93"/>
<circle cx="0" cy="3" r="4" fill="#f2c94c"/>
</g>
<g transform="translate(178,132) scale(0.88)">
<ellipse cx="0" cy="-18" rx="16" ry="22" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="-22" cy="2" rx="22" ry="16" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="22" cy="2" rx="22" ry="16" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<circle cx="0" cy="5" r="9" fill="#d97b93"/>
<circle cx="0" cy="3" r="4" fill="#f2c94c"/>
</g>
<g transform="translate(248,90) scale(0.92)">
<ellipse cx="0" cy="-18" rx="16" ry="22" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="-22" cy="2" rx="22" ry="16" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<ellipse cx="22" cy="2" rx="22" ry="16" fill="#ffffff" stroke="#e5dfd5" stroke-width="1.5"/>
<circle cx="0" cy="5" r="9" fill="#d97b93"/>
<circle cx="0" cy="3" r="4" fill="#f2c94c"/>
</g>
</svg>`
case "lavender":
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 320">
<rect width="400" height="320" fill="#f6f3fb"/>
<circle cx="200" cy="150" r="108" fill="#eae2f6" opacity="0.7"/>
<!-- Tallos -->
<g stroke="#5c8067" stroke-width="3" stroke-linecap="round">
<line x1="200" y1="265" x2="145" y2="75"/>
<line x1="200" y1="265" x2="172" y2="62"/>
<line x1="200" y1="265" x2="200" y2="55"/>
<line x1="200" y1="265" x2="228" y2="64"/>
<line x1="200" y1="265" x2="255" y2="78"/>
</g>
<!-- Espigas de lavanda -->
<g fill="#7e57c2">
<ellipse cx="145" cy="78" rx="6" ry="10"/><ellipse cx="151" cy="94" rx="7" ry="10"/><ellipse cx="157" cy="110" rx="6" ry="9"/>
<ellipse cx="172" cy="65" rx="7" ry="11"/><ellipse cx="176" cy="82" rx="7" ry="10"/><ellipse cx="180" cy="99" rx="6" ry="9"/>
<ellipse cx="200" cy="58" rx="7" ry="12"/><ellipse cx="200" cy="76" rx="8" ry="11"/><ellipse cx="200" cy="94" rx="7" ry="10"/>
<ellipse cx="228" cy="67" rx="7" ry="11"/><ellipse cx="224" cy="84" rx="7" ry="10"/><ellipse cx="220" cy="101" rx="6" ry="9"/>
<ellipse cx="255" cy="80" rx="6" ry="10"/><ellipse cx="249" cy="96" rx="7" ry="10"/><ellipse cx="243" cy="112" rx="6" ry="9"/>
</g>
<!-- Paniculata blanca -->
<g fill="#ffffff" stroke="#d5cce6" stroke-width="1">
<circle cx="132" cy="115" r="5"/><circle cx="163" cy="128" r="6"/><circle cx="188" cy="118" r="5"/>
<circle cx="215" cy="122" r="6"/><circle cx="238" cy="130" r="5"/><circle cx="266" cy="116" r="5"/>
</g>
<!-- Envoltorio kraft y lazo -->
<polygon points="150,185 250,185 222,285 178,285" fill="#d9c2a3" stroke="#b89b74" stroke-width="2"/>
<rect x="174" y="225" width="52" height="12" rx="6" fill="#7e57c2"/>
</svg>`
case "monstera", "spathiphyllum":
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 320">
<rect width="400" height="320" fill="#eef5f0"/>
<circle cx="200" cy="150" r="108" fill="#d8eadc" opacity="0.75"/>
<!-- Cesto / Maceta terracota -->
<path d="M152 225 L248 225 L234 295 L166 295 Z" fill="#c97d60" stroke="#a65e44" stroke-width="2"/>
<rect x="146" y="215" width="108" height="14" rx="5" fill="#d4896c"/>
<!-- Hojas Monstera / Interior -->
<path d="M200 220 Q150 150 120 95 Q155 75 185 115 Q195 150 200 220 Z" fill="#2d6a4f"/>
<path d="M200 220 Q255 150 280 95 Q245 75 215 115 Q205 150 200 220 Z" fill="#1b4332"/>
<path d="M200 220 Q200 130 200 62 Q238 82 225 145 Q212 185 200 220 Z" fill="#40916c"/>
<path d="M200 220 Q162 130 198 62 Q165 88 175 145 Z" fill="#52b788"/>
<!-- Fenestraciones decorativas -->
<ellipse cx="152" cy="118" rx="9" ry="4" transform="rotate(-25 152 118)" fill="#d8eadc"/>
<ellipse cx="248" cy="118" rx="9" ry="4" transform="rotate(25 248 118)" fill="#d8eadc"/>
<ellipse cx="200" cy="105" rx="10" ry="4" fill="#d8eadc"/>
</svg>`
case "lily", "protea", "peony":
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 320">
<rect width="400" height="320" fill="#fbf3f4"/>
<circle cx="200" cy="150" r="108" fill="#f5dde0" opacity="0.7"/>
<!-- Base cerámica baja de centro floral -->
<path d="M125 235 L275 235 L255 282 L145 282 Z" fill="#7f9183"/>
<!-- Follaje ruscus / helecho -->
<path d="M135 230 Q95 175 110 125 Q155 155 170 230 Z" fill="#4a7c59"/>
<path d="M265 230 Q305 175 290 125 Q245 155 230 230 Z" fill="#3b6647"/>
<!-- Flores principales -->
<g transform="translate(160,145)">
<circle cx="0" cy="0" r="34" fill="#e57399"/>
<circle cx="-6" cy="-5" r="24" fill="#f09bb5"/>
<circle cx="4" cy="3" r="14" fill="#fbd0de"/>
<circle cx="0" cy="0" r="5" fill="#f6c453"/>
</g>
<g transform="translate(232,140)">
<circle cx="0" cy="0" r="36" fill="#d95b82"/>
<circle cx="5" cy="-4" r="25" fill="#ec8eab"/>
<circle cx="-3" cy="3" r="15" fill="#f9c6d7"/>
<circle cx="0" cy="0" r="6" fill="#f6c453"/>
</g>
<g transform="translate(198,98)">
<circle cx="0" cy="0" r="30" fill="#eb82a4"/>
<circle cx="0" cy="0" r="20" fill="#f7b7cc"/>
<circle cx="0" cy="0" r="9" fill="#fde4ec"/>
</g>
</svg>`
default:
// Bouquet de rosas rojas y eucalipto
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 320">
<rect width="400" height="320" fill="#faf5f2"/>
<circle cx="200" cy="148" r="108" fill="#f2e2dc" opacity="0.7"/>
<!-- Hojas de eucalipto -->
<g fill="#5f8d75">
<ellipse cx="132" cy="115" rx="18" ry="11" transform="rotate(-35 132 115)"/>
<ellipse cx="268" cy="115" rx="18" ry="11" transform="rotate(35 268 115)"/>
<ellipse cx="145" cy="160" rx="16" ry="10" transform="rotate(-20 145 160)"/>
<ellipse cx="255" cy="160" rx="16" ry="10" transform="rotate(20 255 160)"/>
</g>
<!-- Envoltorio de lino botánico -->
<polygon points="142,175 258,175 225,288 175,288" fill="#e6d7c3" stroke="#c8b296" stroke-width="2"/>
<rect x="172" y="226" width="56" height="12" rx="6" fill="#9e2a2b"/>
<!-- Rosas rojas -->
<g transform="translate(168,125)">
<circle cx="0" cy="0" r="28" fill="#9e2a2b"/>
<circle cx="-3" cy="-3" r="19" fill="#b83336"/>
<circle cx="2" cy="2" r="10" fill="#d64548"/>
</g>
<g transform="translate(228,125)">
<circle cx="0" cy="0" r="28" fill="#8c1d20"/>
<circle cx="3" cy="-3" r="19" fill="#ad282c"/>
<circle cx="-2" cy="2" r="10" fill="#cf3e42"/>
</g>
<g transform="translate(198,86)">
<circle cx="0" cy="0" r="26" fill="#a82428"/>
<circle cx="0" cy="-2" r="17" fill="#c9363a"/>
<circle cx="0" cy="0" r="8" fill="#e05357"/>
</g>
<g transform="translate(198,152)">
<circle cx="0" cy="0" r="25" fill="#941f23"/>
<circle cx="0" cy="0" r="16" fill="#b52d31"/>
<circle cx="0" cy="0" r="8" fill="#d9484c"/>
</g>
</svg>`
}
}

View file

@ -0,0 +1,82 @@
{{if .OOB}}
<span id="header-cart-badge" class="cart-badge" hx-swap-oob="true">{{.Cart.TotalCount}}</span>
{{end}}
<div class="drawer-header">
<div>
<h3 style="font-family:Georgia, serif; color:var(--primary-green);">Tu Cesta Floral</h3>
<span style="font-size:0.78rem; color:var(--text-muted);">{{.Cart.TotalCount}} artículos seleccionados</span>
</div>
<button type="button" class="btn-close" onclick="closeCartDrawer()">✕</button>
</div>
<div class="drawer-body">
{{if .Cart.Items}}
{{if gt .Cart.FreeShipDiff 0.0}}
<div style="background:#fef3c7; color:#92400e; padding:0.6rem 0.85rem; border-radius:8px; font-size:0.8rem; margin-bottom:0.85rem;">
Añade <strong>{{eur .Cart.FreeShipDiff}}</strong> más para disfrutar de <strong>envío refrigerado gratuito</strong>.
</div>
{{else}}
<div style="background:#d1fae5; color:#065f46; padding:0.6rem 0.85rem; border-radius:8px; font-size:0.8rem; margin-bottom:0.85rem;">
✓ Tu pedido incluye <strong>envío refrigerado gratuito</strong>.
</div>
{{end}}
{{range .Cart.Items}}
<div class="cart-item">
<div style="flex:1;">
<div style="font-weight:700; font-size:0.9rem; color:var(--text-dark);">{{.Product.Name}}</div>
<div style="font-size:0.76rem; color:var(--text-muted);">Ref: {{.Product.Reference}} · {{eur .Product.PriceGross}} / ud.</div>
</div>
<div class="qty-controls">
<button type="button" class="qty-btn"
hx-post="{{$.BasePath}}/htmx/carrito/update"
hx-vals='{"ref":"{{.Product.Reference}}","delta":"-1"}'
hx-target="#cart-drawer"
hx-swap="innerHTML">−</button>
<span style="min-width:22px; text-align:center; font-weight:700; font-size:0.88rem;">{{.Quantity}}</span>
<button type="button" class="qty-btn"
hx-post="{{$.BasePath}}/htmx/carrito/update"
hx-vals='{"ref":"{{.Product.Reference}}","delta":"1"}'
hx-target="#cart-drawer"
hx-swap="innerHTML">+</button>
</div>
<div style="font-weight:700; font-size:0.92rem; color:var(--primary-green); min-width:68px; text-align:right;">
{{eur .LineTotalGross}}
</div>
</div>
{{end}}
{{else}}
<div style="text-align:center; padding:3rem 1rem; color:var(--text-muted);">
<div style="font-size:2.4rem; margin-bottom:0.5rem;">✿</div>
<p>Tu cesta floral está vacía.</p>
<p style="font-size:0.82rem; margin-top:0.35rem;">Elige tus ramos, orquídeas o plantas ornamentales favoritas del catálogo.</p>
</div>
{{end}}
</div>
<div class="drawer-footer">
{{if .Cart.Items}}
<div style="display:flex; justify-content:space-between; font-size:0.86rem; color:var(--text-muted); margin-bottom:0.3rem;">
<span>Subtotal flores (imp. incl.)</span>
<span>{{eur .Cart.Subtotal}}</span>
</div>
<div style="display:flex; justify-content:space-between; font-size:0.86rem; color:var(--text-muted); margin-bottom:0.6rem;">
<span>Transporte refrigerado</span>
<span>{{if eq .Cart.ShippingCost 0.0}}Gratis{{else}}{{eur .Cart.ShippingCost}}{{end}}</span>
</div>
<div style="display:flex; justify-content:space-between; font-size:1.1rem; font-weight:800; color:var(--primary-green); margin-bottom:1rem; padding-top:0.5rem; border-top:1px solid var(--border-soft);">
<span>Total Pedido</span>
<span>{{eur .Cart.TotalGross}}</span>
</div>
<button type="button" class="btn-add" style="width:100%; padding:0.75rem; font-size:0.95rem;"
hx-get="{{.BasePath}}/htmx/checkout-form"
hx-target="#modal-content"
hx-on::after-request="closeCartDrawer(); openModal();">
Tramitar pedido y registrar en FacturaScripts →
</button>
{{end}}
</div>

View file

@ -0,0 +1,62 @@
{{if .Products}}
<div class="catalog-grid">
{{range .Products}}
<article class="product-card">
<div class="card-img-wrap"
hx-get="{{$.BasePath}}/htmx/producto?ref={{.Reference}}"
hx-target="#modal-content"
hx-on::after-request="openModal()">
<img src="{{imgPath $.BasePath .ImageURL}}" alt="{{.Name}}" loading="lazy">
{{if .Badge}}
<span class="card-badge">{{.Badge}}</span>
{{end}}
{{if gt .Stock 0}}
<span class="stock-pill">{{.Stock}} disp.</span>
{{else}}
<span class="stock-pill out">Agotado</span>
{{end}}
</div>
<div class="card-body">
<div class="card-family">{{if .FamilyName}}{{.FamilyName}}{{else}}Colección Botánica{{end}} · Ref: {{.Reference}}</div>
<h2 class="card-title"
hx-get="{{$.BasePath}}/htmx/producto?ref={{.Reference}}"
hx-target="#modal-content"
hx-on::after-request="openModal()">
{{.Name}}
</h2>
<p class="card-desc">{{.Observations}}</p>
<div class="card-footer">
<div class="price-block">
<span class="price-gross">{{eur .PriceGross}}</span>
<span class="price-tax">Base: {{eur .PriceNet}} (+{{.TaxRate}}% imp.)</span>
</div>
<form hx-post="{{$.BasePath}}/htmx/carrito/add"
hx-target="#cart-drawer"
hx-swap="innerHTML"
hx-on::after-request="openCartDrawer()">
<input type="hidden" name="ref" value="{{.Reference}}">
<input type="hidden" name="qty" value="1">
<button type="submit" class="btn-add" {{if le .Stock 0}}disabled{{end}}>
{{if gt .Stock 0}}+ Añadir{{else}}Sin stock{{end}}
</button>
</form>
</div>
</div>
</article>
{{end}}
</div>
{{else}}
<div style="text-align:center; padding:3rem 1rem; background:#fff; border-radius:14px; border:1px solid var(--border-soft);">
<h3 style="margin-bottom:0.5rem; color:var(--primary-green);">No se encontraron flores con ese filtro</h3>
<p style="color:var(--text-muted); margin-bottom:1rem;">Prueba otra categoría o sincroniza el catálogo inicial con FacturaScripts.</p>
<button class="btn-add"
hx-post="{{.BasePath}}/htmx/sync?seed=1"
hx-target="#catalog-container"
hx-swap="innerHTML">
Cargar catálogo floral en FacturaScripts
</button>
</div>
{{end}}

View file

@ -0,0 +1,75 @@
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.85rem;">
<div>
<span style="font-size:0.75rem; font-weight:700; text-transform:uppercase; color:var(--accent-terracotta);">Finalizar Compra · Integración Directa ERP</span>
<h2 style="font-family:Georgia, serif; font-size:1.35rem; color:var(--primary-green);">Datos de Entrega y Facturación</h2>
</div>
<button type="button" class="btn-close" onclick="closeModal()">✕</button>
</div>
{{if .ErrorMsg}}
<div style="background:#fee2e2; color:#991b1b; padding:0.75rem 1rem; border-radius:8px; font-size:0.86rem; margin-bottom:0.85rem;">
{{.ErrorMsg}}
</div>
{{end}}
<form hx-post="{{.BasePath}}/htmx/checkout"
hx-target="#modal-content"
hx-swap="innerHTML">
<div class="form-grid">
<div>
<label class="form-label">Nombre completo o Razón Social *</label>
<input type="text" name="nombre" class="form-input" required placeholder="Ej. María González Pérez">
</div>
<div>
<label class="form-label">DNI / NIF / CIF (para factura) *</label>
<input type="text" name="cifnif" class="form-input" required placeholder="Ej. 43812345Z">
</div>
<div>
<label class="form-label">Correo electrónico *</label>
<input type="email" name="email" class="form-input" required placeholder="cliente@ejemplo.es">
</div>
<div>
<label class="form-label">Teléfono de contacto (entrega) *</label>
<input type="tel" name="telefono" class="form-input" required placeholder="Ej. 600 123 456">
</div>
<div class="form-full">
<label class="form-label">Dirección de entrega *</label>
<input type="text" name="direccion" class="form-input" required placeholder="Calle, número, piso, puerta">
</div>
<div>
<label class="form-label">Código Postal *</label>
<input type="text" name="codpostal" class="form-input" required value="38201">
</div>
<div>
<label class="form-label">Municipio / Ciudad *</label>
<input type="text" name="ciudad" class="form-input" required value="San Cristóbal de La Laguna">
</div>
<div>
<label class="form-label">Provincia *</label>
<input type="text" name="provincia" class="form-input" required value="Santa Cruz de Tenerife">
</div>
<div>
<label class="form-label">Fecha de entrega preferida</label>
<input type="date" name="fecha_entrega" class="form-input" value="{{.TomorrowDate}}">
</div>
<div class="form-full">
<label class="form-label">Dedicatoria para la tarjeta floral (opcional)</label>
<input type="text" name="dedicatoria" class="form-input" placeholder="Escribe aquí tu mensaje para acompañar las flores...">
</div>
<div class="form-full">
<label class="form-label">Observaciones de reparto (horario preferente, timbre, etc.)</label>
<input type="text" name="notas" class="form-input" placeholder="Ej. Entregar en horario de mañana">
</div>
</div>
<div style="background:var(--bg-sage-soft); padding:0.9rem 1.1rem; border-radius:10px; margin-top:1.1rem; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:0.75rem;">
<div>
<div style="font-size:0.8rem; color:var(--text-muted);">Importe total ({{.Cart.TotalCount}} uds. + envío)</div>
<div style="font-size:1.3rem; font-weight:800; color:var(--primary-green);">{{eur .Cart.TotalGross}}</div>
</div>
<button type="submit" class="btn-add" style="padding:0.75rem 1.4rem; font-size:0.95rem;">
Confirmar Pedido Floral ✓
</button>
</div>
</form>

675
templates/index.html Normal file
View file

@ -0,0 +1,675 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flora Atlántica — Flores Ornamentales & Taller Botánico</title>
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
<style>
:root {
--bg-cream: #faf7f2;
--bg-card: #ffffff;
--bg-sage-soft: #eef4f0;
--primary-green: #2c5540;
--primary-green-hover: #1e3d2d;
--accent-terracotta: #c46d53;
--text-dark: #1f2a24;
--text-muted: #5c6b62;
--border-soft: #e3ded6;
--shadow-sm: 0 4px 16px rgba(31, 42, 36, 0.06);
--shadow-md: 0 12px 32px rgba(31, 42, 36, 0.12);
--radius-md: 14px;
--radius-lg: 20px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
background-color: var(--bg-cream);
color: var(--text-dark);
line-height: 1.55;
min-height: 100vh;
display: flex;
flex-direction: column;
}
/* Top Bar */
.topbar {
background: var(--primary-green);
color: #f3f7f4;
font-size: 0.82rem;
padding: 0.45rem 1.25rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
}
.topbar-status {
display: inline-flex;
align-items: center;
gap: 0.45rem;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #6ee7b7;
display: inline-block;
}
.topbar a {
color: #d1fae5;
text-decoration: none;
font-weight: 500;
}
.topbar a:hover { text-decoration: underline; }
/* Header */
header {
position: sticky;
top: 0;
z-index: 40;
background: rgba(250, 247, 242, 0.94);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--border-soft);
padding: 0.9rem 1.5rem;
}
.header-inner {
max-width: 1240px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.brand {
display: flex;
align-items: center;
gap: 0.75rem;
text-decoration: none;
color: var(--text-dark);
}
.brand-icon {
width: 42px;
height: 42px;
border-radius: 12px;
background: var(--primary-green);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.35rem;
}
.brand-title {
font-family: Georgia, 'Times New Roman', serif;
font-size: 1.35rem;
font-weight: 700;
letter-spacing: -0.02em;
color: var(--primary-green);
}
.brand-sub {
font-size: 0.75rem;
color: var(--text-muted);
display: block;
}
.header-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
.btn-sync {
background: var(--bg-sage-soft);
color: var(--primary-green);
border: 1px solid #cce0d3;
padding: 0.55rem 0.9rem;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-sync:hover { background: #dcebe1; }
.btn-cart {
background: var(--primary-green);
color: #fff;
border: none;
padding: 0.6rem 1.15rem;
border-radius: 999px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 0.5rem;
box-shadow: var(--shadow-sm);
transition: background 0.2s, transform 0.15s;
}
.btn-cart:hover {
background: var(--primary-green-hover);
transform: translateY(-1px);
}
.cart-badge {
background: var(--accent-terracotta);
color: #fff;
border-radius: 999px;
padding: 0.1rem 0.5rem;
font-size: 0.78rem;
font-weight: 700;
}
/* Hero Banner */
.hero {
max-width: 1240px;
margin: 1.5rem auto 1rem;
padding: 0 1.5rem;
}
.hero-box {
background: linear-gradient(125deg, #214332 0%, #35634b 60%, #4b7d62 100%);
color: #fff;
border-radius: var(--radius-lg);
padding: 2.2rem 2.5rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 2rem;
box-shadow: var(--shadow-md);
flex-wrap: wrap;
}
.hero-content { max-width: 640px; }
.hero-tag {
display: inline-block;
background: rgba(255, 255, 255, 0.16);
padding: 0.25rem 0.75rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 600;
margin-bottom: 0.75rem;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.hero h1 {
font-family: Georgia, 'Times New Roman', serif;
font-size: clamp(1.6rem, 3vw, 2.35rem);
line-height: 1.2;
margin-bottom: 0.65rem;
}
.hero p {
color: #e2efe7;
font-size: 0.98rem;
}
.hero-highlights {
display: flex;
gap: 1.25rem;
margin-top: 1.15rem;
flex-wrap: wrap;
font-size: 0.85rem;
color: #d1fae5;
}
/* Filter Toolbar */
.toolbar {
max-width: 1240px;
margin: 0.75rem auto 1.25rem;
padding: 0 1.5rem;
}
.filter-bar {
background: var(--bg-card);
border: 1px solid var(--border-soft);
border-radius: var(--radius-md);
padding: 0.9rem 1.15rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
box-shadow: var(--shadow-sm);
}
.family-pills {
display: flex;
gap: 0.45rem;
flex-wrap: wrap;
}
.pill {
background: var(--bg-cream);
border: 1px solid var(--border-soft);
color: var(--text-dark);
padding: 0.42rem 0.9rem;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
transition: all 0.15s;
}
.pill:hover, .pill.active {
background: var(--primary-green);
color: #fff;
border-color: var(--primary-green);
}
.search-group {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.search-input {
padding: 0.48rem 0.9rem;
border: 1px solid var(--border-soft);
border-radius: 999px;
font-size: 0.88rem;
min-width: 220px;
background: var(--bg-cream);
}
.stock-toggle {
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-size: 0.84rem;
color: var(--text-muted);
cursor: pointer;
}
/* Product Grid */
main {
max-width: 1240px;
width: 100%;
margin: 0 auto 3rem;
padding: 0 1.5rem;
flex: 1;
}
.catalog-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(275px, 1fr));
gap: 1.35rem;
}
.product-card {
background: var(--bg-card);
border: 1px solid var(--border-soft);
border-radius: var(--radius-md);
overflow: hidden;
display: flex;
flex-direction: column;
box-shadow: var(--shadow-sm);
transition: transform 0.2s, box-shadow 0.2s;
}
.product-card:hover {
transform: translateY(-3px);
box-shadow: var(--shadow-md);
}
.card-img-wrap {
position: relative;
height: 210px;
background: var(--bg-sage-soft);
cursor: pointer;
overflow: hidden;
}
.card-img-wrap img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.card-badge {
position: absolute;
top: 10px;
left: 10px;
background: rgba(44, 85, 64, 0.9);
color: #fff;
padding: 0.2rem 0.65rem;
border-radius: 999px;
font-size: 0.73rem;
font-weight: 600;
}
.stock-pill {
position: absolute;
bottom: 10px;
right: 10px;
background: rgba(255, 255, 255, 0.92);
color: var(--primary-green);
padding: 0.18rem 0.6rem;
border-radius: 999px;
font-size: 0.74rem;
font-weight: 700;
}
.stock-pill.out {
color: #b91c1c;
background: #fee2e2;
}
.card-body {
padding: 1.1rem;
display: flex;
flex-direction: column;
flex: 1;
}
.card-family {
font-size: 0.73rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--accent-terracotta);
font-weight: 700;
margin-bottom: 0.25rem;
}
.card-title {
font-family: Georgia, 'Times New Roman', serif;
font-size: 1.05rem;
font-weight: 700;
color: var(--text-dark);
margin-bottom: 0.45rem;
cursor: pointer;
}
.card-desc {
font-size: 0.84rem;
color: var(--text-muted);
margin-bottom: 1rem;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
flex: 1;
}
.card-footer {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 0.75rem;
border-top: 1px solid var(--border-soft);
gap: 0.5rem;
}
.price-block {
display: flex;
flex-direction: column;
}
.price-gross {
font-size: 1.18rem;
font-weight: 800;
color: var(--primary-green);
}
.price-tax {
font-size: 0.7rem;
color: var(--text-muted);
}
.btn-add {
background: var(--primary-green);
color: #fff;
border: none;
padding: 0.52rem 0.95rem;
border-radius: 10px;
font-size: 0.84rem;
font-weight: 600;
cursor: pointer;
transition: background 0.15s;
}
.btn-add:hover { background: var(--primary-green-hover); }
.btn-add:disabled {
background: #cbd5e1;
cursor: not-allowed;
}
/* Cart Drawer & Modals */
.drawer-backdrop, .modal-backdrop {
position: fixed;
inset: 0;
background: rgba(20, 30, 24, 0.48);
backdrop-filter: blur(3px);
z-index: 60;
display: none;
align-items: center;
justify-content: center;
}
.drawer-backdrop.open, .modal-backdrop.open {
display: flex;
}
.cart-drawer {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: min(420px, 100vw);
background: var(--bg-card);
z-index: 70;
box-shadow: -8px 0 32px rgba(0, 0, 0, 0.18);
display: flex;
flex-direction: column;
transform: translateX(100%);
transition: transform 0.25s ease;
}
.cart-drawer.open { transform: translateX(0); }
.drawer-header {
padding: 1.15rem 1.35rem;
border-bottom: 1px solid var(--border-soft);
display: flex;
justify-content: space-between;
align-items: center;
background: var(--bg-sage-soft);
}
.drawer-body {
padding: 1.15rem 1.35rem;
overflow-y: auto;
flex: 1;
}
.drawer-footer {
padding: 1.15rem 1.35rem;
border-top: 1px solid var(--border-soft);
background: var(--bg-cream);
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 0;
border-bottom: 1px solid var(--border-soft);
}
.qty-controls {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.qty-btn {
width: 26px;
height: 26px;
border-radius: 6px;
border: 1px solid var(--border-soft);
background: #fff;
cursor: pointer;
font-weight: 700;
}
.modal-card {
background: var(--bg-card);
border-radius: var(--radius-lg);
max-width: 640px;
width: calc(100% - 2rem);
max-height: 90vh;
overflow-y: auto;
padding: 1.65rem;
box-shadow: var(--shadow-md);
position: relative;
}
.btn-close {
background: var(--bg-cream);
border: 1px solid var(--border-soft);
width: 32px;
height: 32px;
border-radius: 50%;
cursor: pointer;
font-size: 1rem;
font-weight: 700;
}
/* Checkout Form */
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.85rem;
margin-top: 0.85rem;
}
.form-full { grid-column: 1 / -1; }
.form-label {
display: block;
font-size: 0.8rem;
font-weight: 600;
margin-bottom: 0.25rem;
color: var(--text-dark);
}
.form-input {
width: 100%;
padding: 0.55rem 0.75rem;
border: 1px solid var(--border-soft);
border-radius: 8px;
font-size: 0.9rem;
}
footer {
background: #1f3328;
color: #d3e0d8;
padding: 1.75rem 1.5rem;
font-size: 0.85rem;
}
.footer-inner {
max-width: 1240px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
.footer-inner a { color: #a7f3d0; text-decoration: none; }
@media (max-width: 640px) {
.hero-box { padding: 1.5rem; }
.form-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="topbar">
<div class="topbar-status">
<span class="status-dot"></span>
<span>Catálogo y stock sincronizados en vivo con <strong>FacturaScripts ERP</strong></span>
</div>
<div>
<span>Envío refrigerado gratuito desde 45,00 € · </span>
<a href="/facturas/" target="_blank">Panel ERP FacturaScripts ↗</a>
</div>
</div>
<header>
<div class="header-inner">
<a href="{{.BasePath}}/" class="brand">
<div class="brand-icon">✿</div>
<div>
<span class="brand-title">Flora Atlántica</span>
<span class="brand-sub">Flores Ornamentales &amp; Taller Botánico</span>
</div>
</a>
<div class="header-actions">
<button class="btn-sync"
hx-post="{{.BasePath}}/htmx/sync"
hx-target="#catalog-container"
hx-swap="innerHTML"
title="Sincronizar catálogo con FacturaScripts ahora">
↻ Sincronizar ERP
</button>
<button class="btn-cart" onclick="openCartDrawer()">
<span>Cesta Floral</span>
<span id="header-cart-badge" class="cart-badge">{{.Cart.TotalCount}}</span>
</button>
</div>
</div>
</header>
<section class="hero">
<div class="hero-box">
<div class="hero-content">
<span class="hero-tag">Floristería Artesanal · Tenerife</span>
<h1>Flores ornamentales frescas del cultivo a tu hogar</h1>
<p>Ramos de autor, orquídeas seleccionadas, centros florales y plantas de interior con facturación y control de stock integrados en tiempo real con FacturaScripts.</p>
<div class="hero-highlights">
<span>✓ Corte del día</span>
<span>✓ Tarjeta dedicatoria incluida</span>
<span>✓ Factura y pedido instantáneo en ERP</span>
</div>
</div>
</div>
</section>
<section class="toolbar">
<form class="filter-bar"
hx-get="{{.BasePath}}/htmx/catalogo"
hx-target="#catalog-container"
hx-trigger="change, keyup delay:300ms from:input[name='q']">
<input type="hidden" name="familia" id="familia-input" value="">
<div class="family-pills">
<button type="button" class="pill active" onclick="selectFamilia(this, '')">Todas las flores</button>
{{range .Families}}
<button type="button" class="pill" onclick="selectFamilia(this, '{{.Code}}')">{{.Description}}</button>
{{end}}
</div>
<div class="search-group">
<input type="search" name="q" class="search-input" placeholder="Buscar rosa, orquídea, lavanda...">
<label class="stock-toggle">
<input type="checkbox" name="stock" value="1">
<span>Solo con stock disponible</span>
</label>
</div>
</form>
</section>
<main id="catalog-container">
{{template "catalog_grid.html" .}}
</main>
<!-- Cart Drawer -->
<div id="drawer-backdrop" class="drawer-backdrop" onclick="closeCartDrawer()"></div>
<aside id="cart-drawer" class="cart-drawer">
{{template "cart_drawer.html" (dictCart .BasePath .Cart false)}}
</aside>
<!-- Modal Container (Product Details / Checkout / Order Confirmation) -->
<div id="modal-backdrop" class="modal-backdrop" onclick="if(event.target===this) closeModal()">
<div id="modal-content" class="modal-card"></div>
</div>
<footer>
<div class="footer-inner">
<div>
<strong>Flora Atlántica</strong> — Tienda Online de Flores Ornamentales conectada a FacturaScripts API v3
</div>
<div>
<a href="/facturas/" target="_blank">Gestionar productos, stock y facturas en FacturaScripts →</a>
</div>
</div>
</footer>
<script>
function selectFamilia(btn, code) {
document.querySelectorAll('.family-pills .pill').forEach(el => el.classList.remove('active'));
btn.classList.add('active');
const input = document.getElementById('familia-input');
input.value = code;
htmx.trigger(input.closest('form'), 'change');
}
function openCartDrawer() {
document.getElementById('drawer-backdrop').classList.add('open');
document.getElementById('cart-drawer').classList.add('open');
}
function closeCartDrawer() {
document.getElementById('drawer-backdrop').classList.remove('open');
document.getElementById('cart-drawer').classList.remove('open');
}
function openModal() {
document.getElementById('modal-backdrop').classList.add('open');
}
function closeModal() {
document.getElementById('modal-backdrop').classList.remove('open');
}
</script>
</body>
</html>

View file

@ -0,0 +1,43 @@
<span id="header-cart-badge" class="cart-badge" hx-swap-oob="true">0</span>
<div style="text-align:center; padding:1rem 0.5rem;">
<div style="width:58px; height:58px; border-radius:50%; background:#d1fae5; color:#065f46; display:inline-flex; align-items:center; justify-content:center; font-size:1.8rem; margin-bottom:0.85rem;">
✓
</div>
<h2 style="font-family:Georgia, serif; color:var(--primary-green); font-size:1.5rem; margin-bottom:0.35rem;">
¡Pedido registrado con éxito!
</h2>
<p style="color:var(--text-muted); font-size:0.92rem; margin-bottom:1.25rem;">
Tu pedido se ha grabado automáticamente en <strong>FacturaScripts ERP</strong> y nuestro taller botánico ya lo ha recibido.
</p>
<div style="background:var(--bg-cream); border:1px solid var(--border-soft); border-radius:12px; padding:1rem 1.25rem; text-align:left; margin-bottom:1.25rem; font-size:0.88rem;">
<div style="display:flex; justify-content:space-between; margin-bottom:0.4rem;">
<span style="color:var(--text-muted);">Código Pedido FacturaScripts:</span>
<strong style="color:var(--primary-green);">{{.Order.OrderCode}} (ID #{{.Order.OrderID}})</strong>
</div>
<div style="display:flex; justify-content:space-between; margin-bottom:0.4rem;">
<span style="color:var(--text-muted);">Ficha Cliente FacturaScripts:</span>
<strong>{{.Order.CustomerName}} ({{.Order.CustomerCode}})</strong>
</div>
{{if .Order.DeliveryDate}}
<div style="display:flex; justify-content:space-between; margin-bottom:0.4rem;">
<span style="color:var(--text-muted);">Fecha de entrega:</span>
<strong>{{.Order.DeliveryDate}}</strong>
</div>
{{end}}
<div style="display:flex; justify-content:space-between; padding-top:0.5rem; border-top:1px solid var(--border-soft); font-size:1rem;">
<span>Total registrado:</span>
<strong style="color:var(--primary-green);">{{eur .Order.TotalGross}}</strong>
</div>
</div>
<div style="display:flex; justify-content:center; gap:0.75rem; flex-wrap:wrap;">
<a href="/facturas/EditPedidoCliente?code={{.Order.OrderID}}" target="_blank" class="btn-sync" style="text-decoration:none;">
Ver pedido en FacturaScripts ↗
</a>
<button type="button" class="btn-add" onclick="closeModal(); window.location.reload();">
Seguir comprando
</button>
</div>
</div>

View file

@ -0,0 +1,49 @@
<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:1rem; margin-bottom:1rem;">
<div>
<span style="font-size:0.75rem; font-weight:700; text-transform:uppercase; color:var(--accent-terracotta);">
{{if .Product.FamilyName}}{{.Product.FamilyName}}{{else}}Colección Botánica{{end}} · Ref: {{.Product.Reference}}
</span>
<h2 style="font-family:Georgia, serif; font-size:1.4rem; color:var(--primary-green); margin-top:0.2rem;">
{{.Product.Name}}
</h2>
</div>
<button type="button" class="btn-close" onclick="closeModal()">✕</button>
</div>
<div style="border-radius:12px; overflow:hidden; height:230px; background:var(--bg-sage-soft); margin-bottom:1.1rem;">
<img src="{{imgPath .BasePath .Product.ImageURL}}" alt="{{.Product.Name}}" style="width:100%; height:100%; object-fit:cover;">
</div>
<p style="font-size:0.95rem; color:var(--text-dark); margin-bottom:1rem;">
{{.Product.Observations}}
</p>
{{if .Product.CareTips}}
<div style="background:var(--bg-sage-soft); border-left:4px solid var(--primary-green); padding:0.85rem 1rem; border-radius:8px; margin-bottom:1.25rem; font-size:0.86rem;">
<strong style="color:var(--primary-green); display:block; margin-bottom:0.2rem;">🌿 Guía de conservación y cuidados botánicos:</strong>
<span>{{.Product.CareTips}}</span>
</div>
{{end}}
<div style="display:flex; justify-content:space-between; align-items:center; border-top:1px solid var(--border-soft); padding-top:1rem; flex-wrap:wrap; gap:1rem;">
<div>
<div style="font-size:1.45rem; font-weight:800; color:var(--primary-green);">{{eur .Product.PriceGross}}</div>
<div style="font-size:0.78rem; color:var(--text-muted);">
Precio neto: {{eur .Product.PriceNet}} · Stock en FacturaScripts: <strong>{{.Product.Stock}} uds.</strong>
</div>
</div>
<form hx-post="{{.BasePath}}/htmx/carrito/add"
hx-target="#cart-drawer"
hx-swap="innerHTML"
hx-on::after-request="closeModal(); openCartDrawer();"
style="display:flex; align-items:center; gap:0.65rem;">
<input type="hidden" name="ref" value="{{.Product.Reference}}">
<label style="font-size:0.85rem; font-weight:600;">Cant.:</label>
<input type="number" name="qty" value="1" min="1" max="{{if gt .Product.Stock 0}}{{.Product.Stock}}{{else}}1{{end}}"
style="width:64px; padding:0.45rem; border:1px solid var(--border-soft); border-radius:8px; text-align:center;">
<button type="submit" class="btn-add" {{if le .Product.Stock 0}}disabled{{end}}>
{{if gt .Product.Stock 0}}Añadir a la cesta{{else}}Agotado{{end}}
</button>
</form>
</div>