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-sdkDependencias:
- Requiere
@tgtone/auth-sdkpara 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%) |
notifications |
Notificaciones multi-tenant/app | 6 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 (usarapplicationsdesde 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-sdkseparado)
📖 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
🔧 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()- 401error.isForbidden()- 403error.isNotFound()- 404error.isConflict()- 409error.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: '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);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
});Notifications
// Backend: Crear notificación
await core.notifications.create({
appId: 'baco',
title: 'Análisis completado',
message: 'Barrica B-001 lista',
type: 'success'
});
// Frontend: Polling cada 15s
const { notifications } = await core.notifications.getNotifications({ appId: 'baco' });
const { count } = await core.notifications.getUnreadCount('baco');
// Marcar como leída
await core.notifications.markAsRead(notificationId);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.9.0
Última actualización: 2025-12-16
Changelog 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 frontend
Changelog v1.4.0:
- ✅ Agregado interface
ApplicationFeaturecon campos estructurados - ✅ Nuevos campos en
Application:longDescription- Descripción larga (HTML/Markdown) para páginas de detallefeatures- Array de features estructurados (feature, description, icon)
- ✅ Actualizado
CreateApplicationDtocon camposlongDescriptionyfeatures - ✅ 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ónlaunchDate- fecha estimada de lanzamientocomingSoonMessage- mensaje personalizado para apps próximamente
- ✅ Apps con status
COMING_SOONaparecen en listados pero sin planes disponibles - ✅ Actualizado
CreateApplicationDtocon nuevos campos opcionales
Changelog v1.2.0:
- ✅ Actualizado tipo
ApplicationPlancon campos completos del schema:monthlyPriceyannualPrice(reemplazapriceybillingCycle)features(JSON flexible: string[] o Record<string, unknown>)isPopular- marcar planes destacadosdisplayOrder- orden de visualizaciónlogRetentionDays- días de retención de logsmaxLogsPerMonth- 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
paymentscon soporte para WebPay Plus (Transbank Chile) - ✅ Métodos:
create(),get(),list(),calculateTotal() - ✅ Tipos:
Payment,PaymentItem,CreatePaymentDto,PaymentStatus,PaymentOperationType