SDK de acceso a TGT One Console Core API - Gestión de tenants, usuarios, aplicaciones, suscripciones, pagos (WebPay) y auditoría
npm install @tgtone/core-sdkSDK 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.
---
``bash`
npm install @tgtone/core-sdk
Dependencias:
- Requiere @tgtone/auth-sdk para autenticación (peer dependency opcional)
---
`typescript
import { TGTCoreSDK } from '@tgtone/core-sdk';
const core = new TGTCoreSDK({
apiUrl: 'https://identity.tgtone.cl/api',
getToken: () => localStorage.getItem('tgtone_auth_token'),
debug: true // Opcional: logs en consola
});
`
`typescript
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://identity.tgtone.cl/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ó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%) |notifications
| | Notificaciones multi-tenant/app | 6 endpoints completos (100%) |
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:
- Quick Start Guide - Guía rápida con ejemplos prácticos
- API Reference - Referencia completa de todos los métodos y tipos
---
`typescript`
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
}
---
`typescript
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() - 401error.isForbidden()
- - 403error.isNotFound()
- - 404error.isConflict()
- - 409error.isValidationError()
- - 400
---
typescript
const tenant = await core.tenants.get(tenantId);
await core.tenants.update(tenantId, { name: 'Nueva Empresa' });
const stats = await core.tenants.getStats(tenantId);
`$3
`typescript
// Listar usuarios de un tenant
const users = await core.users.list(tenantId);// Invitar nuevo usuario
await core.users.invite({
email: 'nuevo@empresa.cl',
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);
`$3
`typescript
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
});
`$3
Backend: Crear notificación
`typescript
// En cualquier servicio de tu backend
await core.notifications.create({
appId: 'baco',
title: 'Análisis completado',
message: 'La barrica B-001 está lista para revisión',
type: 'success', // info | success | warning | error
priority: 'normal', // low | normal | high | urgent
actionUrl: '/analisis/123' // opcional: link al detalle
});
`Obtener notificaciones con filtros
`typescript
// Obtener solo no leídas (default)
const { notifications } = await core.notifications.getNotifications({
appId: 'baco',
unreadOnly: true, // default: true
includeDeleted: false, // default: false
take: 50
});// Obtener todas (leídas y no leídas)
const { notifications } = await core.notifications.getNotifications({
appId: 'baco',
unreadOnly: false
});
// Obtener historial completo (incluye eliminadas)
const { notifications } = await core.notifications.getHistory({
appId: 'baco',
take: 100
});
`Campos de respuesta
`typescript
interface Notification {
id: string;
appId: string;
title: string;
message: string;
type: 'info' | 'success' | 'warning' | 'error';
priority: 'low' | 'normal' | 'high' | 'urgent';
actionUrl?: string;
metadata?: Record;
createdAt: string;
isRead: boolean;
readAt?: string;
isDeleted?: boolean; // true si fue soft-deleted
deletedAt?: string; // fecha de eliminación
}
`Frontend: Hook de polling (15s)
`typescript
// hooks/useNotifications.ts
import { useEffect, useState } from 'react';
import { TGTCoreSDK, Notification } from '@tgtone/core-sdk';export function useNotifications(core: TGTCoreSDK, appId: string) {
const [notifications, setNotifications] = useState([]);
const [unreadCount, setUnreadCount] = useState(0);
useEffect(() => {
const fetch = async () => {
const { notifications } = await core.notifications.getNotifications({
appId,
unreadOnly: false // Obtener todas las activas
});
setNotifications(notifications);
const { count } = await core.notifications.getUnreadCount(appId);
setUnreadCount(count);
};
fetch();
const interval = setInterval(fetch, 15000); // polling cada 15s
return () => clearInterval(interval);
}, [appId]);
const markAsRead = async (id: string) => {
await core.notifications.markAsRead(id);
setUnreadCount(prev => Math.max(0, prev - 1));
};
return { notifications, unreadCount, markAsRead };
}
`Frontend: Componente UI
`tsx
function NotificationBell() {
const { notifications, unreadCount, markAsRead } = useNotifications(core, 'baco'); return (
{unreadCount > 0 && {unreadCount} }
{notifications.map(n => (
markAsRead(n.id)}>
{n.title}
{n.message}
))}
);
}
`$3
`typescript
// 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
- Auth SDK: https://www.npmjs.com/package/@tgtone/auth-sdk---
📄 Licencia
MIT © TGT Technology
---
Versión actual: v1.9.4
Última actualización: 2025-12-18
Changelog v1.9.4:
- ✅ Soft-delete de notificaciones con retención de 7 días
- ✅ Nuevo método
getHistory() - Obtener historial completo incluyendo eliminadas
- ✅ Nuevo parámetro includeDeleted en getNotifications()
- ✅ Nuevos campos en respuesta: isDeleted, deletedAt
- ✅ Las notificaciones no leídas NUNCA se borran automáticamenteChangelog v1.9.0:
- ✅ Nuevo módulo
notifications - Sistema de notificaciones multi-tenant/app
- ✅ Métodos: create(), getNotifications(), getUnreadCount(), markAsRead(), markAllAsRead(), delete()
- ✅ Tipos: Notification, CreateNotificationDto, NotificationFilters
- ✅ Soporte polling (15s recomendado) para frontendChangelog 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 ReactChangelog 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 opcionalesChangelog v1.2.0:
- ✅ Actualizado tipo
ApplicationPlan con campos completos del schema:
- monthlyPrice y annualPrice (reemplaza price y billingCycle)
- features (JSON flexible: string[] o Record)
- 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 backendChangelog 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`