Configurazione

Guida completa alla configurazione avanzata di Lema.

File di configurazione

Lema utilizza diversi file di configurazione:

startup-manager-server/
└── data/
    ├── central.db            # Database centrale (tenant, utenti globali, sessioni)
    └── tenants/
        └── tnt-xxxxxx/       # Cartella tenant (ID generato)
            └── tenant.db     # Database SQLite del tenant

## Variabili d'ambiente

```bash
# Server
PORT=3001                      # Porta server API
NODE_ENV=production           # Ambiente: development, production
LOG_LEVEL=info                # Livello log: debug, info, warn, error

# Database
DB_WAL_MODE=true              # Abilita Write-Ahead Logging (consigliato)
DB_BUSY_TIMEOUT=5000          # Timeout lock database (ms)

# Sicurezza
CORS_ORIGIN=http://localhost:5173  # Origini CORS consentite

Configurazione paese

La configurazione del paese determina molti comportamenti del sistema:

// startup-manager-server/src/routes/app.ts
const COUNTRY_CONFIGS = {
  CH: {
    currency: 'CHF',
    vatRates: [
      { code: 'NORMAL', rate: 8.1, label: 'IVA normale 8.1%' },
      { code: 'REDUCED', rate: 2.6, label: 'IVA ridotta 2.6%' },
      { code: 'HOTEL', rate: 3.8, label: 'IVA alloggio 3.8%' },
      { code: 'EXEMPT', rate: 0, label: 'Esente IVA' }
    ],
    labels: {
      state: 'Cantone',
      zip: 'NPA',
      vatNumber: 'N. IVA'
    },
    hiddenFields: ['tax_code', 'pec', 'sdi_code'],
    features: {
      qrBill: true,
      fatturaPA: false
    }
  },
  IT: {
    currency: 'EUR',
    vatRates: [
      { code: 'NORMAL', rate: 22, label: 'IVA ordinaria 22%' },
      { code: 'REDUCED_10', rate: 10, label: 'IVA ridotta 10%' },
      { code: 'REDUCED_5', rate: 5, label: 'IVA ridotta 5%' },
      { code: 'REDUCED_4', rate: 4, label: 'IVA minima 4%' },
      { code: 'EXEMPT', rate: 0, label: 'Esente art. 10' }
    ],
    labels: {
      state: 'Provincia',
      zip: 'CAP',
      vatNumber: 'P. IVA'
    },
    hiddenFields: [],
    features: {
      qrBill: false,
      fatturaPA: true
    }
  }
  // ... DE, FR, AT
};

Database SQLite

WAL Mode

Lema usa SQLite in modalità WAL (Write-Ahead Logging) per migliori performance:

-- Abilitato automaticamente all'avvio
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA cache_size = -64000;  -- 64MB cache
PRAGMA foreign_keys = ON;

Backup

Il sistema di backup è automatizzato e multi-tenant. Il cron job notturno esegue backup di tutti i tenant attivi.

# Backup manuale DB via API (richiede login)
curl -X POST "https://lema.arcaweb.ch/api/backup?type=db" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# Backup completo (DB + uploads)
curl -X POST "https://lema.arcaweb.ch/api/backup?type=full" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# Lista backup
curl "https://lema.arcaweb.ch/api/backup" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# Download backup
curl -O "https://lema.arcaweb.ch/api/backup/BACKUP_ID/download" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Per la documentazione completa delle API backup, vedi API Reference.

Migrazioni

Le migrazioni sono automatiche all'avvio del server:

// startup-manager-server/src/database/migrations.ts
const migrations = [
  { version: 1, name: 'initial_schema', sql: '...' },
  { version: 2, name: 'add_qr_bill_fields', sql: '...' },
  // ...
];

Multi-tenant

Per deployment cloud, Lema supporta multi-tenant con i dati gestiti nel database centrale:

-- Tabella _tenants nel database centrale (central.db)
CREATE TABLE _tenants (
  id TEXT PRIMARY KEY,           -- es. 'tnt-abc123'
  name TEXT NOT NULL,
  plan TEXT DEFAULT 'free',      -- free, pro, team, enterprise
  active INTEGER DEFAULT 1,
  metadata TEXT,                 -- JSON con flags (embedded, autoCreated)
  created_at TEXT,
  updated_at TEXT
);

I tenant vengono creati automaticamente:

  • Tenant embedded: creato all'avvio di Electron (flag embedded: true)
  • Tenant cloud: creato via registrazione utente

Personalizzazione UI

Logo e branding

// Impostazioni azienda (tabella app_settings)
{
  "company_logo": "base64_encoded_image",
  "company_name": "La Mia Azienda",
  "primary_color": "#0047AB",  // Colore principale
  "accent_color": "#00D9FF"    // Colore accento
}

Debug e logging

Livelli di log

// config.ts
const LOG_LEVELS = {
  debug: 0,   // Tutto, inclusi dettagli SQL
  info: 1,    // Operazioni normali
  warn: 2,    // Avvisi, deprecations
  error: 3    // Solo errori
};

Abilitare debug SQL

# .env
LOG_LEVEL=debug
DB_QUERY_LOG=true

Ispezionare il database

# Apri shell SQLite (sostituisci tnt-xxxxxx con l'ID del tuo tenant)
sqlite3 data/tenants/tnt-xxxxxx/startup-manager.db

# Query utili
.tables                         # Lista tabelle
.schema contacts                # Schema tabella
SELECT * FROM contacts LIMIT 5; # Sample dati

Performance tuning

Cache

// Server-side caching
const cacheConfig = {
  metaSchema: 300,    // 5 min - schema tabelle
  vatRates: 3600,     // 1 ora - aliquote IVA
  settings: 60        // 1 min - impostazioni
};

Indici database

Gli indici sono creati automaticamente per i campi più usati:

CREATE INDEX idx_contacts_name ON contacts(name);
CREATE INDEX idx_contacts_email ON contacts(email);
CREATE INDEX idx_invoices_date ON invoices(date);
CREATE INDEX idx_invoices_contact_id ON invoices(contact_id);