JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 58
  • Score
    100M100P100Q62095F
  • License MIT

SDK de acceso a TGT One Console Core API - Gestión de tenants, usuarios, aplicaciones, suscripciones, pagos (WebPay) y auditoría

Package Exports

  • @tgtone/core-sdk
  • @tgtone/core-sdk/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@tgtone/core-sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

🚀 TGT One Core SDK

SDK oficial para integración con TGT One Console Core API.

Gestión de tenants, usuarios, aplicaciones, suscripciones, pagos (WebPay Plus) y logs de auditoría.


📦 Instalación

npm install @tgtone/core-sdk

Dependencias:

  • Requiere @tgtone/auth-sdk para autenticación (peer dependency opcional)

⚡ Quick Start

1. Inicializar el SDK

import { TGTCoreSDK } from '@tgtone/core-sdk';

const core = new TGTCoreSDK({
  apiUrl: 'https://tgtone-console-backend.run.app/api',
  getToken: () => localStorage.getItem('tgtone_auth_token'),
  debug: true // Opcional: logs en consola
});

2. Usar con Auth SDK

import { TGTAuthClient } from '@tgtone/auth-sdk';
import { TGTCoreSDK } from '@tgtone/core-sdk';

// 1. Autenticación
const auth = new TGTAuthClient({
  identityUrl: 'https://identity.tgtone.cl',
  appDomain: window.location.hostname
});

const session = await auth.checkSession();

// 2. Core SDK con token del Auth
const core = new TGTCoreSDK({
  apiUrl: 'https://tgtone-console-backend.run.app/api',
  getToken: () => localStorage.getItem('tgtone_auth_token')
});

// 3. Usar módulos
const tenant = await core.tenants.get(session.tenantId);
console.log('Tenant:', tenant.name);

📚 Módulos Disponibles

Módulo Descripción Métodos
core.tenants CRUD de tenants get(), list(), create(), update(), remove(), getStats()
core.users Gestión de usuarios list(), get(), invite(), update(), updatePermissions(), remove(), reactivate()
core.applications Catálogo de apps list(), get(), getBySlug(), listSubscribed()
core.activity Logs de auditoría getLogs(), getLogsFiltered(), getStats(), exportLogs(), log()
core.subscriptions Suscripciones list(), get(), create(), update(), cancel()
core.payments Pagos WebPay Plus create(), get(), list(), calculateTotal()

📖 Documentación Completa:


🔧 Configuración

interface TGTCoreConfig {
  // URL base del backend (sin trailing slash)
  apiUrl: string;
  
  // Función para obtener el token JWT
  getToken: () => string | null;
  
  // Habilitar logs de debug (default: false)
  debug?: boolean;
  
  // Timeout de requests en ms (default: 30000)
  timeout?: number;
  
  // Headers adicionales
  headers?: Record<string, string>;
}

🛡️ Manejo de Errores

import { TGTCoreError } from '@tgtone/core-sdk';

try {
  const tenant = await core.tenants.get('invalid-id');
} catch (error) {
  if (error instanceof TGTCoreError) {
    if (error.isUnauthorized()) {
      console.log('Token expirado, redirigir a login');
    } else if (error.isNotFound()) {
      console.log('Tenant no encontrado');
    } else {
      console.error('Error API:', error.message);
    }
  }
}

Métodos de error:

  • error.isUnauthorized() - 401
  • error.isForbidden() - 403
  • error.isNotFound() - 404
  • error.isConflict() - 409
  • error.isValidationError() - 400

📖 Ejemplos Rápidos

Tenants

const tenant = await core.tenants.get(tenantId);
await core.tenants.update(tenantId, { name: 'Nueva Empresa' });
const stats = await core.tenants.getStats(tenantId);

Usuarios

const users = await core.users.list(tenantId);
await core.users.invite({
  email: 'nuevo@empresa.cl',
  firstName: 'Juan',
  lastName: 'Pérez',
  tenantId,
  role: 'admin'
});

Activity Logs

const logs = await core.activity.getLogsFiltered(tenantId, {
  level: 'error',
  startDate: '2025-01-01'
});

await core.activity.log({
  action: 'user.login',
  level: 'success',
  resource: 'user',
  resourceId: userId
});

Pagos (WebPay Plus)

// Calcular total a pagar
const total = await core.payments.calculateTotal();
console.log('Total:', total.totalAmount);

// Crear pago e ir a WebPay
const payment = await core.payments.create({
  tenantId: 'tenant-uuid',
  description: 'Suscripción mensual - CRM Pro',
  operationType: 'SUBSCRIPTION_PURCHASE',
  items: [
    {
      subscriptionId: 'sub-uuid',
      planId: 'plan-uuid',
      description: 'CRM Pro - 10 usuarios',
      quantity: 10,
      unitPrice: 9990,
      totalPrice: 99900
    }
  ]
});

// Redirigir a WebPay
window.location.href = payment.webpayUrl;

// Obtener estado del pago (después del callback)
const paymentStatus = await core.payments.get(payment.payment.id);
console.log('Estado:', paymentStatus.status); // AUTHORIZED, FAILED, etc.

Ver más ejemplos en Quick Start Guide



📄 Licencia

MIT © TGT Technology


Versión actual: v1.1.0
Última actualización: 2025-10-30

Changelog v1.1.0:

  • ✅ Agregado módulo payments con soporte para WebPay Plus (Transbank Chile)
  • ✅ Métodos: create(), get(), list(), calculateTotal()
  • ✅ Tipos: Payment, PaymentItem, CreatePaymentDto, PaymentStatus, PaymentOperationType