{"_id":"@calltek/invo-sdk","_rev":"2-0408e91ea7a93882f89389c32312a2d4","name":"@calltek/invo-sdk","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@calltek/invo-sdk","version":"0.1.0","keywords":["auth","authentication","jwt","oauth","typescript","sdk","calltek"],"author":{"name":"Calltek"},"license":"MIT","_id":"@calltek/invo-sdk@0.1.0","maintainers":[{"name":"50l3r","email":"500l3r@gmail.com"}],"homepage":"https://github.com/calltek/invo-sdk-ts#readme","bugs":{"url":"https://github.com/calltek/invo-sdk-ts/issues"},"dist":{"shasum":"98ea7240cc9e5bc14edc841e1868ab00b883f468","tarball":"https://registry.npmjs.org/@calltek/invo-sdk/-/invo-sdk-0.1.0.tgz","fileCount":18,"integrity":"sha512-t3zDHEs/wJYZj7D05OIt2lYa0W4qkOJqXwFVRc463KH48j2LylPexjjy7Q32N4r2z9gQBFb2p+AtK1uDkN4vrA==","signatures":[{"sig":"MEUCIQD5kBD67fo2lNk/DHkt8XEfOFLHyJ2+wukUBarhkTWYlgIgeDIn7r/rb4Q9tRMVJZLIhTbul338m3xPQyCareUSiOA=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":105640},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","require":"./dist/index.js"}},"gitHead":"fe8cf924700a83febd51396972e8490e7bded491","scripts":{"build":"rollup -c","clean":"rm -rf dist","types":"npx tsx ./swagger.ts","prepare":"npm run build","release":"changeset publish","test:token":"npx tsx test/test-api_key.ts","build:watch":"tsc --watch","test:makeup":"npx tsx test/test-makeup.ts","test:reader":"npx tsx test/test-reader.ts","test:invoice":"npx tsx test/test-invoice.ts","types:sandbox":"npx tsx ./swagger.ts sandbox","prepublishOnly":"npm run clean && npm run build"},"_npmUser":{"name":"50l3r","email":"500l3r@gmail.com"},"repository":{"url":"git+https://github.com/calltek/invo-sdk-ts.git","type":"git"},"_npmVersion":"11.6.0","description":"INVO SDK Typescript","directories":{},"_nodeVersion":"24.9.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"tslib":"^2.8.1","dotenv":"^17.2.3","eslint":"^9.39.1","rollup":"^4.53.3","prettier":"^3.6.2","typescript":"^5.9.3","@types/node":"^24.10.1","rollup-plugin-dts":"^6.2.3","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","swagger-typescript-api":"^13.2.16","@rollup/plugin-typescript":"^12.3.0","@typescript-eslint/parser":"^8.46.4","@typescript-eslint/eslint-plugin":"^8.46.4"},"_npmOperationalInternal":{"tmp":"tmp/invo-sdk_0.1.0_1764769148092_0.7813714173692428","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2025-12-03T13:39:08.012Z","modified":"2025-12-03T14:28:06.422Z","0.1.0":"2025-12-03T13:39:08.281Z"},"bugs":{"url":"https://github.com/calltek/invo-sdk-ts/issues"},"author":{"name":"Calltek"},"license":"MIT","homepage":"https://github.com/calltek/invo-sdk-ts#readme","keywords":["auth","authentication","jwt","oauth","typescript","sdk","calltek"],"repository":{"url":"git+https://github.com/calltek/invo-sdk-ts.git","type":"git"},"description":"INVO SDK Typescript","maintainers":[{"email":"500l3r@gmail.com","name":"50l3r"},{"email":"j.hernandez@calltek.es","name":"juanjosehdez"}],"readme":"# INVO SDK\n\nBackend SDK for INVO API - Simplified authentication and invoice management with full TypeScript support.\n\n## Features\n\n✅ **TypeScript Native** - Complete type definitions and autocomplete\n✅ **Backend Optimized** - Designed for Node.js/Backend applications\n✅ **API Token Authentication** - Secure authentication with automatic login\n✅ **Zero Configuration** - Works out of the box with minimal setup\n✅ **Invoice Management** - Create and manage VeriFactu invoices\n✅ **Invoice Reader** - Extract data from PDF and XML invoices\n✅ **PDF Generator** - Generate branded invoice PDFs\n✅ **Webhook Support** - Receive invoice status updates\n✅ **Workspace Support** - Multi-tenant scenarios\n✅ **Multi-Environment** - Production and sandbox modes\n✅ **Zero Dependencies** - No external dependencies\n✅ **Generic Request Method** - Call any API endpoint with authentication\n\n## Installation\n\n```bash\nnpm install @calltek/invo-sdk\n```\n\n```bash\nyarn add @calltek/invo-sdk\n```\n\n```bash\npnpm add @calltek/invo-sdk\n```\n\n## Quick Start\n\n```typescript\nimport { InvoSDK } from '@calltek/invo-sdk'\n\n// Create SDK instance (login is automatic!)\nconst sdk = new InvoSDK({\n  apiToken: process.env.INVO_API_TOKEN!\n  // environment is auto-detected from token prefix\n})\n\n// Create an invoice - authentication happens automatically\nconst result = await sdk.store({\n  issueDate: new Date().toISOString(),\n  invoiceNumber: 'FAC-2024-001',\n  externalId: 'order-12345',\n  totalAmount: 1210.00,\n  customerName: 'Cliente Ejemplo SL',\n  customerTaxId: 'B12345678',\n  emitterName: 'Mi Empresa SL',\n  emitterTaxId: 'B87654321',\n  description: 'Servicios de consultoría tecnológica',\n  taxLines: [{\n    taxRate: 21,\n    baseAmount: 1000.00,\n    taxAmount: 210.00\n  }]\n})\n\nconsole.log('Invoice created:', result.invoiceId)\nconsole.log('Chain index:', result.chainIndex)\n```\n\n## Configuration\n\n```typescript\ninterface InvoSDKConfig {\n  apiToken: string                      // Required: API token from INVO platform\n  environment?: 'production' | 'sandbox' // Optional: Auto-detected from token\n  onError?: (error: Error) => void      // Optional: Error callback\n  debug?: boolean                       // Optional: Enable debug logging\n}\n```\n\n**Important:** The workspace is automatically determined by the API token. Each API token is associated with a specific workspace, so you don't need to specify it separately.\n\n## Usage Examples\n\n### Basic Setup\n\n```typescript\nimport { InvoSDK } from '@calltek/invo-sdk'\n\n// Simple setup - workspace is determined by the API token\nconst sdk = new InvoSDK({\n  apiToken: process.env.INVO_API_TOKEN!\n})\n```\n\n### Creating Invoices\n\n#### Simple Invoice\n\n```typescript\nconst result = await sdk.store({\n  issueDate: new Date().toISOString(),\n  invoiceNumber: 'FAC-2024-001',\n  externalId: 'order-12345',\n  totalAmount: 1210.00,\n  customerName: 'Cliente SL',\n  customerTaxId: 'B12345678',\n  emitterName: 'Mi Empresa SL',\n  emitterTaxId: 'B87654321',\n  description: 'Servicios de consultoría',\n  taxLines: [{\n    taxRate: 21,\n    baseAmount: 1000.00,\n    taxAmount: 210.00\n  }]\n})\n```\n\n#### Invoice with Webhook Callback\n\n```typescript\n// Receive status updates when the invoice is processed\nconst result = await sdk.store({\n  issueDate: new Date().toISOString(),\n  invoiceNumber: 'FAC-2024-001',\n  // ... invoice data\n}, 'https://myapp.com/webhooks/invoice-status')\n\n// Your webhook will be called when the invoice status changes\n```\n\n#### Invoice with Multiple Tax Rates\n\n```typescript\nconst result = await sdk.store({\n  issueDate: new Date().toISOString(),\n  invoiceNumber: 'FAC-2024-002',\n  externalId: 'multi-tax-001',\n  totalAmount: 1864.00,\n  customerName: 'Cliente SL',\n  customerTaxId: 'B12345678',\n  emitterName: 'Mi Empresa SL',\n  emitterTaxId: 'B87654321',\n  description: 'Venta mixta de productos',\n  taxLines: [\n    {\n      taxRate: 21,\n      baseAmount: 1000.00,\n      taxAmount: 210.00\n    },\n    {\n      taxRate: 10,\n      baseAmount: 500.00,\n      taxAmount: 50.00\n    },\n    {\n      taxRate: 4,\n      baseAmount: 100.00,\n      taxAmount: 4.00\n    }\n  ]\n})\n```\n\n### Reading Invoice from File\n\n```typescript\nimport fs from 'fs'\n\n// Read invoice from a PDF file\nconst fileBuffer = fs.readFileSync('invoice.pdf')\nconst file = new File([fileBuffer], 'invoice.pdf', { type: 'application/pdf' })\n\nconst invoiceData = await sdk.read(file)\nconsole.log('Parsed invoice:', invoiceData)\n```\n\n### Generating PDF Invoice\n\n```typescript\nimport fs from 'fs'\n\nconst pdfBuffer = await sdk.pdf({\n  id: 'INV-2024-001',\n  date: '2024-01-15',\n  branding: {\n    logo: 'https://example.com/logo.png',\n    favicon: 'https://example.com/favicon.ico',\n    accent_color: '#0066cc',\n    foreground_color: '#ffffff'\n  },\n  client: {\n    name: 'John Doe',\n    cif: '12345678A',\n    address: 'Street 123',\n    phone: '+34 666 123 123',\n    email: 'john@example.com'\n  },\n  business: {\n    name: 'Business SL',\n    cif: 'B12345678',\n    address: 'Avenue 456',\n    phone: '+34 911 123 123',\n    email: 'business@example.com'\n  },\n  total: 1210,\n  subtotal: 1000,\n  tax_value: 210,\n  tax_percent: 21,\n  surcharge_value: 0,\n  surcharge_percent: 0,\n  observations: 'Thank you!',\n  payment_instructions: 'Bank transfer to ES00...',\n  RGPD: 'Your data is protected.',\n  type: 'invoice',\n  template: 'classic',\n  concepts: []\n})\n\n// Save the PDF\nfs.writeFileSync('invoice.pdf', Buffer.from(pdfBuffer))\n```\n\n### Express.js Integration\n\n```typescript\nimport express from 'express'\nimport { InvoSDK } from '@calltek/invo-sdk'\n\nconst app = express()\napp.use(express.json())\n\n// Initialize SDK (login is automatic on first request)\nconst sdk = new InvoSDK({\n  apiToken: process.env.INVO_API_TOKEN!\n})\n\n// Invoice creation endpoint\napp.post('/api/invoices', async (req, res) => {\n  try {\n    const result = await sdk.store(req.body, req.body.callback)\n    res.json(result)\n  } catch (error) {\n    res.status(500).json({ error: error.message })\n  }\n})\n\napp.listen(3000, () => {\n  console.log('Server running on port 3000')\n})\n```\n\n### NestJS Integration\n\n```typescript\nimport { Injectable } from '@nestjs/common'\nimport { ConfigService } from '@nestjs/config'\nimport { InvoSDK } from '@calltek/invo-sdk'\n\n@Injectable()\nexport class InvoiceService {\n  private sdk: InvoSDK\n\n  constructor(private configService: ConfigService) {\n    this.sdk = new InvoSDK({\n      apiToken: this.configService.get('INVO_API_TOKEN')!\n    })\n  }\n\n  async createInvoice(data: CreateInvoiceDto, callback?: string) {\n    return this.sdk.store(data, callback)\n  }\n\n  async readInvoice(file: File) {\n    return this.sdk.read(file)\n  }\n\n  async generatePDF(data: MakeupPDFDto) {\n    return this.sdk.pdf(data)\n  }\n}\n```\n\n### Multi-tenant with Different API Tokens\n\n```typescript\nimport { InvoSDK } from '@calltek/invo-sdk'\n\n// Tenant 1 - Each API token is already associated with a workspace\nconst tenant1SDK = new InvoSDK({\n  apiToken: process.env.TENANT1_API_TOKEN!\n})\n\n// Tenant 2 - Different API token for different workspace\nconst tenant2SDK = new InvoSDK({\n  apiToken: process.env.TENANT2_API_TOKEN!\n})\n\n// Each operates independently with its own workspace\nawait tenant1SDK.store({...})\nawait tenant2SDK.store({...})\n```\n\n## API Reference\n\n### Main Methods\n\n#### `store(data, callback?): Promise<CreateInvoiceResult>`\nCreate and submit a new invoice.\n\n```typescript\nconst result = await sdk.store(invoiceData, 'https://webhook.url')\n```\n\n#### `read(file): Promise<InvoiceReaderResult>`\nRead and parse invoice data from a file.\n\n```typescript\nconst data = await sdk.read(file)\n```\n\n#### `pdf(data): Promise<ArrayBuffer>`\nGenerate a PDF invoice with custom branding.\n\n```typescript\nconst pdfBuffer = await sdk.pdf(pdfData)\n```\n\n#### `request<T>(endpoint, method?, body?): Promise<T>`\nMake a generic authenticated request.\n\n```typescript\nconst data = await sdk.request('/endpoint', 'GET')\n```\n\n### Utility Methods\n\n#### `getAccessToken(): string | null`\nGet the current access token.\n\n#### `getUser(): User | null`\nGet the current user information.\n\n#### `isAuthenticated(): boolean`\nCheck if authenticated.\n\n### Properties\n\n#### `environment: 'production' | 'sandbox'`\nCurrent environment (read-only).\n\n```typescript\nconsole.log(sdk.environment) // 'production'\n```\n\n## Types\n\n```typescript\ninterface CreateInvoiceDto {\n  issueDate: string              // ISO 8601 format\n  invoiceNumber: string          // 1-60 chars\n  externalId: string             // 1-100 chars\n  totalAmount: number            // Total including taxes\n  customerName: string           // 1-120 chars\n  customerTaxId: string          // NIF/CIF\n  emitterName: string            // 1-120 chars\n  emitterTaxId: string           // NIF/CIF\n  taxLines: InvoiceTaxLineDto[]  // Minimum 1 required\n  currency?: string              // Default: \"EUR\"\n  type?: string                  // Default: \"F1\"\n  description?: string           // 1-500 chars\n}\n\ninterface InvoiceTaxLineDto {\n  taxRate: number                // 0, 4, 5, 10, 21\n  baseAmount: number             // Base amount\n  taxAmount: number              // Tax amount\n  taxType?: string               // Default: \"01\" (IVA)\n  surchargeAmount?: number       // Surcharge amount\n  surchargeRate?: number         // Surcharge rate\n  taxExemptionReason?: string    // E1-E6\n  regimeKey?: string             // \"01\"-\"19\"\n}\n\ninterface CreateInvoiceResult {\n  success: boolean\n  invoiceId: string              // UUID\n  chainIndex: number             // VeriFactu chain index\n}\n```\n\n### Error Classes\n\n```typescript\nimport {\n  AuthError,\n  InvalidCredentialsError,\n  TokenExpiredError,\n  NetworkError,\n} from '@calltek/invo-sdk'\n\ntry {\n  await sdk.store({...})\n} catch (error) {\n  if (error instanceof InvalidCredentialsError) {\n    console.error('Invalid API token')\n  } else if (error instanceof NetworkError) {\n    console.error('Network error')\n  } else if (error instanceof TokenExpiredError) {\n    console.error('Token expired')\n  }\n}\n```\n\n## API Token Management\n\nAPI tokens must be obtained from your INVO account dashboard. Token management (creation, listing, revocation) is done through the INVO web platform.\n\n**Token Format:**\n```\ninvo_tok_prod_*  → production\ninvo_tok_sand_*  → sandbox\n```\n\nThe SDK automatically detects the environment from the token prefix.\n\n## Environment URLs\n\n- **Production**: `https://api.invo.rest`\n- **Sandbox**: `https://sandbox.invo.rest`\n\n## Documentation\n\n- **[API Tokens Guide](./docs/API_TOKENS.md)** - Complete guide on API tokens\n- **[Examples](./docs/EXAMPLES.md)** - Usage examples and integration patterns\n- **[Testing](./docs/TESTING.md)** - Testing guide\n- **[Publishing](./docs/PUBLISHING.md)** - Publishing guide\n\n## Development\n\n```bash\n# Install dependencies\nnpm install\n\n# Build\nnpm run build\n\n# Watch mode\nnpm run build:watch\n\n# Clean\nnpm run clean\n\n# Generate types from Swagger\nnpm run types          # Production\nnpm run types:sandbox  # Sandbox\n```\n\n## Migration from v1.x\n\nIf you're migrating from v1.x:\n\n### ❌ Old API (v1.x)\n\n```typescript\nimport { createInvoSDK } from 'invo-sdk'\n\nconst sdk = createInvoSDK({ email, password })\nawait sdk.login()\nawait sdk.createInvoice({...})\nawait sdk.logout()\n```\n\n### ✅ New API (v2.x)\n\n```typescript\nimport { InvoSDK } from '@calltek/invo-sdk'\n\nconst sdk = new InvoSDK({ apiToken })\n// Login is automatic!\nawait sdk.store({...})\n// No logout needed\n```\n\n**Breaking Changes:**\n- Email/password authentication removed (API token only)\n- `createInvoice` renamed to `store`\n- `readInvoice` renamed to `read`\n- `makeupInvoice` renamed to `pdf`\n- `login()`, `logout()`, `refreshAccessToken()` removed\n- `createInvoSDK` and `createInvoSDKWithToken` helpers removed\n- Use `new InvoSDK()` directly\n\n## License\n\nMIT\n\n## Support\n\nFor issues and questions, please open an issue on [GitHub](https://github.com/calltek/invo-sdk/issues).\n","readmeFilename":"README.md"}