@emisso/sii-api 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1043 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc2) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ConflictError: () => ConflictError,
24
+ DbError: () => DbError,
25
+ ForbiddenError: () => ForbiddenError,
26
+ ListInvoicesQuerySchema: () => ListInvoicesQuerySchema,
27
+ NotFoundError: () => NotFoundError,
28
+ SaveCredentialsSchema: () => SaveCredentialsSchema,
29
+ SiiAuthError: () => SiiAuthError,
30
+ SyncInvoicesSchema: () => SyncInvoicesSchema,
31
+ SyncStatusQuerySchema: () => SyncStatusQuerySchema,
32
+ ValidationError: () => ValidationError,
33
+ createAuthHandlers: () => createAuthHandlers,
34
+ createAuthService: () => createAuthService,
35
+ createCredentialRepo: () => createCredentialRepo,
36
+ createCredentialService: () => createCredentialService,
37
+ createInvoiceHandlers: () => createInvoiceHandlers,
38
+ createInvoiceRepo: () => createInvoiceRepo,
39
+ createInvoiceService: () => createInvoiceService,
40
+ createRouter: () => createRouter,
41
+ createSyncJobRepo: () => createSyncJobRepo,
42
+ createTokenCacheRepo: () => createTokenCacheRepo,
43
+ createdResponse: () => createdResponse,
44
+ credentials: () => credentials,
45
+ handleEffect: () => handleEffect,
46
+ invoiceToRow: () => invoiceToRow,
47
+ invoices: () => invoices,
48
+ isAppError: () => isAppError,
49
+ jsonResponse: () => jsonResponse,
50
+ noContentResponse: () => noContentResponse,
51
+ queryOneOrFail: () => queryOneOrFail,
52
+ rowToInvoice: () => rowToInvoice,
53
+ serializeAppError: () => serializeAppError,
54
+ siiSchema: () => siiSchema,
55
+ syncJobs: () => syncJobs,
56
+ toErrorResponse: () => toErrorResponse,
57
+ toErrorResponseFromUnknown: () => toErrorResponseFromUnknown,
58
+ tokenCache: () => tokenCache
59
+ });
60
+ module.exports = __toCommonJS(index_exports);
61
+
62
+ // src/db/schema/index.ts
63
+ var import_pg_core5 = require("drizzle-orm/pg-core");
64
+
65
+ // src/db/schema/credentials.ts
66
+ var import_pg_core = require("drizzle-orm/pg-core");
67
+ var credentials = siiSchema.table(
68
+ "credentials",
69
+ {
70
+ id: (0, import_pg_core.uuid)("id").defaultRandom().primaryKey(),
71
+ tenantId: (0, import_pg_core.uuid)("tenant_id").notNull(),
72
+ // NOTE: `env` is typed as SiiEnv at the application layer via Drizzle's $type<>().
73
+ // A DB-level CHECK constraint (env IN ('production','certification')) should be
74
+ // added via a future migration to enforce this at the database level as well.
75
+ env: (0, import_pg_core.text)("env").notNull().$type(),
76
+ // TODO: ENCRYPT AT REST — these fields store sensitive SII credentials.
77
+ // Must implement application-level encryption (AES-256-GCM) before production.
78
+ certBase64: (0, import_pg_core.text)("cert_base64"),
79
+ certPassword: (0, import_pg_core.text)("cert_password"),
80
+ portalRut: (0, import_pg_core.text)("portal_rut"),
81
+ // TODO: ENCRYPT AT REST — portal password stores sensitive SII credentials.
82
+ // Must implement application-level encryption (AES-256-GCM) before production.
83
+ portalPassword: (0, import_pg_core.text)("portal_password"),
84
+ createdAt: (0, import_pg_core.timestamp)("created_at").notNull().defaultNow(),
85
+ updatedAt: (0, import_pg_core.timestamp)("updated_at").notNull().defaultNow()
86
+ },
87
+ (table) => [(0, import_pg_core.unique)("uq_credentials_tenant_env").on(table.tenantId, table.env)]
88
+ );
89
+
90
+ // src/db/schema/token-cache.ts
91
+ var import_pg_core2 = require("drizzle-orm/pg-core");
92
+ var tokenCache = siiSchema.table(
93
+ "token_cache",
94
+ {
95
+ id: (0, import_pg_core2.uuid)("id").defaultRandom().primaryKey(),
96
+ credentialId: (0, import_pg_core2.uuid)("credential_id").notNull().references(() => credentials.id, { onDelete: "cascade" }),
97
+ tokenType: (0, import_pg_core2.text)("token_type").notNull().$type(),
98
+ tokenValue: (0, import_pg_core2.text)("token_value").notNull(),
99
+ expiresAt: (0, import_pg_core2.timestamp)("expires_at", { withTimezone: true }).notNull(),
100
+ createdAt: (0, import_pg_core2.timestamp)("created_at").notNull().defaultNow()
101
+ },
102
+ (table) => [(0, import_pg_core2.unique)("uq_token_cache_cred_type").on(table.credentialId, table.tokenType)]
103
+ );
104
+
105
+ // src/db/schema/invoices.ts
106
+ var import_pg_core3 = require("drizzle-orm/pg-core");
107
+ var invoices = siiSchema.table(
108
+ "invoices",
109
+ {
110
+ id: (0, import_pg_core3.uuid)("id").defaultRandom().primaryKey(),
111
+ tenantId: (0, import_pg_core3.uuid)("tenant_id").notNull(),
112
+ documentType: (0, import_pg_core3.text)("document_type").notNull().$type(),
113
+ number: (0, import_pg_core3.integer)("number").notNull(),
114
+ issuerRut: (0, import_pg_core3.text)("issuer_rut"),
115
+ issuerName: (0, import_pg_core3.text)("issuer_name"),
116
+ receiverRut: (0, import_pg_core3.text)("receiver_rut"),
117
+ receiverName: (0, import_pg_core3.text)("receiver_name"),
118
+ date: (0, import_pg_core3.date)("date"),
119
+ netAmount: (0, import_pg_core3.numeric)("net_amount", { precision: 16, scale: 0 }),
120
+ exemptAmount: (0, import_pg_core3.numeric)("exempt_amount", { precision: 16, scale: 0 }),
121
+ vatAmount: (0, import_pg_core3.numeric)("vat_amount", { precision: 16, scale: 0 }),
122
+ totalAmount: (0, import_pg_core3.numeric)("total_amount", { precision: 16, scale: 0 }),
123
+ taxPeriodYear: (0, import_pg_core3.integer)("tax_period_year").notNull(),
124
+ taxPeriodMonth: (0, import_pg_core3.integer)("tax_period_month").notNull(),
125
+ issueType: (0, import_pg_core3.text)("issue_type").notNull().$type(),
126
+ confirmationStatus: (0, import_pg_core3.text)("confirmation_status").$type(),
127
+ raw: (0, import_pg_core3.jsonb)("raw").$type(),
128
+ createdAt: (0, import_pg_core3.timestamp)("created_at").notNull().defaultNow(),
129
+ updatedAt: (0, import_pg_core3.timestamp)("updated_at").notNull().defaultNow()
130
+ },
131
+ (table) => [
132
+ (0, import_pg_core3.unique)("uq_invoices_natural_key").on(
133
+ table.tenantId,
134
+ table.documentType,
135
+ table.number,
136
+ table.issuerRut,
137
+ table.receiverRut,
138
+ table.issueType
139
+ ),
140
+ (0, import_pg_core3.index)("idx_invoices_tenant_period").on(
141
+ table.tenantId,
142
+ table.taxPeriodYear,
143
+ table.taxPeriodMonth
144
+ )
145
+ ]
146
+ );
147
+
148
+ // src/db/schema/sync-jobs.ts
149
+ var import_pg_core4 = require("drizzle-orm/pg-core");
150
+ var syncJobs = siiSchema.table("sync_jobs", {
151
+ id: (0, import_pg_core4.uuid)("id").defaultRandom().primaryKey(),
152
+ tenantId: (0, import_pg_core4.uuid)("tenant_id").notNull(),
153
+ operation: (0, import_pg_core4.text)("operation").notNull().$type(),
154
+ periodYear: (0, import_pg_core4.integer)("period_year").notNull(),
155
+ periodMonth: (0, import_pg_core4.integer)("period_month").notNull(),
156
+ issueType: (0, import_pg_core4.text)("issue_type").notNull().$type(),
157
+ status: (0, import_pg_core4.text)("status").notNull().default("pending").$type(),
158
+ startedAt: (0, import_pg_core4.timestamp)("started_at"),
159
+ completedAt: (0, import_pg_core4.timestamp)("completed_at"),
160
+ recordsFetched: (0, import_pg_core4.integer)("records_fetched"),
161
+ errorMessage: (0, import_pg_core4.text)("error_message"),
162
+ createdAt: (0, import_pg_core4.timestamp)("created_at").notNull().defaultNow()
163
+ });
164
+
165
+ // src/db/schema/index.ts
166
+ var siiSchema = (0, import_pg_core5.pgSchema)("sii");
167
+
168
+ // src/core/effect/app-error.ts
169
+ var import_effect = require("effect");
170
+ var NotFoundError = class _NotFoundError extends import_effect.Data.TaggedError("NotFoundError") {
171
+ static make(entity, entityId) {
172
+ return new _NotFoundError({
173
+ message: `${entity} not found${entityId ? `: ${entityId}` : ""}`,
174
+ entity,
175
+ entityId
176
+ });
177
+ }
178
+ };
179
+ var ValidationError = class _ValidationError extends import_effect.Data.TaggedError("ValidationError") {
180
+ static make(message, field, details) {
181
+ return new _ValidationError({
182
+ message,
183
+ field,
184
+ details
185
+ });
186
+ }
187
+ static fromZodErrors(message, issues) {
188
+ return new _ValidationError({
189
+ message,
190
+ fieldErrors: issues.map((i) => ({
191
+ path: i.path.join("."),
192
+ message: i.message
193
+ }))
194
+ });
195
+ }
196
+ };
197
+ var ForbiddenError = class _ForbiddenError extends import_effect.Data.TaggedError("ForbiddenError") {
198
+ static make(message = "Forbidden", requiredPermission) {
199
+ return new _ForbiddenError({
200
+ message,
201
+ requiredPermission
202
+ });
203
+ }
204
+ };
205
+ var DbError = class _DbError extends import_effect.Data.TaggedError("DbError") {
206
+ static make(operation, cause) {
207
+ const message = cause instanceof Error ? cause.message : "Database operation failed";
208
+ return new _DbError({
209
+ message,
210
+ operation,
211
+ cause
212
+ });
213
+ }
214
+ };
215
+ var ConflictError = class _ConflictError extends import_effect.Data.TaggedError("ConflictError") {
216
+ static make(message, resource, conflictingValue) {
217
+ return new _ConflictError({
218
+ message,
219
+ resource,
220
+ conflictingValue
221
+ });
222
+ }
223
+ };
224
+ var SiiAuthError = class _SiiAuthError extends import_effect.Data.TaggedError("SiiAuthError") {
225
+ static make(message, cause) {
226
+ return new _SiiAuthError({
227
+ message,
228
+ cause
229
+ });
230
+ }
231
+ };
232
+ function isAppError(error) {
233
+ return error instanceof NotFoundError || error instanceof ValidationError || error instanceof ForbiddenError || error instanceof DbError || error instanceof ConflictError || error instanceof SiiAuthError;
234
+ }
235
+ function serializeAppError(error) {
236
+ const result = {
237
+ _type: error._tag,
238
+ message: error.message
239
+ };
240
+ switch (error._tag) {
241
+ case "NotFoundError":
242
+ if (error.entity) result.entity = error.entity;
243
+ if (error.entityId) result.entityId = error.entityId;
244
+ break;
245
+ case "ValidationError":
246
+ if (error.field) result.field = error.field;
247
+ if (error.details) result.details = error.details;
248
+ if (error.fieldErrors) result.fieldErrors = error.fieldErrors;
249
+ break;
250
+ case "ForbiddenError":
251
+ if (error.requiredPermission)
252
+ result.requiredPermission = error.requiredPermission;
253
+ break;
254
+ case "DbError":
255
+ if (error.operation) result.operation = error.operation;
256
+ break;
257
+ case "ConflictError":
258
+ if (error.resource) result.resource = error.resource;
259
+ if (error.conflictingValue)
260
+ result.conflictingValue = error.conflictingValue;
261
+ break;
262
+ case "SiiAuthError":
263
+ break;
264
+ default: {
265
+ const _exhaustive = error;
266
+ return result;
267
+ }
268
+ }
269
+ return result;
270
+ }
271
+
272
+ // src/core/effect/http-response.ts
273
+ var import_effect2 = require("effect");
274
+ var STATUS_MAP = {
275
+ ValidationError: 400,
276
+ ForbiddenError: 403,
277
+ NotFoundError: 404,
278
+ ConflictError: 409,
279
+ SiiAuthError: 502,
280
+ DbError: 500
281
+ };
282
+ function toErrorResponse(error) {
283
+ const status = STATUS_MAP[error._tag] ?? 500;
284
+ const body = serializeAppError(error);
285
+ return Response.json({ error: body }, { status });
286
+ }
287
+ function extractAppError(error) {
288
+ if (isAppError(error)) return error;
289
+ const cause = error?.cause;
290
+ if (cause) {
291
+ const inner = cause?.error;
292
+ if (isAppError(inner)) return inner;
293
+ }
294
+ return null;
295
+ }
296
+ function toErrorResponseFromUnknown(error) {
297
+ const appError = extractAppError(error);
298
+ if (appError) return toErrorResponse(appError);
299
+ console.error("[sii-api] Unhandled error:", error);
300
+ return Response.json(
301
+ { error: { _type: "InternalError", message: "Internal server error" } },
302
+ { status: 500 }
303
+ );
304
+ }
305
+ function handleEffect(effect, toResponse = jsonResponse) {
306
+ return import_effect2.Effect.runPromise(
307
+ effect.pipe(
308
+ import_effect2.Effect.map(toResponse),
309
+ import_effect2.Effect.catchAll((err) => import_effect2.Effect.succeed(toErrorResponse(err)))
310
+ )
311
+ );
312
+ }
313
+ function jsonResponse(data, status = 200) {
314
+ return Response.json(data, { status });
315
+ }
316
+ function createdResponse(data) {
317
+ return Response.json(data, { status: 201 });
318
+ }
319
+ function noContentResponse() {
320
+ return new Response(null, { status: 204 });
321
+ }
322
+
323
+ // src/core/effect/repo-helpers.ts
324
+ var import_effect3 = require("effect");
325
+ function queryOneOrFail(operation, entity, entityId, query) {
326
+ return import_effect3.Effect.tryPromise({
327
+ try: query,
328
+ catch: (e) => DbError.make(operation, e)
329
+ }).pipe(
330
+ import_effect3.Effect.flatMap(
331
+ (row) => row ? import_effect3.Effect.succeed(row) : import_effect3.Effect.fail(NotFoundError.make(entity, entityId))
332
+ )
333
+ );
334
+ }
335
+
336
+ // src/core/bridge.ts
337
+ function invoiceToRow(tenantId, invoice, issueType) {
338
+ return {
339
+ tenantId,
340
+ documentType: invoice.documentType,
341
+ number: invoice.number,
342
+ issuerRut: invoice.issuer.rut || null,
343
+ issuerName: invoice.issuer.name || null,
344
+ receiverRut: invoice.receiver.rut || null,
345
+ receiverName: invoice.receiver.name || null,
346
+ date: invoice.date || null,
347
+ netAmount: String(invoice.netAmount),
348
+ exemptAmount: String(invoice.exemptAmount),
349
+ vatAmount: String(invoice.vatAmount),
350
+ totalAmount: String(invoice.totalAmount),
351
+ taxPeriodYear: invoice.taxPeriod.year,
352
+ taxPeriodMonth: invoice.taxPeriod.month,
353
+ issueType,
354
+ confirmationStatus: invoice.confirmationStatus ?? null,
355
+ raw: invoice.raw ?? null
356
+ };
357
+ }
358
+ function rowToInvoice(row) {
359
+ return {
360
+ id: `${row.documentType}-${row.number}-${row.issuerRut || row.receiverRut || ""}`,
361
+ number: row.number,
362
+ issuer: {
363
+ rut: row.issuerRut ?? "",
364
+ name: row.issuerName ?? ""
365
+ },
366
+ receiver: {
367
+ rut: row.receiverRut ?? "",
368
+ name: row.receiverName ?? ""
369
+ },
370
+ date: row.date ?? "",
371
+ netAmount: Number(row.netAmount ?? 0),
372
+ exemptAmount: Number(row.exemptAmount ?? 0),
373
+ vatAmount: Number(row.vatAmount ?? 0),
374
+ totalAmount: Number(row.totalAmount ?? 0),
375
+ currency: "CLP",
376
+ taxPeriod: {
377
+ year: row.taxPeriodYear,
378
+ month: row.taxPeriodMonth
379
+ },
380
+ documentType: row.documentType,
381
+ confirmationStatus: row.confirmationStatus ?? "REGISTRO",
382
+ raw: row.raw ?? {}
383
+ };
384
+ }
385
+
386
+ // src/validation/schemas.ts
387
+ var import_zod = require("zod");
388
+ var import_sii = require("@emisso/sii");
389
+ var SaveCredentialsSchema = import_zod.z.object({
390
+ env: import_sii.SiiEnvSchema.default("production"),
391
+ certBase64: import_zod.z.string().optional(),
392
+ certPassword: import_zod.z.string().optional(),
393
+ portalRut: import_zod.z.string().optional(),
394
+ portalPassword: import_zod.z.string().optional()
395
+ }).refine(
396
+ (d) => d.certBase64 || d.certPassword || (d.portalRut || d.portalPassword),
397
+ { message: "At least one credential pair is required: certificate (certBase64 + certPassword) or portal (portalRut + portalPassword)" }
398
+ ).refine(
399
+ (d) => !d.certBase64 && !d.certPassword || d.certBase64 && d.certPassword,
400
+ { message: "certBase64 and certPassword must both be provided or both omitted" }
401
+ ).refine(
402
+ (d) => !d.portalRut && !d.portalPassword || d.portalRut && d.portalPassword,
403
+ { message: "portalRut and portalPassword must both be provided or both omitted" }
404
+ );
405
+ var SyncInvoicesSchema = import_zod.z.object({
406
+ period: import_zod.z.string().regex(/^\d{4}-\d{2}$/, "Period must be YYYY-MM format"),
407
+ type: import_sii.IssueTypeSchema.default("received")
408
+ });
409
+ var ListInvoicesQuerySchema = import_zod.z.object({
410
+ period: import_zod.z.string().regex(/^\d{4}-\d{2}$/).optional(),
411
+ type: import_sii.IssueTypeSchema.optional(),
412
+ documentType: import_sii.DteTypeSchema.optional(),
413
+ limit: import_zod.z.coerce.number().int().positive().max(1e3).default(100),
414
+ offset: import_zod.z.coerce.number().int().nonnegative().default(0)
415
+ });
416
+ var SyncStatusQuerySchema = import_zod.z.object({
417
+ period: import_zod.z.string().regex(/^\d{4}-\d{2}$/).optional(),
418
+ type: import_sii.IssueTypeSchema.optional()
419
+ });
420
+
421
+ // src/repos/credential-repo.ts
422
+ var import_effect4 = require("effect");
423
+ var import_drizzle_orm = require("drizzle-orm");
424
+ function createCredentialRepo(db) {
425
+ return {
426
+ getByTenantAndEnv(tenantId, env) {
427
+ return queryOneOrFail(
428
+ "credential.getByTenantAndEnv",
429
+ "Credential",
430
+ `${tenantId}/${env}`,
431
+ () => db.select().from(credentials).where(
432
+ (0, import_drizzle_orm.and)(
433
+ (0, import_drizzle_orm.eq)(credentials.tenantId, tenantId),
434
+ (0, import_drizzle_orm.eq)(credentials.env, env)
435
+ )
436
+ ).then((rows) => rows[0])
437
+ );
438
+ },
439
+ upsert(tenantId, data) {
440
+ return import_effect4.Effect.tryPromise({
441
+ try: () => db.insert(credentials).values({ ...data, tenantId }).onConflictDoUpdate({
442
+ target: [credentials.tenantId, credentials.env],
443
+ set: { ...data, updatedAt: /* @__PURE__ */ new Date() }
444
+ }).returning().then((rows) => rows[0]),
445
+ catch: (e) => DbError.make("credential.upsert", e)
446
+ });
447
+ },
448
+ delete(tenantId, env) {
449
+ return import_effect4.Effect.tryPromise({
450
+ try: () => db.delete(credentials).where(
451
+ (0, import_drizzle_orm.and)(
452
+ (0, import_drizzle_orm.eq)(credentials.tenantId, tenantId),
453
+ (0, import_drizzle_orm.eq)(credentials.env, env)
454
+ )
455
+ ).returning().then((rows) => rows.length > 0),
456
+ catch: (e) => DbError.make("credential.delete", e)
457
+ });
458
+ }
459
+ };
460
+ }
461
+
462
+ // src/repos/token-cache-repo.ts
463
+ var import_effect5 = require("effect");
464
+ var import_drizzle_orm2 = require("drizzle-orm");
465
+ function createTokenCacheRepo(db) {
466
+ return {
467
+ get(credentialId, tokenType) {
468
+ return import_effect5.Effect.tryPromise({
469
+ try: () => db.select().from(tokenCache).where(
470
+ (0, import_drizzle_orm2.and)(
471
+ (0, import_drizzle_orm2.eq)(tokenCache.credentialId, credentialId),
472
+ (0, import_drizzle_orm2.eq)(tokenCache.tokenType, tokenType)
473
+ )
474
+ ).then((rows) => rows[0] ?? null),
475
+ catch: (e) => DbError.make("tokenCache.get", e)
476
+ });
477
+ },
478
+ upsert(credentialId, tokenType, tokenValue, expiresAt) {
479
+ return import_effect5.Effect.tryPromise({
480
+ try: () => db.insert(tokenCache).values({ credentialId, tokenType, tokenValue, expiresAt }).onConflictDoUpdate({
481
+ target: [tokenCache.credentialId, tokenCache.tokenType],
482
+ set: { tokenValue, expiresAt, createdAt: /* @__PURE__ */ new Date() }
483
+ }).returning().then((rows) => rows[0]),
484
+ catch: (e) => DbError.make("tokenCache.upsert", e)
485
+ });
486
+ },
487
+ deleteByCredential(credentialId) {
488
+ return import_effect5.Effect.tryPromise({
489
+ try: () => db.delete(tokenCache).where((0, import_drizzle_orm2.eq)(tokenCache.credentialId, credentialId)).then(() => void 0),
490
+ catch: (e) => DbError.make("tokenCache.deleteByCredential", e)
491
+ });
492
+ }
493
+ };
494
+ }
495
+
496
+ // src/repos/invoice-repo.ts
497
+ var import_effect6 = require("effect");
498
+ var import_drizzle_orm3 = require("drizzle-orm");
499
+ function createInvoiceRepo(db) {
500
+ return {
501
+ list(tenantId, filters) {
502
+ return import_effect6.Effect.tryPromise({
503
+ try: () => {
504
+ const conditions = [(0, import_drizzle_orm3.eq)(invoices.tenantId, tenantId)];
505
+ if (filters?.periodYear !== void 0) {
506
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.taxPeriodYear, filters.periodYear));
507
+ }
508
+ if (filters?.periodMonth !== void 0) {
509
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.taxPeriodMonth, filters.periodMonth));
510
+ }
511
+ if (filters?.issueType) {
512
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.issueType, filters.issueType));
513
+ }
514
+ if (filters?.documentType) {
515
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.documentType, filters.documentType));
516
+ }
517
+ return db.select().from(invoices).where((0, import_drizzle_orm3.and)(...conditions)).limit(filters?.limit ?? 100).offset(filters?.offset ?? 0);
518
+ },
519
+ catch: (e) => DbError.make("invoice.list", e)
520
+ });
521
+ },
522
+ upsertMany(rows) {
523
+ if (rows.length === 0) return import_effect6.Effect.succeed(0);
524
+ return import_effect6.Effect.tryPromise({
525
+ try: () => db.insert(invoices).values(rows).onConflictDoUpdate({
526
+ target: [
527
+ invoices.tenantId,
528
+ invoices.documentType,
529
+ invoices.number,
530
+ invoices.issuerRut,
531
+ invoices.receiverRut,
532
+ invoices.issueType
533
+ ],
534
+ set: {
535
+ issuerName: import_drizzle_orm3.sql`excluded.issuer_name`,
536
+ receiverName: import_drizzle_orm3.sql`excluded.receiver_name`,
537
+ date: import_drizzle_orm3.sql`excluded.date`,
538
+ netAmount: import_drizzle_orm3.sql`excluded.net_amount`,
539
+ exemptAmount: import_drizzle_orm3.sql`excluded.exempt_amount`,
540
+ vatAmount: import_drizzle_orm3.sql`excluded.vat_amount`,
541
+ totalAmount: import_drizzle_orm3.sql`excluded.total_amount`,
542
+ confirmationStatus: import_drizzle_orm3.sql`excluded.confirmation_status`,
543
+ raw: import_drizzle_orm3.sql`excluded.raw`,
544
+ updatedAt: /* @__PURE__ */ new Date()
545
+ }
546
+ }).returning({ id: invoices.id }).then((rows2) => rows2.length),
547
+ catch: (e) => DbError.make("invoice.upsertMany", e)
548
+ });
549
+ },
550
+ count(tenantId, filters) {
551
+ return import_effect6.Effect.tryPromise({
552
+ try: () => {
553
+ const conditions = [(0, import_drizzle_orm3.eq)(invoices.tenantId, tenantId)];
554
+ if (filters?.periodYear !== void 0) {
555
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.taxPeriodYear, filters.periodYear));
556
+ }
557
+ if (filters?.periodMonth !== void 0) {
558
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.taxPeriodMonth, filters.periodMonth));
559
+ }
560
+ if (filters?.issueType) {
561
+ conditions.push((0, import_drizzle_orm3.eq)(invoices.issueType, filters.issueType));
562
+ }
563
+ return db.select({ count: import_drizzle_orm3.sql`count(*)::int` }).from(invoices).where((0, import_drizzle_orm3.and)(...conditions)).then((rows) => rows[0]?.count ?? 0);
564
+ },
565
+ catch: (e) => DbError.make("invoice.count", e)
566
+ });
567
+ }
568
+ };
569
+ }
570
+
571
+ // src/repos/sync-job-repo.ts
572
+ var import_effect7 = require("effect");
573
+ var import_drizzle_orm4 = require("drizzle-orm");
574
+ function createSyncJobRepo(db) {
575
+ return {
576
+ create(data) {
577
+ return import_effect7.Effect.tryPromise({
578
+ try: () => db.insert(syncJobs).values(data).returning().then((rows) => rows[0]),
579
+ catch: (e) => DbError.make("syncJob.create", e)
580
+ });
581
+ },
582
+ getById(id) {
583
+ return queryOneOrFail(
584
+ "syncJob.getById",
585
+ "SyncJob",
586
+ id,
587
+ () => db.select().from(syncJobs).where((0, import_drizzle_orm4.eq)(syncJobs.id, id)).then((rows) => rows[0])
588
+ );
589
+ },
590
+ listByTenant(tenantId, filters) {
591
+ return import_effect7.Effect.tryPromise({
592
+ try: () => {
593
+ const conditions = [(0, import_drizzle_orm4.eq)(syncJobs.tenantId, tenantId)];
594
+ if (filters?.periodYear !== void 0) {
595
+ conditions.push((0, import_drizzle_orm4.eq)(syncJobs.periodYear, filters.periodYear));
596
+ }
597
+ if (filters?.periodMonth !== void 0) {
598
+ conditions.push((0, import_drizzle_orm4.eq)(syncJobs.periodMonth, filters.periodMonth));
599
+ }
600
+ if (filters?.issueType) {
601
+ conditions.push((0, import_drizzle_orm4.eq)(syncJobs.issueType, filters.issueType));
602
+ }
603
+ return db.select().from(syncJobs).where((0, import_drizzle_orm4.and)(...conditions)).orderBy((0, import_drizzle_orm4.desc)(syncJobs.createdAt)).limit(20);
604
+ },
605
+ catch: (e) => DbError.make("syncJob.listByTenant", e)
606
+ });
607
+ },
608
+ update(id, data) {
609
+ return queryOneOrFail(
610
+ "syncJob.update",
611
+ "SyncJob",
612
+ id,
613
+ () => db.update(syncJobs).set(data).where((0, import_drizzle_orm4.eq)(syncJobs.id, id)).returning().then((rows) => rows[0])
614
+ );
615
+ }
616
+ };
617
+ }
618
+
619
+ // src/services/credential-service.ts
620
+ var import_effect8 = require("effect");
621
+ function createCredentialService(deps) {
622
+ const { credentialRepo, tokenCacheRepo } = deps;
623
+ const enc = (v) => v && deps.encrypt ? deps.encrypt(v) : v;
624
+ const dec = (v) => v && deps.decrypt ? deps.decrypt(v) : v;
625
+ return {
626
+ save(tenantId, input) {
627
+ return credentialRepo.upsert(tenantId, {
628
+ env: input.env,
629
+ certBase64: enc(input.certBase64) ?? null,
630
+ certPassword: enc(input.certPassword) ?? null,
631
+ portalRut: input.portalRut ?? null,
632
+ portalPassword: enc(input.portalPassword) ?? null
633
+ });
634
+ },
635
+ getStatus(tenantId, env) {
636
+ return credentialRepo.getByTenantAndEnv(tenantId, env).pipe(
637
+ import_effect8.Effect.map((cred) => ({
638
+ connected: true,
639
+ env: cred.env,
640
+ hasCert: !!cred.certBase64,
641
+ hasPortal: !!cred.portalRut && !!cred.portalPassword,
642
+ portalRut: cred.portalRut
643
+ })),
644
+ import_effect8.Effect.catchTag(
645
+ "NotFoundError",
646
+ () => import_effect8.Effect.succeed({
647
+ connected: false,
648
+ env,
649
+ hasCert: false,
650
+ hasPortal: false,
651
+ portalRut: null
652
+ })
653
+ )
654
+ );
655
+ },
656
+ disconnect(tenantId, env) {
657
+ return import_effect8.Effect.gen(function* () {
658
+ const cred = yield* credentialRepo.getByTenantAndEnv(tenantId, env);
659
+ yield* tokenCacheRepo.deleteByCredential(cred.id);
660
+ yield* credentialRepo.delete(tenantId, env);
661
+ });
662
+ }
663
+ };
664
+ }
665
+
666
+ // src/services/auth-service.ts
667
+ var import_effect9 = require("effect");
668
+ var import_sii2 = require("@emisso/sii");
669
+ function toMessage(e) {
670
+ return e instanceof Error ? e.message : String(e);
671
+ }
672
+ async function authenticateSoap(certBase64, certPassword, env) {
673
+ const certData = (0, import_sii2.loadCertFromBase64)(certBase64, certPassword);
674
+ const seed = await (0, import_sii2.getSeed)({ certPath: "", certPassword: "", env });
675
+ const signedSeed = (0, import_sii2.signSeedFromCertData)(seed, certData);
676
+ return (0, import_sii2.getToken)(signedSeed, { certPath: "", certPassword: "", env });
677
+ }
678
+ function createAuthService(deps) {
679
+ const { credentialRepo, tokenCacheRepo } = deps;
680
+ const dec = (v) => deps.decrypt ? deps.decrypt(v) : v;
681
+ return {
682
+ /**
683
+ * Get a valid SOAP token, using cache if available.
684
+ */
685
+ getSoapToken(tenantId, env) {
686
+ return import_effect9.Effect.gen(function* () {
687
+ const cred = yield* credentialRepo.getByTenantAndEnv(tenantId, env);
688
+ if (!cred.certBase64 || !cred.certPassword) {
689
+ return yield* import_effect9.Effect.fail(
690
+ SiiAuthError.make("No certificate configured for SOAP authentication")
691
+ );
692
+ }
693
+ const cached = yield* tokenCacheRepo.get(cred.id, "soap");
694
+ if (cached && new Date(cached.expiresAt).getTime() > Date.now()) {
695
+ return { token: cached.tokenValue, expiresAt: new Date(cached.expiresAt) };
696
+ }
697
+ const siiToken = yield* import_effect9.Effect.tryPromise({
698
+ try: () => authenticateSoap(dec(cred.certBase64), dec(cred.certPassword), env),
699
+ catch: (e) => SiiAuthError.make(`SOAP authentication failed: ${toMessage(e)}`, e)
700
+ });
701
+ yield* tokenCacheRepo.upsert(
702
+ cred.id,
703
+ "soap",
704
+ siiToken.token,
705
+ siiToken.expiresAt
706
+ );
707
+ return siiToken;
708
+ });
709
+ },
710
+ /**
711
+ * Get a portal session via fresh login.
712
+ */
713
+ getPortalSession(tenantId, env) {
714
+ return import_effect9.Effect.gen(function* () {
715
+ const cred = yield* credentialRepo.getByTenantAndEnv(tenantId, env);
716
+ if (!cred.portalRut || !cred.portalPassword) {
717
+ return yield* import_effect9.Effect.fail(
718
+ SiiAuthError.make("No portal credentials configured")
719
+ );
720
+ }
721
+ const session = yield* import_effect9.Effect.tryPromise({
722
+ try: () => (0, import_sii2.portalLogin)(
723
+ { rut: cred.portalRut, claveTributaria: dec(cred.portalPassword), env },
724
+ { connectBrowser: deps.connectBrowser }
725
+ ),
726
+ catch: (e) => SiiAuthError.make(`Portal login failed: ${toMessage(e)}`, e)
727
+ });
728
+ return session;
729
+ });
730
+ },
731
+ /**
732
+ * Test credentials by attempting authentication.
733
+ * Runs SOAP and portal tests concurrently.
734
+ */
735
+ testConnection(tenantId, env) {
736
+ return import_effect9.Effect.gen(function* () {
737
+ const cred = yield* credentialRepo.getByTenantAndEnv(tenantId, env);
738
+ const errors = [];
739
+ const soapTest = cred.certBase64 && cred.certPassword ? import_effect9.Effect.tryPromise({
740
+ try: () => authenticateSoap(dec(cred.certBase64), dec(cred.certPassword), env).then(() => true),
741
+ catch: (e) => toMessage(e)
742
+ }).pipe(import_effect9.Effect.catchAll((msg) => {
743
+ errors.push(`SOAP: ${msg}`);
744
+ return import_effect9.Effect.succeed(false);
745
+ })) : import_effect9.Effect.sync(() => {
746
+ errors.push("SOAP: No certificate configured");
747
+ return false;
748
+ });
749
+ const portalTest = cred.portalRut && cred.portalPassword ? import_effect9.Effect.tryPromise({
750
+ try: () => (0, import_sii2.portalLogin)(
751
+ { rut: cred.portalRut, claveTributaria: dec(cred.portalPassword), env },
752
+ { connectBrowser: deps.connectBrowser }
753
+ ).then(() => true),
754
+ catch: (e) => toMessage(e)
755
+ }).pipe(import_effect9.Effect.catchAll((msg) => {
756
+ errors.push(`Portal: ${msg}`);
757
+ return import_effect9.Effect.succeed(false);
758
+ })) : import_effect9.Effect.sync(() => {
759
+ errors.push("Portal: No portal credentials configured");
760
+ return false;
761
+ });
762
+ const [soapOk, portalOk] = yield* import_effect9.Effect.all(
763
+ [soapTest, portalTest],
764
+ { concurrency: 2 }
765
+ );
766
+ return { soap: soapOk, portal: portalOk, errors };
767
+ });
768
+ }
769
+ };
770
+ }
771
+
772
+ // src/services/invoice-service.ts
773
+ var import_effect10 = require("effect");
774
+ var import_sii3 = require("@emisso/sii");
775
+ function createInvoiceService(deps) {
776
+ const { invoiceRepo, syncJobRepo, authService, credentialRepo } = deps;
777
+ return {
778
+ /**
779
+ * Trigger an RCV invoice sync for a given period.
780
+ * Creates a sync job, fetches from SII, upserts into DB.
781
+ */
782
+ sync(tenantId, env, periodYear, periodMonth, issueType) {
783
+ return import_effect10.Effect.gen(function* () {
784
+ const job = yield* syncJobRepo.create({
785
+ tenantId,
786
+ operation: "rcv_sync",
787
+ periodYear,
788
+ periodMonth,
789
+ issueType,
790
+ status: "running",
791
+ startedAt: /* @__PURE__ */ new Date()
792
+ });
793
+ const failJob = (err) => syncJobRepo.update(job.id, {
794
+ status: "failed",
795
+ completedAt: /* @__PURE__ */ new Date(),
796
+ errorMessage: err.message
797
+ }).pipe(import_effect10.Effect.flatMap(() => import_effect10.Effect.fail(err)));
798
+ const cred = yield* credentialRepo.getByTenantAndEnv(tenantId, env);
799
+ if (!cred.portalRut) {
800
+ const err = SiiAuthError.make("No portal RUT configured for RCV sync");
801
+ return yield* failJob(err);
802
+ }
803
+ const session = yield* authService.getPortalSession(tenantId, env).pipe(import_effect10.Effect.catchAll(failJob));
804
+ const siiInvoices = yield* import_effect10.Effect.tryPromise({
805
+ try: () => (0, import_sii3.listInvoices)(session, {
806
+ rut: cred.portalRut,
807
+ issueType,
808
+ period: { year: periodYear, month: periodMonth }
809
+ }),
810
+ catch: (e) => SiiAuthError.make(
811
+ `RCV fetch failed: ${e instanceof Error ? e.message : String(e)}`,
812
+ e
813
+ )
814
+ }).pipe(import_effect10.Effect.catchAll(failJob));
815
+ const rows = siiInvoices.map(
816
+ (inv) => invoiceToRow(tenantId, inv, issueType)
817
+ );
818
+ const count = yield* invoiceRepo.upsertMany(rows);
819
+ return yield* syncJobRepo.update(job.id, {
820
+ status: "completed",
821
+ completedAt: /* @__PURE__ */ new Date(),
822
+ recordsFetched: count
823
+ });
824
+ });
825
+ }
826
+ };
827
+ }
828
+
829
+ // src/handlers/router.ts
830
+ function compilePattern(pattern) {
831
+ const paramNames = [];
832
+ const regexStr = pattern.split("/").map((segment) => {
833
+ if (segment.startsWith(":")) {
834
+ paramNames.push(segment.slice(1));
835
+ return "([^/]+)";
836
+ }
837
+ return segment;
838
+ }).join("/");
839
+ return { regex: new RegExp(`^${regexStr}$`), paramNames };
840
+ }
841
+ function createRouter(routes) {
842
+ const compiled = routes.map((r) => {
843
+ const { regex, paramNames } = compilePattern(r.pattern);
844
+ return { method: r.method, regex, paramNames, handler: r.handler };
845
+ });
846
+ return async (req, tenantId) => {
847
+ const url = new URL(req.url);
848
+ const method = req.method.toUpperCase();
849
+ const path = url.pathname;
850
+ for (const route of compiled) {
851
+ if (route.method !== method) continue;
852
+ const match = path.match(route.regex);
853
+ if (!match) continue;
854
+ const params = {};
855
+ route.paramNames.forEach((name, i) => {
856
+ params[name] = match[i + 1];
857
+ });
858
+ return route.handler(req, { tenantId, params });
859
+ }
860
+ return Response.json(
861
+ { error: { _type: "NotFoundError", message: "Route not found" } },
862
+ { status: 404 }
863
+ );
864
+ };
865
+ }
866
+
867
+ // src/handlers/auth-handlers.ts
868
+ var import_effect11 = require("effect");
869
+
870
+ // src/handlers/handler-utils.ts
871
+ function resolveEnv(req) {
872
+ const url = new URL(req.url);
873
+ const env = url.searchParams.get("env");
874
+ return env === "certification" ? "certification" : "production";
875
+ }
876
+ function parsePeriod(period) {
877
+ const [y, m] = period.split("-");
878
+ return { year: parseInt(y, 10), month: parseInt(m, 10) };
879
+ }
880
+
881
+ // src/handlers/auth-handlers.ts
882
+ function createAuthHandlers(deps) {
883
+ const { credentialService, authService } = deps;
884
+ const saveCredentials = (req, ctx) => handleEffect(
885
+ import_effect11.Effect.gen(function* () {
886
+ const body = yield* import_effect11.Effect.tryPromise({
887
+ try: () => req.json(),
888
+ catch: () => ValidationError.make("Invalid JSON body")
889
+ });
890
+ const parsed = SaveCredentialsSchema.safeParse(body);
891
+ if (!parsed.success) {
892
+ return yield* import_effect11.Effect.fail(
893
+ ValidationError.fromZodErrors("Invalid credentials data", parsed.error.issues)
894
+ );
895
+ }
896
+ const result = yield* credentialService.save(ctx.tenantId, parsed.data);
897
+ return {
898
+ id: result.id,
899
+ env: result.env,
900
+ hasCert: !!result.certBase64,
901
+ hasPortal: !!result.portalRut,
902
+ portalRut: result.portalRut,
903
+ createdAt: result.createdAt,
904
+ updatedAt: result.updatedAt
905
+ };
906
+ })
907
+ );
908
+ const getStatus = (req, ctx) => {
909
+ const env = resolveEnv(req);
910
+ return handleEffect(credentialService.getStatus(ctx.tenantId, env));
911
+ };
912
+ const testConnection = (req, ctx) => {
913
+ const env = resolveEnv(req);
914
+ return handleEffect(authService.testConnection(ctx.tenantId, env));
915
+ };
916
+ const disconnect = (req, ctx) => {
917
+ const env = resolveEnv(req);
918
+ return handleEffect(
919
+ credentialService.disconnect(ctx.tenantId, env).pipe(import_effect11.Effect.map(() => null)),
920
+ () => noContentResponse()
921
+ );
922
+ };
923
+ return {
924
+ saveCredentials,
925
+ getStatus,
926
+ testConnection,
927
+ disconnect
928
+ };
929
+ }
930
+
931
+ // src/handlers/invoice-handlers.ts
932
+ var import_effect12 = require("effect");
933
+ function createInvoiceHandlers(deps) {
934
+ const { invoiceService, invoiceRepo, syncJobRepo } = deps;
935
+ const listInvoices2 = (req, ctx) => handleEffect(
936
+ import_effect12.Effect.gen(function* () {
937
+ const url = new URL(req.url);
938
+ const query = ListInvoicesQuerySchema.safeParse(
939
+ Object.fromEntries(url.searchParams)
940
+ );
941
+ if (!query.success) {
942
+ return yield* import_effect12.Effect.fail(
943
+ ValidationError.fromZodErrors("Invalid query parameters", query.error.issues)
944
+ );
945
+ }
946
+ const { period, type, documentType, limit, offset } = query.data;
947
+ const periodParsed = period ? parsePeriod(period) : void 0;
948
+ const rows = yield* invoiceRepo.list(ctx.tenantId, {
949
+ periodYear: periodParsed?.year,
950
+ periodMonth: periodParsed?.month,
951
+ issueType: type,
952
+ documentType,
953
+ limit,
954
+ offset
955
+ });
956
+ return { data: rows.map(rowToInvoice), count: rows.length };
957
+ })
958
+ );
959
+ const syncInvoices = (req, ctx) => handleEffect(
960
+ import_effect12.Effect.gen(function* () {
961
+ const body = yield* import_effect12.Effect.tryPromise({
962
+ try: () => req.json(),
963
+ catch: () => ValidationError.make("Invalid JSON body")
964
+ });
965
+ const parsed = SyncInvoicesSchema.safeParse(body);
966
+ if (!parsed.success) {
967
+ return yield* import_effect12.Effect.fail(
968
+ ValidationError.fromZodErrors("Invalid sync parameters", parsed.error.issues)
969
+ );
970
+ }
971
+ const { year: periodYear, month: periodMonth } = parsePeriod(parsed.data.period);
972
+ const env = resolveEnv(req);
973
+ return yield* invoiceService.sync(ctx.tenantId, env, periodYear, periodMonth, parsed.data.type);
974
+ }),
975
+ createdResponse
976
+ );
977
+ const getSyncStatus = (req, ctx) => handleEffect(
978
+ import_effect12.Effect.gen(function* () {
979
+ const url = new URL(req.url);
980
+ const query = SyncStatusQuerySchema.safeParse(
981
+ Object.fromEntries(url.searchParams)
982
+ );
983
+ if (!query.success) {
984
+ return yield* import_effect12.Effect.fail(
985
+ ValidationError.fromZodErrors("Invalid query parameters", query.error.issues)
986
+ );
987
+ }
988
+ const { period, type } = query.data;
989
+ const periodParsed = period ? parsePeriod(period) : void 0;
990
+ const jobs = yield* syncJobRepo.listByTenant(ctx.tenantId, {
991
+ periodYear: periodParsed?.year,
992
+ periodMonth: periodParsed?.month,
993
+ issueType: type
994
+ });
995
+ return { data: jobs };
996
+ })
997
+ );
998
+ return {
999
+ listInvoices: listInvoices2,
1000
+ syncInvoices,
1001
+ getSyncStatus
1002
+ };
1003
+ }
1004
+ // Annotate the CommonJS export names for ESM import in node:
1005
+ 0 && (module.exports = {
1006
+ ConflictError,
1007
+ DbError,
1008
+ ForbiddenError,
1009
+ ListInvoicesQuerySchema,
1010
+ NotFoundError,
1011
+ SaveCredentialsSchema,
1012
+ SiiAuthError,
1013
+ SyncInvoicesSchema,
1014
+ SyncStatusQuerySchema,
1015
+ ValidationError,
1016
+ createAuthHandlers,
1017
+ createAuthService,
1018
+ createCredentialRepo,
1019
+ createCredentialService,
1020
+ createInvoiceHandlers,
1021
+ createInvoiceRepo,
1022
+ createInvoiceService,
1023
+ createRouter,
1024
+ createSyncJobRepo,
1025
+ createTokenCacheRepo,
1026
+ createdResponse,
1027
+ credentials,
1028
+ handleEffect,
1029
+ invoiceToRow,
1030
+ invoices,
1031
+ isAppError,
1032
+ jsonResponse,
1033
+ noContentResponse,
1034
+ queryOneOrFail,
1035
+ rowToInvoice,
1036
+ serializeAppError,
1037
+ siiSchema,
1038
+ syncJobs,
1039
+ toErrorResponse,
1040
+ toErrorResponseFromUnknown,
1041
+ tokenCache
1042
+ });
1043
+ //# sourceMappingURL=index.cjs.map