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