npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tgtone/core-sdk

v1.8.0

Published

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

Downloads

515

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

✅ Implementados (6 módulos)

| Módulo | Descripción | Coverage Backend | |--------|-------------|------------------| | tenants | Gestión de organizaciones | GET /:id, PUT /:id (100%) | | users | Gestión de usuarios e invitaciones | 7 endpoints completos (100%) | | applications | Catálogo de aplicaciones y roles | 11 endpoints completos (100%) | | subscriptions | Suscripciones de apps | POST /, GET /active (100%) | | payments | Pagos WebPay Plus | 5 endpoints completos (100%) | | activity | Logs de auditoría multi-tenant | 5 endpoints completos (100%) |

⏸️ Módulos Backend NO incluidos (uso interno/futuro)

Los siguientes módulos del backend NO están en el SDK por decisión de arquitectura:

  • apps - Gestión interna de apps (usar applications desde frontend)
  • billing - Facturación avanzada (no necesario por ahora)
  • dashboard - Stats agregados (solo para console)
  • email - Sistema de emails (backend-to-backend, no para clientes)
  • maintenance - Limpieza de logs (CRON interno)
  • auth - Autenticación (en @tgtone/auth-sdk separado)

📖 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

// Listar usuarios de un tenant
const users = await core.users.list(tenantId);

// Invitar nuevo usuario
await core.users.invite({
  email: '[email protected]',
  firstName: 'Juan',
  lastName: 'Pérez',
  tenantId,
  organizationalRole: 'admin',
  applicationAccess: [
    { applicationId: 'app-uuid', roleId: 'role-uuid' }
  ]
});

// Actualizar usuario
await core.users.update(userId, {
  firstName: 'Juan Carlos',
  organizationalRole: 'user'
});

// Actualizar permisos de aplicaciones
await core.users.updatePermissions(userId, {
  permissions: [
    { applicationId: 'app-uuid', roleId: 'role-uuid' }
  ]
});

// Obtener permisos del usuario autenticado
const permissions = await core.users.getMyPermissions();
// Resultado:
// {
//   userId: 'user-uuid',
//   tenantId: 'tenant-uuid',
//   organizationalRole: 'admin',
//   applications: [
//     {
//       applicationKey: 'crm',
//       applicationName: 'Zenith CRM',
//       roleKey: 'vendedor',
//       roleName: 'Vendedor Senior',
//       permissions: {
//         modules: {
//           contacts: { read: true, create: true, update: true, delete: true },
//           tickets: { read: true, create: true, assign: true, close: true },
//           reports: { read: true, export: true }
//         }
//       },
//       level: 1
//     }
//   ]
// }

// Verificar permisos con helper
import { PermissionsChecker } from '@tgtone/core-sdk';

const checker = new PermissionsChecker(permissions);

// Verificar permiso específico
if (checker.can('crm', 'contacts', 'create')) {
  console.log('Puede crear contactos');
}

// Verificar múltiples permisos
if (checker.canAll('crm', 'tickets', ['read', 'close'])) {
  console.log('Puede ver y cerrar tickets');
}

// Obtener acciones permitidas
const allowedActions = checker.getAllowedActions('crm', 'contacts');
// ['read', 'create', 'update', 'delete']

// Verificar rol organizacional
if (checker.isAdminOrOwner()) {
  console.log('Acceso completo a la consola');
}

// Verificar permisos específicos
const canCreateContact = permissions.applications
  .find(app => app.applicationKey === 'crm')
  ?.permissions?.includes('contacts.create');

// Reenviar invitación
await core.users.resendInvitation(userId);

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


🔗 Links

  • Documentación completa: docs/API.md
  • Repo: https://github.com/tgt-technology/tgtone-console
  • Auth SDK: https://www.npmjs.com/package/@tgtone/auth-sdk

📄 Licencia

MIT © TGT Technology


Versión actual: v1.4.0
Última actualización: 2025-11-13

Changelog v1.4.0:

  • ✅ Agregado interface ApplicationFeature con campos estructurados
  • ✅ Nuevos campos en Application:
    • longDescription - Descripción larga (HTML/Markdown) para páginas de detalle
    • features - Array de features estructurados (feature, description, icon)
  • ✅ Actualizado CreateApplicationDto con campos longDescription y features
  • ✅ Soporte para renderizado dinámico de features con iconos Lucide React

Changelog v1.3.0:

  • ✅ Agregado enum ApplicationStatus (ACTIVE, COMING_SOON, INACTIVE)
  • ✅ Nuevos campos en Application:
    • status - estado de la aplicación
    • launchDate - fecha estimada de lanzamiento
    • comingSoonMessage - mensaje personalizado para apps próximamente
  • ✅ Apps con status COMING_SOON aparecen en listados pero sin planes disponibles
  • ✅ Actualizado CreateApplicationDto con nuevos campos opcionales

Changelog v1.2.0:

  • ✅ Actualizado tipo ApplicationPlan con campos completos del schema:
    • monthlyPrice y annualPrice (reemplaza price y billingCycle)
    • features (JSON flexible: string[] o Record<string, unknown>)
    • isPopular - marcar planes destacados
    • displayOrder - orden de visualización
    • logRetentionDays - días de retención de logs
    • maxLogsPerMonth - límite opcional de logs por mes
  • ✅ Agregados tipos: ApplicationPlansResponse, ApplicationWithPlans
  • ✅ SDK ahora refleja exactamente la estructura del backend

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