Riferimento API

Core

Riferimento API per il package Core - HTTP client, autenticazione e tipi base.

Package Core

Il package @fatturazione-elettronica-aruba/core è la base dell'SDK. Fornisce il client HTTP, l'autenticazione OAuth2 e tutti i tipi base usati negli altri package.

Installazione

pnpm add @fatturazione-elettronica-aruba/core

ArubaClient

Punto di ingresso principale che combina client HTTP e autenticazione.

import { ArubaClient } from '@fatturazione-elettronica-aruba/core';

const client = new ArubaClient({
  environment: 'production',
  timeout: 30000,
  maxRetries: 3,
});

ArubaClientOptions

ProprietàTipoDefaultDescrizione
environment'demo' | 'production'ObbligatorioAmbiente API
timeoutnumber30000Timeout richieste in millisecondi
maxRetriesnumber3Max tentativi per errori rate limit
tokenStorageTokenStorageMemoryTokenStorageImplementazione storage token personalizzata
autoRefreshbooleantrueRefresh automatico token scaduti
refreshMarginnumber60Secondi prima della scadenza per refresh

Proprietà

ProprietàTipoDescrizione
authAuthClientClient di autenticazione
httpHttpClientClient HTTP per chiamate API dirette

Metodi

// Verifica se il client è autenticato
client.isAuthenticated(): boolean

AuthClient

Gestisce l'autenticazione OAuth2 e la gestione dei token.

signIn(username, password)

Autentica con le credenziali Aruba e memorizza il token.

const token = await client.auth.signIn('user@example.com', 'password');
// Il token viene automaticamente memorizzato e usato per le richieste successive

Ritorna: AuthToken

refresh(refreshToken?)

Rinnova l'access token. Se non viene fornito un refresh token, usa quello memorizzato.

const newToken = await client.auth.refresh();
// Oppure con refresh token esplicito
const newToken = await client.auth.refresh('refresh_token_value');

Ritorna: AuthToken

getUserInfo()

Recupera le informazioni sull'utente autenticato.

const info = await client.auth.getUserInfo();
console.log(info.vatCode);      // Partita IVA
console.log(info.fiscalCode);   // Codice fiscale
console.log(info.accountStatus.expired); // Stato account
console.log(info.usageStatus.usedSpaceKB); // Spazio usato

Ritorna: UserInfo

getMulticedenti(params?)

Recupera la lista delle aziende per account multi-azienda (funzionalità Premium).

const result = await client.auth.getMulticedenti({
  page: 0,
  size: 20,
  status: 'ACTIVE',
});

for (const company of result.content) {
  console.log(company.vatCode, company.description);
}

Ritorna: PagedResponse<Multicedente>

isAuthenticated()

Verifica se un token valido è memorizzato.

if (client.auth.isAuthenticated()) {
  // Token disponibile
}

HttpClient

Client HTTP di basso livello per chiamate API dirette. Di solito non serve usarlo direttamente.

const http = client.http;

// Richiesta GET
const data = await http.get<ResponseType>('ws', '/api/v2/endpoint', { param: 'value' });

// Richiesta POST
const result = await http.post<ResponseType>('ws', '/api/v2/endpoint', { body: 'data' });

HttpClientOptions

ProprietàTipoDefaultDescrizione
environmentEnvironmentObbligatorioAmbiente API
timeoutnumber30000Timeout richieste in ms
maxRetriesnumber3Max tentativi per errori 429
retryDelaynumber1000Delay base tra i tentativi
headersRecord<string, string>-Header aggiuntivi

Metodi

// GET con parametri query
http.get<T>(baseType: 'auth' | 'ws', path: string, params?: object, options?: RequestOptions): Promise<T>

// POST con body JSON
http.post<T>(baseType: 'auth' | 'ws', path: string, body?: unknown, options?: RequestOptions): Promise<T>

// POST con form data
http.postForm<T>(baseType: 'auth' | 'ws', path: string, data: Record<string, string>, options?: RequestOptions): Promise<T>

// Gestione token
http.setAccessToken(token: string | null): void
http.getAccessToken(): string | null

TokenStorage

Interfaccia per persistenza token personalizzata. Implementa questa per salvare token in localStorage, database, ecc.

interface TokenStorage {
  getToken(): AuthToken | null;
  setToken(token: AuthToken): void;
  clearToken(): void;
}

MemoryTokenStorage

Implementazione di default in memoria (token persi al riavvio).

import { MemoryTokenStorage } from '@fatturazione-elettronica-aruba/core';

const storage = new MemoryTokenStorage();

Esempio Implementazione Personalizzata

class RedisTokenStorage implements TokenStorage {
  constructor(private redis: RedisClient, private key: string) {}

  getToken(): AuthToken | null {
    const data = this.redis.get(this.key);
    return data ? JSON.parse(data) : null;
  }

  setToken(token: AuthToken): void {
    this.redis.set(this.key, JSON.stringify(token));
  }

  clearToken(): void {
    this.redis.del(this.key);
  }
}

const client = new ArubaClient({
  environment: 'production',
  tokenStorage: new RedisTokenStorage(redis, 'aruba:token'),
});

Tipi

Environment

type Environment = 'demo' | 'production';

AuthToken

interface AuthToken {
  access_token: string;
  token_type: 'bearer';
  expires_in: number;       // Secondi (tipicamente 1800 = 30 min)
  refresh_token: string;
  userName: string;
  'as:client_id': string;
  '.issued': string;
  '.expires': string;
}

UserInfo

interface UserInfo {
  username: string;
  pec: string;
  userDescription: string;
  countryCode: string;
  vatCode: string;
  fiscalCode: string;
  accountStatus: AccountStatus;
  usageStatus: UsageStatus;
}

interface AccountStatus {
  expired: boolean;
  expirationDate: string;
}

interface UsageStatus {
  usedSpaceKB: number;
  maxSpaceKB: number;
}

Multicedente

interface Multicedente {
  id: string;
  description: string;
  countryCode: string;
  vatCode: string;
  usedSpaceKB: number;
  creationDate: string;
  status: MulticedenteStatus;
}

type MulticedenteStatus =
  | 'ACTIVE'
  | 'INACTIVE'
  | 'PENDING'
  | 'REQUESTED_FOR_ACTIVATION'
  | 'REQUESTED_FOR_DEACTIVATION';

PagedResponse

Tipo generico per risposte paginate usato in tutto l'SDK.

interface PagedResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;  // Pagina corrente (0-indexed)
}

Costanti

URL Ambienti

import { ENVIRONMENT_URLS } from '@fatturazione-elettronica-aruba/core';

ENVIRONMENT_URLS.demo.authUrl    // 'https://demoauth.fatturazioneelettronica.aruba.it'
ENVIRONMENT_URLS.demo.wsUrl      // 'https://demows.fatturazioneelettronica.aruba.it'
ENVIRONMENT_URLS.production.authUrl // 'https://auth.fatturazioneelettronica.aruba.it'
ENVIRONMENT_URLS.production.wsUrl   // 'https://ws.fatturazioneelettronica.aruba.it'

Rate Limits

import { RATE_LIMITS } from '@fatturazione-elettronica-aruba/core';

RATE_LIMITS.auth    // 1 richiesta/minuto
RATE_LIMITS.upload  // 30 richieste/minuto
RATE_LIMITS.search  // 12 richieste/minuto

Limiti File

import { FILE_LIMITS } from '@fatturazione-elettronica-aruba/core';

FILE_LIMITS.maxFileSize  // 5242880 (5 MB)

Costanti Aruba

Costanti necessarie per costruire fatture tramite il servizio intermediario Aruba.

import { ARUBA_CONSTANTS } from '@fatturazione-elettronica-aruba/core';

ARUBA_CONSTANTS.codiceDestinatario  // 'KRRH6B9'
ARUBA_CONSTANTS.idTrasmittente      // 'IT01879020517'

Oppure importa singolarmente:

import {
  ARUBA_ID_TRASMITTENTE,     // '01879020517'
  ARUBA_CODICE_DESTINATARIO, // 'KRRH6B9'
  ARUBA_COUNTRY_CODE,        // 'IT'
} from '@fatturazione-elettronica-aruba/core';