@dokicasa/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,880 @@
1
+ /** Stati di una richiesta scanner. ENQUEUED/WAITING/SCANNING sono transitori. */
2
+ type ScannerRequestStatus = 'ENQUEUED' | 'WAITING' | 'SCANNING' | 'PENDING_CALLBACK' | 'SUCCESS' | 'ERROR' | 'CANCELLED';
3
+ declare const FINAL_STATUSES: readonly ScannerRequestStatus[];
4
+ declare function isFinalStatus(status: string | null | undefined): boolean;
5
+ /** Tipo catastale: F = fabbricati, T = terreni, E = entrambi (solo ricerche per soggetto). */
6
+ type CatastoType = 'F' | 'T' | 'E';
7
+ /** Campi comuni accettati da tutte le ricerche. */
8
+ interface CommonScanParams {
9
+ /** Riusa un risultato identico recente invece di rifare la ricerca (se disponibile). */
10
+ reuse_recent?: boolean;
11
+ /** URL chiamato a fine ricerca con il risultato compatto. */
12
+ callback?: string;
13
+ /** URL chiamato a fine ricerca con `{ scanner_request }`, firmato (header `Signature`). */
14
+ webhook?: string;
15
+ /** Richiesta padre (censimenti, documenti legati a una ricerca). */
16
+ scanner_request_parent_id?: number;
17
+ sezione_comune?: string;
18
+ /** Salta il blocco anti-doppione (stessa richiesta entro pochi secondi). */
19
+ skip_pending_calls?: boolean;
20
+ [extra: string]: unknown;
21
+ }
22
+ interface ParcelParams extends CommonScanParams {
23
+ foglio: string;
24
+ particella: string;
25
+ subalterno?: string;
26
+ comune: string;
27
+ provincia?: string;
28
+ search_catasto_type?: CatastoType;
29
+ }
30
+ /** Parametri per tipo di ricerca (POST /api/scanner/{type}). */
31
+ interface ScanParamsByType {
32
+ catasto: ParcelParams & {
33
+ search_catasto_type: 'F' | 'T';
34
+ };
35
+ 'elenco-immobili': ParcelParams & {
36
+ search_catasto_type: 'F' | 'T';
37
+ };
38
+ 'intestatari-catasto': ParcelParams & {
39
+ provincia: string;
40
+ search_catasto_type: 'F' | 'T';
41
+ };
42
+ 'visura-catasto': ParcelParams & {
43
+ provincia: string;
44
+ tipo_visura: 'ANALITICA' | 'SINTETICA' | 'COMPLETA';
45
+ enable_multi_step?: boolean;
46
+ selected_value?: string;
47
+ };
48
+ 'visura-tax-data': CommonScanParams & {
49
+ tax_code?: string;
50
+ provincia: string;
51
+ comune?: string;
52
+ tipo_visura: 'ANALITICA' | 'SINTETICA' | 'COMPLETA';
53
+ storica?: boolean;
54
+ situazione_al?: string;
55
+ search_catasto_type?: CatastoType;
56
+ selected_value?: string;
57
+ };
58
+ 'tax-data': CommonScanParams & {
59
+ tax_code: string;
60
+ provincia?: string;
61
+ comune?: string;
62
+ search_catasto_type?: CatastoType;
63
+ };
64
+ 'ispezione-catasto': ParcelParams & {
65
+ enable_multi_step?: boolean;
66
+ selected_value?: string;
67
+ };
68
+ 'ispezione-tax-data': CommonScanParams & {
69
+ tax_code: string;
70
+ provincia?: string;
71
+ comune?: string;
72
+ conservatoria?: 'NAZIONALE' | string;
73
+ };
74
+ 'nota-catasto': ParcelParams & {
75
+ provincia: string;
76
+ numero_registro_particolare: string;
77
+ anno_registro: string;
78
+ tipo_nota: string;
79
+ enable_multi_step?: boolean;
80
+ selected_value?: string;
81
+ };
82
+ 'nota-tax-data': CommonScanParams & {
83
+ tax_data: string;
84
+ provincia: string;
85
+ comune: string;
86
+ numero_registro_particolare: string;
87
+ anno_registro: string;
88
+ tipo_nota: string;
89
+ };
90
+ 'mappa-catasto': ParcelParams & {
91
+ provincia: string;
92
+ tipo_richiesta: 'ATTUALITA' | 'STORICA';
93
+ tipo_foglio: 'INTERO' | 'MAPPE_LIMITROFE';
94
+ formato: 'A3' | 'A4' | 'SCALA_ORIGINARIA';
95
+ sezione?: string;
96
+ };
97
+ 'mappa-sezioni': ParcelParams & {
98
+ provincia: string;
99
+ };
100
+ 'elaborato-planimetrico': ParcelParams & {
101
+ provincia: string;
102
+ elaborato_planimetrico?: string;
103
+ formato?: 'A3' | 'A4';
104
+ tipo_richiesta?: string;
105
+ };
106
+ 'search-fiscal-code': CommonScanParams & {
107
+ first_name: string;
108
+ last_name: string;
109
+ provincia?: string;
110
+ comune?: string;
111
+ birth_date?: string;
112
+ };
113
+ 'search-company': CommonScanParams & {
114
+ company_name: string;
115
+ provincia?: string;
116
+ };
117
+ 'immobili-by-name': CommonScanParams & {
118
+ first_name: string;
119
+ last_name: string;
120
+ selected_value?: string;
121
+ };
122
+ 'list-addresses': CommonScanParams & {
123
+ indirizzo: string;
124
+ comune: string;
125
+ provincia: string;
126
+ search_catasto_type?: 'F' | 'T';
127
+ address_value?: string;
128
+ numero_civico?: string;
129
+ civico_a?: string;
130
+ };
131
+ 'bulk-list-addresses': CommonScanParams & {
132
+ search_mode?: null | 'PROPERTY_OWNERS' | 'MULTI_ADDRESS';
133
+ };
134
+ }
135
+ type ScanType = keyof ScanParamsByType;
136
+ /** Risposta del POST /api/scanner/{type}. */
137
+ interface CreatedScan<R = ScanResult> {
138
+ status: ScannerRequestStatus;
139
+ scanner_request_id: number;
140
+ type: string;
141
+ response?: R | null;
142
+ polling_url?: string;
143
+ reused?: boolean;
144
+ reused_at?: string;
145
+ }
146
+ /** Risultato di una richiesta: la forma dipende dal tipo. */
147
+ interface ScanResult {
148
+ /** Documenti (visure, ispezioni, note, mappe...): link da scaricare. */
149
+ pdf_path?: string | null;
150
+ is_empty?: boolean;
151
+ is_nota_negativa?: boolean;
152
+ /** Ricerche in piu' passi: scegliere un valore e rilanciare con `selected_value`. */
153
+ needs_selection?: boolean;
154
+ rows_immobili?: Array<{
155
+ label: string;
156
+ value: string;
157
+ }>;
158
+ rows_telematiche?: Array<{
159
+ label: string;
160
+ value: string;
161
+ }>;
162
+ omonimi?: Array<Record<string, unknown>>;
163
+ sezioni?: Array<Record<string, unknown>>;
164
+ elaborati?: Array<{
165
+ id: string;
166
+ [k: string]: unknown;
167
+ }>;
168
+ /** list-addresses (primo passo): mappa valore -> indirizzo. */
169
+ addresses?: Record<string, string>;
170
+ immobili?: Array<Record<string, unknown>>;
171
+ soggetti?: Array<Record<string, unknown>>;
172
+ has_soppressi?: boolean;
173
+ [extra: string]: unknown;
174
+ }
175
+ interface ScannerRequest<R = ScanResult> {
176
+ id: number;
177
+ type: string;
178
+ status: ScannerRequestStatus;
179
+ percentage: number;
180
+ params?: Record<string, unknown>;
181
+ result?: R | null;
182
+ details?: string | null;
183
+ started_at?: string | null;
184
+ finished_at?: string | null;
185
+ created_at?: string;
186
+ updated_at?: string;
187
+ scanner_request_parent_id?: number | null;
188
+ soggetti?: Array<Record<string, unknown>>;
189
+ documents?: Array<Record<string, unknown>>;
190
+ [extra: string]: unknown;
191
+ }
192
+ interface ScannerRequestStatusInfo {
193
+ id: number;
194
+ status: ScannerRequestStatus;
195
+ percentage: number;
196
+ children?: {
197
+ total: number;
198
+ success: number;
199
+ error: number;
200
+ open: number;
201
+ };
202
+ }
203
+ /** Evento realtime sul canale private-scanner_request.{id}. */
204
+ interface ScannerProgressEvent {
205
+ id: number;
206
+ status: ScannerRequestStatus;
207
+ percentage: number;
208
+ updated_at?: string;
209
+ }
210
+ interface Paginated<T> {
211
+ data: T[];
212
+ current_page: number;
213
+ last_page: number;
214
+ per_page?: number;
215
+ total: number;
216
+ [extra: string]: unknown;
217
+ }
218
+ interface ResultsQuery {
219
+ page?: number;
220
+ per_page?: number;
221
+ include_soppressi?: boolean;
222
+ /** Filtri per colonna: `{ foglio: ['12'], categoria: ['A/2'] }`. */
223
+ filters?: Record<string, Array<string | number> | string | number>;
224
+ }
225
+ interface ScannerHealth {
226
+ status: 'ok' | 'degraded' | 'down' | string;
227
+ accepting_requests: boolean;
228
+ maintenance?: {
229
+ scanner_blocked?: boolean;
230
+ [k: string]: unknown;
231
+ } | null;
232
+ queue?: {
233
+ enqueued?: number;
234
+ scanning?: number;
235
+ max_wait_seconds?: number;
236
+ };
237
+ types?: Record<string, {
238
+ status: 'ok' | 'degraded' | 'down' | string;
239
+ reason?: string | null;
240
+ [k: string]: unknown;
241
+ }>;
242
+ recommended_poll_seconds?: number;
243
+ [extra: string]: unknown;
244
+ }
245
+ interface ServiceCatalogItem {
246
+ has_credits: boolean;
247
+ can_unlock: boolean;
248
+ checkout_url?: string | null;
249
+ product?: {
250
+ amount?: number;
251
+ [k: string]: unknown;
252
+ } | null;
253
+ amount_negative_response?: number | null;
254
+ service_id?: number | null;
255
+ [extra: string]: unknown;
256
+ }
257
+ interface Wallet {
258
+ wallet: number;
259
+ real_wallet: number;
260
+ }
261
+ interface MonitoringModel {
262
+ model_name: 'IMMOBILE' | 'SOGGETTO';
263
+ model_id: number;
264
+ }
265
+ interface DownloadedFile {
266
+ data: ArrayBuffer;
267
+ contentType: string | null;
268
+ filename: string | null;
269
+ }
270
+
271
+ type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
272
+ interface RequestOptions {
273
+ query?: Record<string, unknown>;
274
+ body?: unknown;
275
+ headers?: Record<string, string>;
276
+ signal?: AbortSignal;
277
+ /** Timeout di questa chiamata (sovrascrive quello del client). */
278
+ timeoutMs?: number;
279
+ /** Forza (true) o vieta (false) i ritentativi per questa chiamata. */
280
+ retry?: boolean;
281
+ }
282
+ interface HttpRequestInfo {
283
+ method: HttpMethod;
284
+ url: string;
285
+ attempt: number;
286
+ headers: Record<string, string>;
287
+ }
288
+ interface HttpResponseInfo extends HttpRequestInfo {
289
+ status: number;
290
+ durationMs: number;
291
+ error?: unknown;
292
+ }
293
+ /** Client HTTP: autenticazione, timeout, annullamento, ritentativi ed errori tipizzati. */
294
+ declare class HttpClient {
295
+ private readonly config;
296
+ constructor(config: ResolvedConfig);
297
+ get baseUrl(): string;
298
+ request<T = unknown>(method: HttpMethod, path: string, options?: RequestOptions): Promise<T>;
299
+ get<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
300
+ post<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
301
+ patch<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
302
+ delete<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
303
+ /** Scarica un file (PDF, XLSX...) con il nome da Content-Disposition. */
304
+ download(pathOrUrl: string, options?: RequestOptions): Promise<DownloadedFile>;
305
+ /** URL assoluto: i path relativi si appoggiano al baseUrl, gli URL completi restano tali. */
306
+ url(pathOrUrl: string, query?: Record<string, unknown>): string;
307
+ private send;
308
+ private attempt;
309
+ /** Attesa prima del prossimo tentativo, o null se non si ritenta. */
310
+ private retryDelay;
311
+ private parseBody;
312
+ }
313
+
314
+ /** Ambienti ufficiali (valori pubblici di docs.dokicasa.it). */
315
+ declare const ENVIRONMENTS: {
316
+ readonly production: {
317
+ readonly baseUrl: "https://api.dokicasa.it";
318
+ readonly realtime: {
319
+ readonly key: "ra9jcihuz0sx7vtw8yut";
320
+ readonly wsHost: "socket.dokicasa.it";
321
+ readonly wsPort: 443;
322
+ readonly forceTLS: true;
323
+ };
324
+ };
325
+ readonly sandbox: {
326
+ readonly baseUrl: "https://api-dev.dokicasa.it";
327
+ readonly realtime: {
328
+ readonly key: "staging";
329
+ readonly wsHost: "api-dev.dokicasa.it";
330
+ readonly wsPort: 443;
331
+ readonly forceTLS: true;
332
+ };
333
+ };
334
+ };
335
+ type EnvironmentName = keyof typeof ENVIRONMENTS;
336
+ interface Logger {
337
+ debug?(message: string, context?: Record<string, unknown>): void;
338
+ info?(message: string, context?: Record<string, unknown>): void;
339
+ warn?(message: string, context?: Record<string, unknown>): void;
340
+ error?(message: string, context?: Record<string, unknown>): void;
341
+ }
342
+ interface RetryOptions {
343
+ /** Ritentativi massimi dopo il primo tentativo (default 3). */
344
+ maxRetries?: number;
345
+ /** Prima attesa in ms, poi raddoppia con jitter (default 500). */
346
+ baseDelayMs?: number;
347
+ /** Attesa massima tra due tentativi (default 10000). */
348
+ maxDelayMs?: number;
349
+ /**
350
+ * Metodi ritentati su errori temporanei (rete, 429, 502/503/504). Default solo letture:
351
+ * una ricerca (POST) costa crediti e non va rilanciata alla cieca.
352
+ */
353
+ methods?: Array<'GET' | 'HEAD' | 'PUT' | 'DELETE' | 'POST' | 'PATCH'>;
354
+ /** Stati HTTP considerati temporanei (default 408, 425, 429, 500, 502, 503, 504). */
355
+ statuses?: number[];
356
+ }
357
+ interface PollingOptions {
358
+ /** Intervallo iniziale del polling in ms (default 2000). */
359
+ intervalMs?: number;
360
+ /** Intervallo massimo: il polling rallenta da solo nelle attese lunghe (default 15000). */
361
+ maxIntervalMs?: number;
362
+ /** Fattore di rallentamento a ogni giro (default 1.5). */
363
+ backoffFactor?: number;
364
+ }
365
+ interface RealtimeOptions {
366
+ /** false = mai socket, solo polling (default true se pusher-js e' disponibile). */
367
+ enabled?: boolean;
368
+ key?: string;
369
+ wsHost?: string;
370
+ wsPort?: number;
371
+ forceTLS?: boolean;
372
+ cluster?: string;
373
+ /** Endpoint di autorizzazione dei canali privati (default `${baseUrl}/broadcasting/auth`). */
374
+ authEndpoint?: string;
375
+ /**
376
+ * Costruttore Pusher da usare (es. `import Pusher from 'pusher-js'`). Se manca, l'SDK
377
+ * prova a importare pusher-js da solo.
378
+ */
379
+ Pusher?: PusherConstructor;
380
+ /** Opzioni extra passate a pusher-js. */
381
+ pusherOptions?: Record<string, unknown>;
382
+ }
383
+ type PusherConstructor = new (key: string, options: Record<string, unknown>) => unknown;
384
+ /**
385
+ * Utente per conto del quale chiama un partner SSO (header X-Dokicasa-User):
386
+ * - stringa gia' pronta: `'wikicasa:98765'` o `'email:mario@agenzia.it'`;
387
+ * - `{ source: 'wikicasa', id: 98765 }` -> `wikicasa:98765`;
388
+ * - `{ email: 'mario@agenzia.it' }` -> `email:mario@agenzia.it`.
389
+ */
390
+ type ActingUser = string | {
391
+ source: string;
392
+ id: string | number;
393
+ } | {
394
+ email: string;
395
+ };
396
+ declare function formatActingUser(user: ActingUser): string;
397
+ interface ClientOptions {
398
+ /** Token API (Bearer). In alternativa `getToken`. */
399
+ token?: string;
400
+ /** Funzione che restituisce il token (es. letto da storage o rinnovato). */
401
+ getToken?: () => string | null | undefined | Promise<string | null | undefined>;
402
+ /** Ambiente preimpostato (default production). */
403
+ environment?: EnvironmentName;
404
+ /** URL base dell'API: sovrascrive quello dell'ambiente. */
405
+ baseUrl?: string;
406
+ /** Timeout di ogni chiamata HTTP in ms (default 60000). */
407
+ timeoutMs?: number;
408
+ retry?: RetryOptions | false;
409
+ polling?: PollingOptions;
410
+ realtime?: RealtimeOptions | false;
411
+ /** Header aggiunti a ogni chiamata. */
412
+ headers?: Record<string, string>;
413
+ /** Partner SSO: chiama per conto di questo utente (vedi ActingUser). Anche `client.as(...)`. */
414
+ actingUser?: ActingUser;
415
+ /** Nome dell'header per actingUser (default X-Dokicasa-User). */
416
+ actingUserHeader?: string;
417
+ /** Implementazione di fetch (default globalThis.fetch). */
418
+ fetch?: typeof fetch;
419
+ logger?: Logger;
420
+ /** Hook prima di ogni chiamata (log, tracciamento, header dinamici). */
421
+ onRequest?: (request: HttpRequestInfo) => void | Promise<void>;
422
+ /** Hook dopo ogni risposta, anche di errore. */
423
+ onResponse?: (response: HttpResponseInfo) => void | Promise<void>;
424
+ }
425
+ interface ResolvedConfig {
426
+ baseUrl: string;
427
+ timeoutMs: number;
428
+ retry: Required<RetryOptions> | false;
429
+ polling: Required<PollingOptions>;
430
+ realtime: (Required<Omit<RealtimeOptions, 'Pusher' | 'pusherOptions'>> & Pick<RealtimeOptions, 'Pusher' | 'pusherOptions'>) | false;
431
+ headers: Record<string, string>;
432
+ fetch: typeof fetch;
433
+ logger: Logger;
434
+ getToken: () => Promise<string | null>;
435
+ onRequest?: ClientOptions['onRequest'];
436
+ onResponse?: ClientOptions['onResponse'];
437
+ }
438
+
439
+ /** Interfaccia minima di pusher-js usata dall'SDK (anche per i test). */
440
+ interface PusherLike {
441
+ subscribe(channelName: string): ChannelLike;
442
+ unsubscribe(channelName: string): void;
443
+ disconnect(): void;
444
+ connection: {
445
+ state: string;
446
+ bind(event: string, callback: (...args: any[]) => void): void;
447
+ unbind(event?: string, callback?: (...args: any[]) => void): void;
448
+ };
449
+ }
450
+ interface ChannelLike {
451
+ bind(event: string, callback: (data: any) => void): void;
452
+ unbind(event?: string, callback?: (data: any) => void): void;
453
+ }
454
+ interface SubscriptionCallbacks {
455
+ /** Canale autorizzato e attivo. */
456
+ onSubscribed?: () => void;
457
+ /** Socket non disponibile o canale negato: chi aspetta passa al polling. */
458
+ onUnavailable?: (reason: string) => void;
459
+ }
460
+ /** Notifica a comparsa per l'utente (canale private-App.Models.User.{id}). */
461
+ interface UserToastEvent {
462
+ level: 'success' | 'info' | 'warning' | 'error' | string;
463
+ title?: string | null;
464
+ message: string;
465
+ url?: string | null;
466
+ }
467
+ interface PropertyHistoryEvent {
468
+ scanner_immobile_id: number;
469
+ status: 'generating' | 'ready' | 'failed';
470
+ stage?: string;
471
+ error_code?: string;
472
+ error?: string;
473
+ message?: string;
474
+ resource_url?: string;
475
+ }
476
+ interface UserEventHandlers {
477
+ onToast?: (event: UserToastEvent) => void;
478
+ onPropertyHistory?: (event: PropertyHistoryEvent) => void;
479
+ onAmlReport?: (event: Record<string, unknown>) => void;
480
+ /** Qualsiasi altro evento del canale utente. */
481
+ onEvent?: (eventName: string, data: unknown) => void;
482
+ }
483
+ type ConnectionState = 'initialized' | 'connecting' | 'connected' | 'unavailable' | 'failed' | 'disconnected' | string;
484
+ /**
485
+ * Aggiornamenti in tempo reale via Laravel Reverb (protocollo Pusher).
486
+ * La connessione parte al primo utilizzo; i canali sono condivisi e chiusi quando
487
+ * l'ultimo ascoltatore si stacca. Il socket e' "best effort": chi aspetta un risultato
488
+ * deve avere sempre il polling come riserva (lo fa ScannerResource.wait).
489
+ */
490
+ declare class RealtimeClient {
491
+ private readonly config;
492
+ private readonly http;
493
+ private pusher;
494
+ private connecting;
495
+ private readonly channels;
496
+ private readonly stateListeners;
497
+ constructor(config: ResolvedConfig, http: HttpClient);
498
+ /** false se il realtime e' spento nelle opzioni del client. */
499
+ get enabled(): boolean;
500
+ get state(): ConnectionState;
501
+ /** Avvisa a ogni cambio di stato della connessione. Restituisce la funzione per staccarsi. */
502
+ onStateChange(listener: (state: ConnectionState) => void): () => void;
503
+ /** Apre la connessione (di solito non serve chiamarla: lo fanno le iscrizioni). */
504
+ connect(): Promise<PusherLike>;
505
+ /** Chiude la connessione e tutti i canali. */
506
+ disconnect(): void;
507
+ /**
508
+ * Avanzamento di una ricerca (canale private-scanner_request.{id}, evento
509
+ * ScannerRequestNotification). Restituisce la funzione per smettere di ascoltare.
510
+ */
511
+ scannerRequest(id: number, onProgress: (event: ScannerProgressEvent) => void, callbacks?: SubscriptionCallbacks): () => void;
512
+ /** Eventi personali dell'utente: notifiche, storia dell'immobile pronta, report AML. */
513
+ user(userId: number, handlers: UserEventHandlers, callbacks?: SubscriptionCallbacks): () => void;
514
+ /** Iscrizione generica a un canale con i suoi eventi. */
515
+ listen(channelName: string, events: Record<string, (data: any) => void>, callbacks?: SubscriptionCallbacks): () => void;
516
+ private create;
517
+ }
518
+
519
+ interface CreateScanOptions extends Pick<RequestOptions, 'signal' | 'timeoutMs' | 'headers'> {
520
+ /** Parametri in query string (es. `skip_billing` per gli usi interni). */
521
+ query?: Record<string, unknown>;
522
+ /** Controlla lo stato del servizio prima di lanciare: se e' fermo non si spendono crediti. */
523
+ checkHealth?: boolean;
524
+ }
525
+ interface WaitOptions {
526
+ signal?: AbortSignal;
527
+ /** Attesa massima in ms (default 15 minuti). */
528
+ timeoutMs?: number;
529
+ /** Ogni aggiornamento di stato/percentuale, dal socket o dal polling. */
530
+ onProgress?: (progress: ScannerProgressEvent & {
531
+ source: 'realtime' | 'polling';
532
+ }) => void;
533
+ /** false = solo polling per questa attesa. */
534
+ realtime?: boolean;
535
+ /** true (default) = ERROR/CANCELLED lanciano ScanFailedError; false = restituisce la richiesta. */
536
+ throwOnFailure?: boolean;
537
+ /** Errori consecutivi tollerati nel polling prima di arrendersi (default 5). */
538
+ maxConsecutiveErrors?: number;
539
+ }
540
+ type RunOptions = CreateScanOptions & WaitOptions;
541
+ /** Ricerche del Market Scanner: lancio, attesa, risultati, documenti, export, monitoraggio. */
542
+ declare class ScannerResource {
543
+ private readonly http;
544
+ private readonly realtime;
545
+ private readonly config;
546
+ constructor(http: HttpClient, realtime: RealtimeClient, config: ResolvedConfig);
547
+ /** Lancia una ricerca. Non aspetta il risultato: usa `run` o `wait`. */
548
+ create<T extends ScanType>(type: T, params: ScanParamsByType[T], options?: CreateScanOptions): Promise<CreatedScan>;
549
+ /** Lancia la ricerca e aspetta il risultato finale (socket + polling di riserva). */
550
+ run<T extends ScanType, R = ScanResult>(type: T, params: ScanParamsByType[T], options?: RunOptions): Promise<ScannerRequest<R>>;
551
+ get<R = ScanResult>(id: number, options?: RequestOptions): Promise<ScannerRequest<R>>;
552
+ status(id: number, options?: RequestOptions): Promise<ScannerRequestStatusInfo>;
553
+ /** Una pagina di risultati strutturati (immobili, soggetti). */
554
+ results<T = Record<string, unknown>>(id: number, query?: ResultsQuery, options?: RequestOptions): Promise<Paginated<T>>;
555
+ /** Tutti i risultati, pagina dopo pagina: `for await (const row of client.scanner.iterateResults(id))`. */
556
+ iterateResults<T = Record<string, unknown>>(id: number, query?: ResultsQuery, options?: RequestOptions): AsyncGenerator<T>;
557
+ filters(id: number, options?: RequestOptions): Promise<{
558
+ filters: Record<string, unknown>;
559
+ }>;
560
+ children(id: number, options?: RequestOptions): Promise<Paginated<ScannerRequest<ScanResult>> | ScannerRequest<ScanResult>[]>;
561
+ documents(id: number, query?: {
562
+ type?: string;
563
+ }, options?: RequestOptions): Promise<Record<string, unknown>[]>;
564
+ /** Censimenti: passa alla modalita' intestatari (PROPERTY_OWNERS). */
565
+ update(id: number, data: {
566
+ search_mode?: 'PROPERTY_OWNERS' | null;
567
+ }, options?: RequestOptions): Promise<null>;
568
+ delete(id: number, options?: RequestOptions): Promise<null>;
569
+ retry(id: number, options?: RequestOptions): Promise<{
570
+ message?: string;
571
+ }>;
572
+ /** Export Excel dei risultati, inviato per email (a pagamento). */
573
+ exportXls(id: number, filters?: Record<string, unknown>, options?: RequestOptions): Promise<{
574
+ message: string;
575
+ scheduled_at?: string;
576
+ }>;
577
+ /** Export Excel per particella, inviato per email (a pagamento). */
578
+ exportXlsParticelle(id: number, filters?: Record<string, unknown>, options?: RequestOptions): Promise<{
579
+ message: string;
580
+ }>;
581
+ /** Mette in monitoraggio immobili o soggetti della ricerca (a pagamento). `models: []` = tutti. */
582
+ monitor(id: number, data: {
583
+ models: MonitoringModel[];
584
+ name?: string;
585
+ note?: string;
586
+ is_from_censimento?: boolean;
587
+ }, options?: RequestOptions): Promise<{
588
+ total_models: number;
589
+ }>;
590
+ /** Salva immobili o soggetti nel proprio archivio. */
591
+ saveToDatabase(id: number, models: MonitoringModel[], options?: RequestOptions): Promise<unknown>;
592
+ /** Scarica il PDF di una ricerca documentale (da `result.pdf_path` o dalla richiesta). */
593
+ downloadDocument(requestOrPath: ScannerRequest | string, options?: RequestOptions): Promise<DownloadedFile>;
594
+ /** Solo ascolto dell'avanzamento in tempo reale. Restituisce la funzione per smettere. */
595
+ watch(id: number, onProgress: (event: ScannerProgressEvent) => void): () => void;
596
+ /**
597
+ * Aspetta che la ricerca arrivi a uno stato finale e restituisce la richiesta completa.
598
+ * Usa il socket se disponibile, con un controllo periodico di sicurezza (gli eventi
599
+ * possono andare persi, es. durante un riavvio del server); senza socket fa polling
600
+ * con intervalli crescenti. Errori di rete passeggeri sono tollerati.
601
+ */
602
+ wait<R = ScanResult>(id: number, options?: WaitOptions): Promise<ScannerRequest<R>>;
603
+ /** Stato del servizio per tipo; lancia ServiceUnavailableError se e' fermo. */
604
+ private assertAvailable;
605
+ }
606
+
607
+ /**
608
+ * Censimento di zona: una richiesta padre (BULK-LIST-ADDRESSES) a cui si agganciano le
609
+ * ricerche per indirizzo. Un solo censimento alla volta per utente (CensusInProgressError).
610
+ */
611
+ declare class CensusResource {
612
+ private readonly http;
613
+ private readonly scanner;
614
+ constructor(http: HttpClient, scanner: ScannerResource);
615
+ /** Apre il censimento. `searchMode: 'MULTI_ADDRESS'` = ricerca singola su piu' vie (max 5). */
616
+ create(options?: {
617
+ searchMode?: 'PROPERTY_OWNERS' | 'MULTI_ADDRESS' | null;
618
+ } & CreateScanOptions): Promise<CreatedScan>;
619
+ /** Primo passo per indirizzo: restituisce gli indirizzi catastali candidati (`result.addresses`). */
620
+ findAddresses(params: {
621
+ indirizzo: string;
622
+ comune: string;
623
+ provincia: string;
624
+ }, options?: CreateScanOptions & WaitOptions): Promise<ScannerRequest<ScanResult>>;
625
+ /** Aggiunge al censimento un indirizzo scelto tra quelli di `findAddresses`. */
626
+ addAddress(parentId: number, params: {
627
+ indirizzo: string;
628
+ comune: string;
629
+ provincia: string;
630
+ address_value: string;
631
+ numero_civico: string;
632
+ civico_a?: string;
633
+ }, options?: CreateScanOptions): Promise<CreatedScan>;
634
+ /** Passa alla ricerca degli intestatari sugli immobili trovati. */
635
+ switchToOwners(parentId: number, options?: RequestOptions): Promise<null>;
636
+ /** Aspetta la fine del censimento (tutte le ricerche figlie). */
637
+ wait(parentId: number, options?: WaitOptions): Promise<ScannerRequest>;
638
+ list(query?: {
639
+ text?: string;
640
+ page?: number;
641
+ }, options?: RequestOptions): Promise<Paginated<ScannerRequest<ScanResult>> | ScannerRequest<ScanResult>[]>;
642
+ get(id: number, options?: RequestOptions): Promise<ScannerRequest<ScanResult>>;
643
+ }
644
+ interface MonitoringListQuery {
645
+ page?: number;
646
+ type?: 'IMMOBILE' | 'SOGGETTO';
647
+ source?: string;
648
+ status?: string;
649
+ text?: string;
650
+ change_owner?: boolean;
651
+ sort_ends_at?: 'asc' | 'desc';
652
+ }
653
+ /** Monitoraggi di immobili e soggetti (avvisi di variazione). */
654
+ declare class MonitoringsResource {
655
+ private readonly http;
656
+ constructor(http: HttpClient);
657
+ list(query?: MonitoringListQuery, options?: RequestOptions): Promise<Paginated<Record<string, unknown>>>;
658
+ ids(options?: RequestOptions): Promise<number[] | Record<string, unknown>>;
659
+ get(id: number, options?: RequestOptions): Promise<Record<string, unknown>>;
660
+ delete(id: number, options?: RequestOptions): Promise<null>;
661
+ renew(id: number, options?: RequestOptions): Promise<Record<string, unknown>>;
662
+ setNote(id: number, note: string, options?: RequestOptions): Promise<Record<string, unknown>>;
663
+ setWebhook(id: number, webhookUrl: string | null, options?: RequestOptions): Promise<Record<string, unknown>>;
664
+ reactivateAll(options?: RequestOptions): Promise<Record<string, unknown>>;
665
+ /** Mette in monitoraggio un immobile a partire dai dati catastali (a pagamento). */
666
+ fromCatasto(params: {
667
+ foglio: string;
668
+ particella: string;
669
+ subalterno?: string;
670
+ comune: string;
671
+ provincia: string;
672
+ search_catasto_type?: 'F' | 'T';
673
+ sezione_comune?: string;
674
+ name?: string;
675
+ note?: string;
676
+ webhook_url?: string;
677
+ }, options?: RequestOptions): Promise<{
678
+ immobile_id: number;
679
+ user_monitoring_id: number;
680
+ created: boolean;
681
+ scanned: boolean;
682
+ last_monitoring?: string | null;
683
+ next_monitoring?: string | null;
684
+ }>;
685
+ }
686
+ /** Conto dell'utente: wallet, movimenti, crediti. */
687
+ declare class AccountResource {
688
+ private readonly http;
689
+ constructor(http: HttpClient);
690
+ wallet(options?: RequestOptions): Promise<Wallet>;
691
+ walletTransactions(query?: {
692
+ page?: number;
693
+ per_page?: number;
694
+ }, options?: RequestOptions): Promise<Paginated<Record<string, unknown>>>;
695
+ credits(options?: RequestOptions): Promise<Record<string, unknown>>;
696
+ /** Crediti, wallet e abbonamenti in una chiamata. */
697
+ overview(options?: RequestOptions): Promise<Record<string, unknown>>;
698
+ }
699
+ /** Stato del servizio e catalogo prezzi. */
700
+ declare class SystemResource {
701
+ private readonly http;
702
+ constructor(http: HttpClient);
703
+ /** Stato di Sister e della coda, anche per tipo di ricerca. */
704
+ health(options?: RequestOptions): Promise<ScannerHealth>;
705
+ /** Problemi noti su Sister (banner). */
706
+ heartbeat(options?: RequestOptions): Promise<{
707
+ [k: string]: unknown;
708
+ has_sister_problems: boolean;
709
+ sister_maintenance?: unknown;
710
+ }>;
711
+ /** Catalogo servizi: prezzo, crediti disponibili, link di acquisto per ogni tipo. */
712
+ services(options?: RequestOptions): Promise<Record<string, ServiceCatalogItem>>;
713
+ /** true se il Market Scanner e' disattivato dall'amministrazione. */
714
+ isMarketScannerDisabled(options?: RequestOptions): Promise<boolean>;
715
+ }
716
+
717
+ /**
718
+ * Client DokiCasa.
719
+ *
720
+ * ```ts
721
+ * const dk = new DokicasaClient({ token: process.env.DOKICASA_TOKEN, environment: 'sandbox' });
722
+ * const visura = await dk.scanner.run('visura-catasto', { ... }, { onProgress: (p) => console.log(p.percentage) });
723
+ * const file = await dk.scanner.downloadDocument(visura);
724
+ * ```
725
+ */
726
+ declare class DokicasaClient {
727
+ private readonly options;
728
+ readonly config: ResolvedConfig;
729
+ readonly http: HttpClient;
730
+ readonly realtime: RealtimeClient;
731
+ readonly scanner: ScannerResource;
732
+ readonly census: CensusResource;
733
+ readonly monitorings: MonitoringsResource;
734
+ readonly account: AccountResource;
735
+ readonly system: SystemResource;
736
+ constructor(options: ClientOptions);
737
+ /**
738
+ * Copia del client che chiama per conto di un utente (partner SSO, header X-Dokicasa-User).
739
+ * Stesse opzioni, socket a parte: anche l'autorizzazione dei canali passa l'header.
740
+ *
741
+ * ```ts
742
+ * const agente = dk.as({ source: 'wikicasa', id: 98765 });
743
+ * await agente.account.wallet();
744
+ * ```
745
+ */
746
+ as(user: ActingUser): DokicasaClient;
747
+ /** Chiude il socket (da chiamare quando non serve piu', es. allo smontaggio dell'app). */
748
+ close(): void;
749
+ }
750
+ declare function createClient(options: ClientOptions): DokicasaClient;
751
+
752
+ /**
753
+ * Errori dell'SDK. Tutti estendono DokicasaError: chi integra puo' intercettare il caso
754
+ * specifico con instanceof (es. InsufficientFundsError) o leggere `code` e `status`.
755
+ */
756
+ declare class DokicasaError extends Error {
757
+ /** Codice applicativo (es. AMOUNT_NOT_ENOUGH) o tecnico (es. TIMEOUT). */
758
+ readonly code: string;
759
+ constructor(message: string, code?: string, options?: {
760
+ cause?: unknown;
761
+ });
762
+ }
763
+ /** Risposta HTTP con esito di errore. */
764
+ declare class ApiError extends DokicasaError {
765
+ readonly status: number;
766
+ /** Corpo della risposta (JSON se possibile, altrimenti testo). */
767
+ readonly body: unknown;
768
+ readonly method: string;
769
+ readonly url: string;
770
+ constructor(params: {
771
+ message: string;
772
+ code: string;
773
+ status: number;
774
+ body: unknown;
775
+ method: string;
776
+ url: string;
777
+ });
778
+ }
779
+ /** 401: token mancante, scaduto o non valido. */
780
+ declare class AuthenticationError extends ApiError {
781
+ }
782
+ /** 403: risorsa di un altro utente, origine non abilitata, listino partner mancante. */
783
+ declare class PermissionError extends ApiError {
784
+ }
785
+ /** 403 PARTNER_PRICING_REQUIRED: il partner non ha un listino per questo tipo di ricerca. */
786
+ declare class PartnerPricingRequiredError extends PermissionError {
787
+ get scannerType(): string | undefined;
788
+ }
789
+ /** 404 */
790
+ declare class NotFoundError extends ApiError {
791
+ }
792
+ /** 422: dati non validi. `fields` ha i messaggi per campo. */
793
+ declare class ValidationError extends ApiError {
794
+ get fields(): Record<string, string[]>;
795
+ /** Richiesta identica gia' in corso o appena fatta: non e' un errore vero. */
796
+ get isDuplicate(): boolean;
797
+ }
798
+ /** 400 AMOUNT_NOT_ENOUGH: crediti o saldo insufficienti. */
799
+ declare class InsufficientFundsError extends ApiError {
800
+ private get data();
801
+ get missingAmount(): number | undefined;
802
+ get walletBalance(): number | undefined;
803
+ get totalAmount(): number | undefined;
804
+ /** Link per acquistare crediti. */
805
+ get checkoutLink(): string | undefined;
806
+ }
807
+ /** 400 PENDING_CENSIMENTO: c'e' gia' un censimento in corso per l'utente. */
808
+ declare class CensusInProgressError extends ApiError {
809
+ }
810
+ /** Sister/Agenzia delle Entrate fermo, in manutenzione o sovraccarico (SISTER_FORCE_BLOCK, SISTER_PROBLEM, 503). */
811
+ declare class ServiceUnavailableError extends ApiError {
812
+ }
813
+ /** 429: troppe richieste. `retryAfterSeconds` dice quando riprovare. */
814
+ declare class RateLimitError extends ApiError {
815
+ readonly retryAfterSeconds: number | null;
816
+ constructor(params: ConstructorParameters<typeof ApiError>[0] & {
817
+ retryAfterSeconds: number | null;
818
+ });
819
+ }
820
+ /** Errore lato server (5xx) dopo eventuali ritentativi. */
821
+ declare class ServerError extends ApiError {
822
+ }
823
+ /** La richiesta HTTP non e' arrivata (rete, DNS, CORS...). */
824
+ declare class NetworkError extends DokicasaError {
825
+ constructor(message: string, cause?: unknown);
826
+ }
827
+ /** Tempo scaduto: della singola chiamata HTTP o dell'attesa di una ricerca. */
828
+ declare class TimeoutError extends DokicasaError {
829
+ constructor(message: string);
830
+ }
831
+ /** Operazione annullata dal chiamante (AbortSignal). */
832
+ declare class AbortError extends DokicasaError {
833
+ constructor(message?: string);
834
+ }
835
+ /** Ricerca terminata in ERROR o CANCELLED mentre la si aspettava. */
836
+ declare class ScanFailedError extends DokicasaError {
837
+ readonly request: {
838
+ id: number;
839
+ status: string;
840
+ details?: string | null;
841
+ [k: string]: unknown;
842
+ };
843
+ constructor(request: {
844
+ id: number;
845
+ status: string;
846
+ details?: string | null;
847
+ [k: string]: unknown;
848
+ });
849
+ }
850
+ /** Errore del canale realtime (configurazione mancante, pusher-js non installato, auth negata). */
851
+ declare class RealtimeError extends DokicasaError {
852
+ constructor(message: string, cause?: unknown);
853
+ }
854
+ /** Costruisce l'errore giusto da una risposta HTTP non riuscita. */
855
+ declare function errorFromResponse(params: {
856
+ status: number;
857
+ body: unknown;
858
+ method: string;
859
+ url: string;
860
+ retryAfterSeconds: number | null;
861
+ }): ApiError;
862
+
863
+ /**
864
+ * Verifica dei webhook di DokiCasa: l'header `Signature` e' l'HMAC-SHA256 (esadecimale)
865
+ * del corpo grezzo della richiesta, con chiave il token API del destinatario.
866
+ * Va calcolato sul corpo cosi' come arriva (stringa o byte), prima di fare JSON.parse.
867
+ */
868
+ declare function verifyWebhookSignature(params: {
869
+ body: string | ArrayBuffer | Uint8Array;
870
+ signature: string | null | undefined;
871
+ secret: string;
872
+ }): Promise<boolean>;
873
+ /** Come verifyWebhookSignature ma restituisce il JSON gia' letto, o lancia se la firma non torna. */
874
+ declare function parseWebhook<T = Record<string, unknown>>(params: {
875
+ body: string | ArrayBuffer | Uint8Array;
876
+ signature: string | null | undefined;
877
+ secret: string;
878
+ }): Promise<T>;
879
+
880
+ export { AbortError, AccountResource, type ActingUser, ApiError, AuthenticationError, type CatastoType, CensusInProgressError, CensusResource, type ChannelLike, type ClientOptions, type CommonScanParams, type ConnectionState, type CreateScanOptions, type CreatedScan, DokicasaClient, DokicasaError, type DownloadedFile, ENVIRONMENTS, type EnvironmentName, FINAL_STATUSES, type HttpMethod, type HttpRequestInfo, type HttpResponseInfo, InsufficientFundsError, type Logger, type MonitoringListQuery, type MonitoringModel, MonitoringsResource, NetworkError, NotFoundError, type Paginated, type ParcelParams, PartnerPricingRequiredError, PermissionError, type PollingOptions, type PropertyHistoryEvent, type PusherConstructor, type PusherLike, RateLimitError, RealtimeClient, RealtimeError, type RealtimeOptions, type RequestOptions, type ResultsQuery, type RetryOptions, type RunOptions, ScanFailedError, type ScanParamsByType, type ScanResult, type ScanType, type ScannerHealth, type ScannerProgressEvent, type ScannerRequest, type ScannerRequestStatus, type ScannerRequestStatusInfo, ScannerResource, ServerError, type ServiceCatalogItem, ServiceUnavailableError, type SubscriptionCallbacks, SystemResource, TimeoutError, type UserEventHandlers, type UserToastEvent, ValidationError, type WaitOptions, type Wallet, createClient, errorFromResponse, formatActingUser, isFinalStatus, parseWebhook, verifyWebhookSignature };