fiscalisto 0.1.2 → 0.1.4

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/cli.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { spawn, spawnSync } from "node:child_process";
11
11
  import { createHmac } from "node:crypto";
12
- import { existsSync, readFileSync } from "node:fs";
12
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
13
13
  import { appendFile, chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
14
14
  import { homedir, hostname } from "node:os";
15
15
  import { dirname, join, resolve } from "node:path";
@@ -40,9 +40,20 @@ function print(value, human) {
40
40
  }
41
41
  const line = (s = "") => process.stdout.write(`${s}\n`);
42
42
  const note = (s) => process.stderr.write(`${s}\n`);
43
- const money = (n, currency = "MXN") => typeof n === "number"
44
- ? `${n.toLocaleString("es-MX", { style: "currency", currency: currency === "XXX" ? "MXN" : currency })}${currency !== "MXN" ? ` ${currency}` : ""}`
45
- : "";
43
+ const money = (n, currency = "MXN") => {
44
+ if (typeof n !== "number")
45
+ return "";
46
+ const amount = n.toLocaleString("es-MX", {
47
+ minimumFractionDigits: 2,
48
+ maximumFractionDigits: 2,
49
+ });
50
+ return currency === "MXN" || currency === "XXX" ? `$${amount}` : `${amount} ${currency}`;
51
+ };
52
+ /** What a document is worth in a list: a payment complement's total is 0, so its amount paid. */
53
+ const worth = (i) => {
54
+ const paid = i.payment;
55
+ return i.type === "P" && paid ? money(paid.amount, paid.currency) : money(i.total, i.currency);
56
+ };
46
57
  const configPath = () => join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "fiscalisto", "config.json");
47
58
  async function loadConfig() {
48
59
  try {
@@ -240,6 +251,7 @@ async function whoami(g) {
240
251
  line(`Emisores: ${issuers.data.map((i) => `${i.tax_id}${i.status !== "active" ? dim(` (${i.status})`) : ""}`).join(", ") || dim("ninguno")}`);
241
252
  });
242
253
  }
254
+ const LANGS = ["node", "python", "php", "go", "dotnet", "java"];
243
255
  function detectLang(dir) {
244
256
  if (existsSync(join(dir, "package.json")))
245
257
  return "node";
@@ -247,8 +259,15 @@ function detectLang(dir) {
247
259
  return "python";
248
260
  if (existsSync(join(dir, "composer.json")))
249
261
  return "php";
262
+ if (existsSync(join(dir, "go.mod")))
263
+ return "go";
264
+ if (["pom.xml", "build.gradle", "build.gradle.kts"].some((f) => existsSync(join(dir, f))))
265
+ return "java";
266
+ if (readdirSync(dir).some((f) => /\.(csproj|fsproj|sln)$/.test(f)))
267
+ return "dotnet";
250
268
  return null;
251
269
  }
270
+ /** The command that adds the SDK, or null where it goes in a build file by hand (Java). */
252
271
  function installCommand(lang, dir) {
253
272
  if (lang === "python") {
254
273
  if (existsSync(join(dir, "uv.lock")))
@@ -259,6 +278,12 @@ function installCommand(lang, dir) {
259
278
  }
260
279
  if (lang === "php")
261
280
  return ["composer", "require", "fiscalisto/fiscalisto"];
281
+ if (lang === "go")
282
+ return ["go", "get", "fiscalisto.com/go"];
283
+ if (lang === "dotnet")
284
+ return ["dotnet", "add", "package", "Fiscalisto"];
285
+ if (lang === "java")
286
+ return null;
262
287
  if (existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb")))
263
288
  return ["bun", "add", "fiscalisto"];
264
289
  if (existsSync(join(dir, "pnpm-lock.yaml")))
@@ -267,6 +292,10 @@ function installCommand(lang, dir) {
267
292
  return ["yarn", "add", "fiscalisto"];
268
293
  return ["npm", "install", "fiscalisto"];
269
294
  }
295
+ /** What to add to a Java build by hand. */
296
+ const javaDependency = (dir) => existsSync(join(dir, "pom.xml"))
297
+ ? `pom.xml: agregue <dependency><groupId>com.fiscalisto</groupId><artifactId>fiscalisto</artifactId><version>${VERSION}</version></dependency>`
298
+ : `build.gradle: agregue implementation("com.fiscalisto:fiscalisto:${VERSION}")`;
270
299
  const EXAMPLE_INVOICE = {
271
300
  customer: {
272
301
  tax_id: "ICV060329BY0",
@@ -350,14 +379,117 @@ echo $factura['status'], ' ', $factura['uuid'], ' ', $factura['total'], PHP_EOL;
350
379
  `,
351
380
  },
352
381
  };
382
+ EXAMPLES.go = {
383
+ file: "fiscalisto-ejemplo/main.go",
384
+ run: "env $(grep -v '^#' .env | xargs) go run ./fiscalisto-ejemplo",
385
+ code: `// Timbra una factura de prueba con el SDK de Fiscalisto:
386
+ // env $(grep -v '^#' .env | xargs) go run ./fiscalisto-ejemplo
387
+ package main
388
+
389
+ import (
390
+ "context"
391
+ "fmt"
392
+ "log"
393
+ "time"
394
+
395
+ fiscalisto "fiscalisto.com/go"
396
+ )
397
+
398
+ func main() {
399
+ // La llave viene de FISCALISTO_API_KEY.
400
+ client, err := fiscalisto.NewClient("")
401
+ if err != nil {
402
+ log.Fatal(err)
403
+ }
404
+ factura, err := client.Invoices.Create(context.Background(), &fiscalisto.InvoiceCreate{
405
+ Customer: fiscalisto.ObjectOf(fiscalisto.InvoiceCreateCustomer{
406
+ TaxID: "ICV060329BY0",
407
+ LegalName: "INMOBILIARIA CVA",
408
+ TaxSystem: "601",
409
+ Zip: "33826",
410
+ }),
411
+ PaymentForm: fiscalisto.String("03"),
412
+ Items: []fiscalisto.InvoiceCreateItem{{
413
+ Description: fiscalisto.String("Consultoría"),
414
+ ProductKey: fiscalisto.String("80101500"),
415
+ UnitPrice: fiscalisto.Float64(1000),
416
+ }},
417
+ }, fiscalisto.WithIdempotencyKey(fmt.Sprintf("pedido-%d", time.Now().Unix()))) // use el id de su pedido
418
+ if err != nil {
419
+ log.Fatal(err)
420
+ }
421
+ fmt.Println(factura.ID)
422
+ }
423
+ `,
424
+ };
425
+ EXAMPLES.dotnet = {
426
+ file: "FiscalistoEjemplo.cs",
427
+ run: "llame a await FiscalistoEjemplo.RunAsync() con FISCALISTO_API_KEY en el entorno",
428
+ code: `// Timbra una factura de prueba con el SDK de Fiscalisto: await FiscalistoEjemplo.RunAsync();
429
+ using Fiscalisto;
430
+
431
+ public static class FiscalistoEjemplo
432
+ {
433
+ public static async Task RunAsync()
434
+ {
435
+ // La llave viene de FISCALISTO_API_KEY.
436
+ var fiscalisto = new FiscalistoClient();
437
+ var factura = await fiscalisto.Invoices.CreateAsync(new InvoiceCreate
438
+ {
439
+ Customer = new InvoiceCreateCustomer
440
+ {
441
+ TaxId = "ICV060329BY0",
442
+ LegalName = "INMOBILIARIA CVA",
443
+ TaxSystem = "601",
444
+ Zip = "33826",
445
+ },
446
+ PaymentForm = "03",
447
+ Items = new() { new() { Description = "Consultoría", ProductKey = "80101500", UnitPrice = 1000 } },
448
+ }, new RequestOptions { IdempotencyKey = $"pedido-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}" }); // use el id de su pedido
449
+ Console.WriteLine(factura.Id);
450
+ }
451
+ }
452
+ `,
453
+ };
454
+ EXAMPLES.java = {
455
+ file: "FiscalistoEjemplo.java",
456
+ run: "corra FiscalistoEjemplo.main con FISCALISTO_API_KEY en el entorno",
457
+ code: `// Timbra una factura de prueba con el SDK de Fiscalisto (FISCALISTO_API_KEY en el entorno).
458
+ import com.fiscalisto.FiscalistoClient;
459
+ import com.fiscalisto.RequestOptions;
460
+ import com.fiscalisto.model.InvoiceCreate;
461
+ import com.fiscalisto.model.InvoiceCreateCustomer;
462
+ import com.fiscalisto.model.InvoiceCreateItem;
463
+ import java.util.List;
464
+
465
+ public class FiscalistoEjemplo {
466
+ public static void main(String[] args) {
467
+ var fiscalisto = new FiscalistoClient();
468
+ var factura = fiscalisto.invoices().create(new InvoiceCreate()
469
+ .setCustomer(new InvoiceCreateCustomer()
470
+ .setTaxId("ICV060329BY0")
471
+ .setLegalName("INMOBILIARIA CVA")
472
+ .setTaxSystem("601")
473
+ .setZip("33826"))
474
+ .setPaymentForm("03")
475
+ .setItems(List.of(new InvoiceCreateItem()
476
+ .setDescription("Consultoría")
477
+ .setProductKey("80101500")
478
+ .setUnitPrice(1000))),
479
+ RequestOptions.idempotencyKey("pedido-" + System.currentTimeMillis() / 1000)); // use el id de su pedido
480
+ System.out.println(factura.getId());
481
+ }
482
+ }
483
+ `,
484
+ };
353
485
  const AGENTS_SECTION = `
354
486
  ## Facturación (Fiscalisto)
355
487
 
356
488
  Facturas electrónicas (CFDI 4.0) con la API de Fiscalisto. La llave está en \`FISCALISTO_API_KEY\`
357
489
  (\`.env\`; \`fk_test_\` timbra en pruebas sin costo). Documentación completa para agentes:
358
- https://fiscalisto.com/llms.txt y la referencia en https://api.fiscalisto.com/v1/openapi.json.
490
+ https://fiscalisto.com/docs/api/llms.txt y la referencia en https://api.fiscalisto.com/v1/openapi.json.
359
491
 
360
- - Use el SDK \`fiscalisto\` (npm, PyPI, Packagist). Cada timbrado lleva una Idempotency-Key
492
+ - Use el SDK \`fiscalisto\` (npm, PyPI, Packagist, Go, Maven, NuGet). Cada timbrado lleva una Idempotency-Key
361
493
  (el id del pedido): repetirla nunca timbra dos veces.
362
494
  - El cliente va con su RFC, nombre, régimen y código postal exactamente como en su constancia.
363
495
  - Para probar rechazos del SAT use los RFC de prueba (NOM010101FK9 y otros, ver "Pruebas y producción").
@@ -375,10 +507,10 @@ async function init(args, g) {
375
507
  });
376
508
  const dir = resolve(values.dir ?? ".");
377
509
  const lang = values.lang ?? detectLang(dir);
378
- if (lang && !EXAMPLES[lang])
379
- throw new UsageError("--lang es node, python o php.");
510
+ if (lang && !LANGS.includes(lang))
511
+ throw new UsageError(`--lang es ${LANGS.join(", ")}.`);
380
512
  if (!lang)
381
- throw new UsageError("No encontré package.json, pyproject.toml/requirements.txt ni composer.json aquí. Indique --lang node|python|php.");
513
+ throw new UsageError(`No encontré package.json, pyproject.toml/requirements.txt, composer.json, go.mod, pom.xml/build.gradle ni un .csproj aquí. Indique --lang ${LANGS.join("|")}.`);
382
514
  if (!env.FISCALISTO_API_KEY && !g.apiKey && !(await loadConfig()).test_key)
383
515
  await login([], g);
384
516
  const key = g.apiKey ?? env.FISCALISTO_API_KEY ?? (await loadConfig()).test_key ?? "";
@@ -399,7 +531,9 @@ async function init(args, g) {
399
531
  // The SDK.
400
532
  const install = installCommand(lang, dir);
401
533
  let installed = false;
402
- if (!values["no-install"]) {
534
+ if (!install)
535
+ done.push(javaDependency(dir));
536
+ else if (!values["no-install"]) {
403
537
  const go = g.yes || !process.stdin.isTTY || json
404
538
  ? true
405
539
  : await ask(`Instalar el SDK con «${install.join(" ")}»? [S/n] `).then((y) => y);
@@ -428,10 +562,15 @@ async function init(args, g) {
428
562
  }
429
563
  // An example that stamps.
430
564
  const example = EXAMPLES[lang];
431
- const examplePath = join(dir, example.file);
565
+ // Maven and Gradle compile src/main/java.
566
+ const exampleFile = lang === "java" && existsSync(join(dir, "src/main/java"))
567
+ ? `src/main/java/${example.file}`
568
+ : example.file;
569
+ const examplePath = join(dir, exampleFile);
432
570
  if (!existsSync(examplePath)) {
571
+ await mkdir(dirname(examplePath), { recursive: true });
433
572
  await writeFile(examplePath, example.code);
434
- done.push(`${example.file}: timbra una factura de prueba`);
573
+ done.push(`${exampleFile}: timbra una factura de prueba`);
435
574
  }
436
575
  if (values.agents) {
437
576
  const agentsPath = join(dir, existsSync(join(dir, "CLAUDE.md")) && !existsSync(join(dir, "AGENTS.md"))
@@ -465,7 +604,7 @@ const status = (s, width = 0) => {
465
604
  return color(label.padEnd(width));
466
605
  };
467
606
  function showInvoice(i) {
468
- line(`${bold(`${i.series ?? ""}${i.folio ?? ""}` || i.id)} ${status(i.status)} ${money(i.total, i.currency)}`);
607
+ line(`${bold(`${i.series ?? ""}${i.folio ?? ""}` || i.id)} ${status(i.status)} ${worth(i)}`);
469
608
  line(` ${i.customer.legal_name ?? ""} ${dim(i.customer.tax_id)}`);
470
609
  if (i.uuid)
471
610
  line(` UUID ${i.uuid}`);
@@ -514,7 +653,9 @@ async function invoices(args, g) {
514
653
  body = structuredClone(EXAMPLE_INVOICE);
515
654
  if (!body) {
516
655
  if (!values.customer || !values.item?.length)
517
- throw new UsageError('Pase --data (JSON, @archivo o -), --example, o --customer RFC --name "NOMBRE" --regime 601 --zip 12345 --item "Descripción|clave|precio".');
656
+ throw new UsageError('Pase --data (JSON, @archivo o -), --example, o --customer RFC --name "NOMBRE" --regime 601 --zip 12345 --item "Descripción|clave|precio" --payment-form 03.');
657
+ if (!values["payment-form"] && values["payment-method"] !== "PPD")
658
+ throw new UsageError("Falta --payment-form: 03 transferencia, 01 efectivo, 04 tarjeta de crédito, 28 de débito (o --payment-method PPD si se la pagan después).");
518
659
  body = {
519
660
  customer: {
520
661
  tax_id: values.customer.toUpperCase(),
@@ -569,7 +710,7 @@ async function invoices(args, g) {
569
710
  if (!page.data.length)
570
711
  return line(dim("Sin facturas."));
571
712
  for (const i of page.data)
572
- line(`${(`${i.series ?? ""}${i.folio ?? ""}` || "—").padEnd(8)} ${status(i.status, 10)} ${money(i.total, i.currency).padStart(14)} ${(i.customer.legal_name ?? "").slice(0, 32).padEnd(32)} ${dim(i.id)}`);
713
+ line(`${(`${i.series ?? ""}${i.folio ?? ""}` || "—").padEnd(8)} ${status(i.status, 10)} ${worth(i).padStart(14)} ${(i.customer.legal_name ?? "").slice(0, 32).padEnd(32)} ${dim(i.id)}`);
573
714
  if (page.has_more)
574
715
  line(dim(`… hay más: --limit ${Number(values.limit) * 2}`));
575
716
  });
@@ -675,7 +816,18 @@ async function issuers(args, g) {
675
816
  method: "GET",
676
817
  path: `/v1/issuers/${need(args[1], "fiscalisto issuers get iss_…")}`,
677
818
  });
678
- return print(issuer);
819
+ return print(issuer, () => {
820
+ line(`${bold(String(issuer.legal_name ?? issuer.tax_id))} ${dim(String(issuer.tax_id))}`);
821
+ line(` Estado ${String(issuer.status)}`);
822
+ for (const [label, key] of [
823
+ ["Régimen", "tax_system"],
824
+ ["C.P.", "zip"],
825
+ ["Modo", "livemode"],
826
+ ])
827
+ if (issuer[key] !== undefined && issuer[key] !== null)
828
+ line(` ${label.padEnd(10)} ${key === "livemode" ? (issuer[key] ? "producción" : "pruebas") : String(issuer[key])}`);
829
+ line(dim(` ${String(issuer.id)}`));
830
+ });
679
831
  }
680
832
  if (args[0] && args[0] !== "list")
681
833
  throw new UsageError("fiscalisto issuers list|get");
@@ -706,10 +858,16 @@ async function events(args, g) {
706
858
  options: {
707
859
  type: { type: "string" },
708
860
  object: { type: "string" },
861
+ failed: { type: "boolean" },
709
862
  limit: { type: "string", default: "20" },
710
863
  },
711
864
  });
712
- await simpleList(api, "/v1/events", { type: values.type, object: values.object, limit: values.limit }, (e) => {
865
+ await simpleList(api, "/v1/events", {
866
+ type: values.type,
867
+ object: values.object,
868
+ delivery_success: values.failed ? "false" : undefined,
869
+ limit: values.limit,
870
+ }, (e) => {
713
871
  const o = e.data.object;
714
872
  return `${dim(String(e.created_at))} ${String(e.type).padEnd(30)} ${o.id} ${dim(String(e.id))}`;
715
873
  });
@@ -979,7 +1137,11 @@ async function trigger(args, g) {
979
1137
  case "invoice.failed":
980
1138
  made = await stamp({
981
1139
  ...EXAMPLE_INVOICE,
982
- customer: { ...EXAMPLE_INVOICE.customer, tax_id: "NOM010101FK9" },
1140
+ customer: {
1141
+ ...EXAMPLE_INVOICE.customer,
1142
+ tax_id: "NOM010101FK9",
1143
+ legal_name: "CLIENTE DE PRUEBA RECHAZADO",
1144
+ },
983
1145
  }).catch((e) => {
984
1146
  if (e instanceof FiscalistoError && e.code === "invoice_rejected")
985
1147
  return e.raw;
@@ -1040,12 +1202,13 @@ function openPlace(args) {
1040
1202
  print({ url }, () => line(url));
1041
1203
  }
1042
1204
  async function docs() {
1043
- const r = await fetch(`${APP_URL()}/llms.txt`);
1205
+ const url = `${APP_URL()}/docs/api/llms.txt`;
1206
+ const r = await fetch(url);
1044
1207
  if (!r.ok)
1045
1208
  throw new Error(`No se pudo leer la documentación (${r.status}).`);
1046
1209
  const text = await r.text();
1047
1210
  if (json)
1048
- print({ url: `${APP_URL()}/llms.txt`, text });
1211
+ print({ url, text });
1049
1212
  else
1050
1213
  process.stdout.write(text);
1051
1214
  }
@@ -1106,13 +1269,13 @@ const HELP = `${bold("fiscalisto")} ${dim(VERSION)} · facturación electrónica
1106
1269
 
1107
1270
  ${bold("Empezar")}
1108
1271
  login [--live] [--key fk_…] Inicia sesión por el navegador y guarda su llave de pruebas
1109
- init [--lang node|python|php] Deja el SDK, la llave en .env y un ejemplo en su proyecto (--agents: AGENTS.md)
1272
+ init [--lang node|python|php|go|dotnet|java] Deja el SDK, la llave en .env y un ejemplo en su proyecto (--agents: AGENTS.md)
1110
1273
  whoami Cuenta, modo, timbres y emisores
1111
1274
  logout Olvida las llaves en esta computadora
1112
1275
 
1113
1276
  ${bold("Facturas")}
1114
1277
  invoices create --example Timbra una factura de prueba
1115
- invoices create --data @f.json | --customer RFC --name … --regime 601 --zip … --item "Desc|clave|precio"
1278
+ invoices create --data @f.json | --customer RFC --name … --regime 601 --zip … --item "Desc|clave|precio" --payment-form 03 [--payment-method PPD] [--use G03]
1116
1279
  invoices list [--status valid] [--customer RFC]
1117
1280
  invoices get|pdf|xml|send <inv_…>
1118
1281
  invoices cancel <inv_…> [--motive 02] [--substitution inv_…]
@@ -1122,7 +1285,8 @@ ${bold("Webhooks")}
1122
1285
  listen [--forward-to URL] Reenvía los eventos a su computadora, firmados
1123
1286
  trigger <evento> Crea en pruebas lo que manda ese evento (invoice.stamped, invoice.failed…)
1124
1287
  webhooks list|create|delete|test
1125
- events list|get
1288
+ events list [--type invoice.*] [--failed] Los últimos 30 días; --failed: los que algún webhook no recibió
1289
+ events get <evt_…>
1126
1290
 
1127
1291
  ${bold("Otros")}
1128
1292
  issuers list|get Sus emisores
@@ -1157,6 +1321,13 @@ export async function main(argv) {
1157
1321
  rest.push(a);
1158
1322
  }
1159
1323
  const [command, ...args] = rest;
1324
+ // «fiscalisto invoices create --help»: the help, not «Unknown option».
1325
+ if (command && args.some((a) => a === "--help" || a === "-h")) {
1326
+ const lines = HELP.split("\n").filter((l) => l.trimStart().startsWith(`${command} `) || l.trimStart() === command);
1327
+ line(lines.length ? lines.join("\n") : HELP);
1328
+ line(dim("\nDocumentación: https://fiscalisto.com/docs/api/cli"));
1329
+ return;
1330
+ }
1160
1331
  try {
1161
1332
  switch (command) {
1162
1333
  case "login":
package/dist/core.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * llamar.
5
5
  */
6
6
  import type { ErrorCode } from "./error-codes.js";
7
- export declare const VERSION = "0.1.2";
7
+ export declare const VERSION = "0.1.4";
8
8
  /**
9
9
  * La versión de la API para la que se hizo este SDK: la manda en cada solicitud
10
10
  * (Fiscalisto-Version), así actualizar la API no cambia lo que recibe hasta que actualice el SDK.
package/dist/core.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * errores y las listas que se recorren solas. Los recursos (generated.ts) solo dicen qué ruta
4
4
  * llamar.
5
5
  */
6
- export const VERSION = "0.1.2";
6
+ export const VERSION = "0.1.4";
7
7
  /**
8
8
  * La versión de la API para la que se hizo este SDK: la manda en cada solicitud
9
9
  * (Fiscalisto-Version), así actualizar la API no cambia lo que recibe hasta que actualice el SDK.