6 Commits

Author SHA1 Message Date
Francisco Gaona
c7282ee2a0 WIP - do not display id on list views and correctly format datetime fields 2026-01-26 19:37:17 +01:00
Francisco Gaona
ce65817670 WIP - do not trim history 2026-01-26 19:14:33 +01:00
Francisco Gaona
fe51355d29 WIP - use AI assistant to create records in the system 2026-01-18 09:15:06 +01:00
Francisco Gaona
4f466d7992 WIP - create records via AI Assistant more flexible and dynamic 2026-01-18 08:47:51 +01:00
Francisco Gaona
c822017ef1 WIP - some success creating related records 2026-01-18 05:24:41 +01:00
Francisco Gaona
8b192ba7f5 WIP - using deep agent to create complex workflow 2026-01-18 04:45:15 +01:00
35 changed files with 459 additions and 2516 deletions

View File

@@ -1,5 +1,5 @@
NUXT_PORT=3001 NUXT_PORT=3001
NUXT_HOST=0.0.0.0 NUXT_HOST=0.0.0.0
# Nitro BFF backend URL (server-only, not exposed to client) # Point Nuxt to the API container (not localhost)
BACKEND_URL=https://backend.routebox.co NUXT_PUBLIC_API_BASE_URL=https://tenant1.routebox.co

View File

@@ -1,95 +0,0 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = async function(knex) {
// Check if layout_type column already exists (in case of partial migration)
const hasLayoutType = await knex.schema.hasColumn('page_layouts', 'layout_type');
// Check if the old index exists
const [indexes] = await knex.raw(`SHOW INDEX FROM page_layouts WHERE Key_name = 'page_layouts_object_id_is_default_index'`);
const hasOldIndex = indexes.length > 0;
// Check if foreign key exists
const [fks] = await knex.raw(`
SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'page_layouts'
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
AND CONSTRAINT_NAME = 'page_layouts_object_id_foreign'
`);
const hasForeignKey = fks.length > 0;
if (hasOldIndex) {
// First, drop the foreign key constraint that depends on the index (if it exists)
if (hasForeignKey) {
await knex.schema.alterTable('page_layouts', (table) => {
table.dropForeign(['object_id']);
});
}
// Now we can safely drop the old index
await knex.schema.alterTable('page_layouts', (table) => {
table.dropIndex(['object_id', 'is_default']);
});
}
// Add layout_type column if it doesn't exist
if (!hasLayoutType) {
await knex.schema.alterTable('page_layouts', (table) => {
// Add layout_type column to distinguish between detail/edit layouts and list view layouts
// Default to 'detail' for existing layouts
table.enum('layout_type', ['detail', 'list']).notNullable().defaultTo('detail').after('name');
});
}
// Check if new index exists
const [newIndexes] = await knex.raw(`SHOW INDEX FROM page_layouts WHERE Key_name = 'page_layouts_object_id_layout_type_is_default_index'`);
const hasNewIndex = newIndexes.length > 0;
if (!hasNewIndex) {
// Create new index including layout_type
await knex.schema.alterTable('page_layouts', (table) => {
table.index(['object_id', 'layout_type', 'is_default']);
});
}
// Re-check if foreign key exists (may have been dropped above or in previous attempt)
const [fksAfter] = await knex.raw(`
SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'page_layouts'
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
AND CONSTRAINT_NAME = 'page_layouts_object_id_foreign'
`);
if (fksAfter.length === 0) {
// Re-add the foreign key constraint
await knex.schema.alterTable('page_layouts', (table) => {
table.foreign('object_id').references('id').inTable('object_definitions').onDelete('CASCADE');
});
}
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = async function(knex) {
// Drop the foreign key first
await knex.schema.alterTable('page_layouts', (table) => {
table.dropForeign(['object_id']);
});
// Drop the new index and column, restore old index
await knex.schema.alterTable('page_layouts', (table) => {
table.dropIndex(['object_id', 'layout_type', 'is_default']);
table.dropColumn('layout_type');
table.index(['object_id', 'is_default']);
});
// Re-add the foreign key constraint
await knex.schema.alterTable('page_layouts', (table) => {
table.foreign('object_id').references('id').inTable('object_definitions').onDelete('CASCADE');
});
};

View File

@@ -10,14 +10,14 @@ export class AppBuilderService {
// Runtime endpoints // Runtime endpoints
async getApps(tenantId: string, userId: string) { async getApps(tenantId: string, userId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
// For now, return all apps // For now, return all apps
// In production, you'd filter by user permissions // In production, you'd filter by user permissions
return App.query(knex).withGraphFetched('pages').orderBy('label', 'asc'); return App.query(knex).withGraphFetched('pages').orderBy('label', 'asc');
} }
async getApp(tenantId: string, slug: string, userId: string) { async getApp(tenantId: string, slug: string, userId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await App.query(knex) const app = await App.query(knex)
.findOne({ slug }) .findOne({ slug })
.withGraphFetched('pages'); .withGraphFetched('pages');
@@ -35,7 +35,7 @@ export class AppBuilderService {
pageSlug: string, pageSlug: string,
userId: string, userId: string,
) { ) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getApp(tenantId, appSlug, userId); const app = await this.getApp(tenantId, appSlug, userId);
const page = await AppPage.query(knex).findOne({ const page = await AppPage.query(knex).findOne({
@@ -52,12 +52,12 @@ export class AppBuilderService {
// Setup endpoints // Setup endpoints
async getAllApps(tenantId: string) { async getAllApps(tenantId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
return App.query(knex).withGraphFetched('pages').orderBy('label', 'asc'); return App.query(knex).withGraphFetched('pages').orderBy('label', 'asc');
} }
async getAppForSetup(tenantId: string, slug: string) { async getAppForSetup(tenantId: string, slug: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await App.query(knex) const app = await App.query(knex)
.findOne({ slug }) .findOne({ slug })
.withGraphFetched('pages'); .withGraphFetched('pages');
@@ -77,7 +77,7 @@ export class AppBuilderService {
description?: string; description?: string;
}, },
) { ) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
return App.query(knex).insert({ return App.query(knex).insert({
...data, ...data,
displayOrder: 0, displayOrder: 0,
@@ -92,7 +92,7 @@ export class AppBuilderService {
description?: string; description?: string;
}, },
) { ) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getAppForSetup(tenantId, slug); const app = await this.getAppForSetup(tenantId, slug);
return App.query(knex).patchAndFetchById(app.id, data); return App.query(knex).patchAndFetchById(app.id, data);
@@ -109,7 +109,7 @@ export class AppBuilderService {
sortOrder?: number; sortOrder?: number;
}, },
) { ) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getAppForSetup(tenantId, appSlug); const app = await this.getAppForSetup(tenantId, appSlug);
return AppPage.query(knex).insert({ return AppPage.query(knex).insert({
@@ -133,7 +133,7 @@ export class AppBuilderService {
sortOrder?: number; sortOrder?: number;
}, },
) { ) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getAppForSetup(tenantId, appSlug); const app = await this.getAppForSetup(tenantId, appSlug);
const page = await AppPage.query(knex).findOne({ const page = await AppPage.query(knex).findOne({

View File

@@ -1,19 +1,15 @@
import { import {
Controller, Controller,
Post, Post,
Get,
Body, Body,
UnauthorizedException, UnauthorizedException,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Req, Req,
UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator'; import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { TenantId } from '../tenant/tenant.decorator'; import { TenantId } from '../tenant/tenant.decorator';
import { JwtAuthGuard } from './jwt-auth.guard';
import { CurrentUser } from './current-user.decorator';
class LoginDto { class LoginDto {
@IsEmail() @IsEmail()
@@ -115,15 +111,4 @@ export class AuthController {
// This endpoint exists for consistency and potential future enhancements // This endpoint exists for consistency and potential future enhancements
return { message: 'Logged out successfully' }; return { message: 'Logged out successfully' };
} }
@UseGuards(JwtAuthGuard)
@Get('me')
async me(@CurrentUser() user: any, @TenantId() tenantId: string) {
// Return the current authenticated user info
return {
id: user.userId,
email: user.email,
tenantId: tenantId || user.tenantId,
};
}
} }

View File

@@ -29,7 +29,7 @@ export class AuthService {
} }
// Otherwise, validate as tenant user // Otherwise, validate as tenant user
const tenantDb = await this.tenantDbService.getTenantKnexById(tenantId); const tenantDb = await this.tenantDbService.getTenantKnex(tenantId);
const user = await tenantDb('users') const user = await tenantDb('users')
.where({ email }) .where({ email })
@@ -113,7 +113,7 @@ export class AuthService {
} }
// Otherwise, register as tenant user // Otherwise, register as tenant user
const tenantDb = await this.tenantDbService.getTenantKnexById(tenantId); const tenantDb = await this.tenantDbService.getTenantKnex(tenantId);
const hashedPassword = await bcrypt.hash(password, 10); const hashedPassword = await bcrypt.hash(password, 10);

View File

@@ -1,6 +1,4 @@
import { IsString, IsUUID, IsBoolean, IsOptional, IsObject, IsIn } from 'class-validator'; import { IsString, IsUUID, IsBoolean, IsOptional, IsObject } from 'class-validator';
export type PageLayoutType = 'detail' | 'list';
export class CreatePageLayoutDto { export class CreatePageLayoutDto {
@IsString() @IsString()
@@ -9,25 +7,18 @@ export class CreatePageLayoutDto {
@IsUUID() @IsUUID()
objectId: string; objectId: string;
@IsIn(['detail', 'list'])
@IsOptional()
layoutType?: PageLayoutType = 'detail';
@IsBoolean() @IsBoolean()
@IsOptional() @IsOptional()
isDefault?: boolean; isDefault?: boolean;
@IsObject() @IsObject()
layoutConfig: { layoutConfig: {
// For detail layouts: grid-based field positions
fields: Array<{ fields: Array<{
fieldId: string; fieldId: string;
x?: number; x: number;
y?: number; y: number;
w?: number; w: number;
h?: number; h: number;
// For list layouts: field order (optional, defaults to array index)
order?: number;
}>; }>;
relatedLists?: string[]; relatedLists?: string[];
}; };
@@ -51,11 +42,10 @@ export class UpdatePageLayoutDto {
layoutConfig?: { layoutConfig?: {
fields: Array<{ fields: Array<{
fieldId: string; fieldId: string;
x?: number; x: number;
y?: number; y: number;
w?: number; w: number;
h?: number; h: number;
order?: number;
}>; }>;
relatedLists?: string[]; relatedLists?: string[];
}; };

View File

@@ -10,7 +10,7 @@ import {
Query, Query,
} from '@nestjs/common'; } from '@nestjs/common';
import { PageLayoutService } from './page-layout.service'; import { PageLayoutService } from './page-layout.service';
import { CreatePageLayoutDto, UpdatePageLayoutDto, PageLayoutType } from './dto/page-layout.dto'; import { CreatePageLayoutDto, UpdatePageLayoutDto } from './dto/page-layout.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { TenantId } from '../tenant/tenant.decorator'; import { TenantId } from '../tenant/tenant.decorator';
@@ -25,21 +25,13 @@ export class PageLayoutController {
} }
@Get() @Get()
findAll( findAll(@TenantId() tenantId: string, @Query('objectId') objectId?: string) {
@TenantId() tenantId: string, return this.pageLayoutService.findAll(tenantId, objectId);
@Query('objectId') objectId?: string,
@Query('layoutType') layoutType?: PageLayoutType,
) {
return this.pageLayoutService.findAll(tenantId, objectId, layoutType);
} }
@Get('default/:objectId') @Get('default/:objectId')
findDefaultByObject( findDefaultByObject(@TenantId() tenantId: string, @Param('objectId') objectId: string) {
@TenantId() tenantId: string, return this.pageLayoutService.findDefaultByObject(tenantId, objectId);
@Param('objectId') objectId: string,
@Query('layoutType') layoutType?: PageLayoutType,
) {
return this.pageLayoutService.findDefaultByObject(tenantId, objectId, layoutType || 'detail');
} }
@Get(':id') @Get(':id')

View File

@@ -1,26 +1,24 @@
import { Injectable, NotFoundException } from '@nestjs/common'; import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantDatabaseService } from '../tenant/tenant-database.service'; import { TenantDatabaseService } from '../tenant/tenant-database.service';
import { CreatePageLayoutDto, UpdatePageLayoutDto, PageLayoutType } from './dto/page-layout.dto'; import { CreatePageLayoutDto, UpdatePageLayoutDto } from './dto/page-layout.dto';
@Injectable() @Injectable()
export class PageLayoutService { export class PageLayoutService {
constructor(private tenantDbService: TenantDatabaseService) {} constructor(private tenantDbService: TenantDatabaseService) {}
async create(tenantId: string, createDto: CreatePageLayoutDto) { async create(tenantId: string, createDto: CreatePageLayoutDto) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const layoutType = createDto.layoutType || 'detail';
// If this layout is set as default, unset other defaults for the same object and layout type // If this layout is set as default, unset other defaults for the same object
if (createDto.isDefault) { if (createDto.isDefault) {
await knex('page_layouts') await knex('page_layouts')
.where({ object_id: createDto.objectId, layout_type: layoutType }) .where({ object_id: createDto.objectId })
.update({ is_default: false }); .update({ is_default: false });
} }
const [id] = await knex('page_layouts').insert({ const [id] = await knex('page_layouts').insert({
name: createDto.name, name: createDto.name,
object_id: createDto.objectId, object_id: createDto.objectId,
layout_type: layoutType,
is_default: createDto.isDefault || false, is_default: createDto.isDefault || false,
layout_config: JSON.stringify(createDto.layoutConfig), layout_config: JSON.stringify(createDto.layoutConfig),
description: createDto.description || null, description: createDto.description || null,
@@ -31,8 +29,8 @@ export class PageLayoutService {
return result; return result;
} }
async findAll(tenantId: string, objectId?: string, layoutType?: PageLayoutType) { async findAll(tenantId: string, objectId?: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
let query = knex('page_layouts'); let query = knex('page_layouts');
@@ -40,16 +38,12 @@ export class PageLayoutService {
query = query.where({ object_id: objectId }); query = query.where({ object_id: objectId });
} }
if (layoutType) {
query = query.where({ layout_type: layoutType });
}
const layouts = await query.orderByRaw('is_default DESC, name ASC'); const layouts = await query.orderByRaw('is_default DESC, name ASC');
return layouts; return layouts;
} }
async findOne(tenantId: string, id: string) { async findOne(tenantId: string, id: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const layout = await knex('page_layouts').where({ id }).first(); const layout = await knex('page_layouts').where({ id }).first();
@@ -60,26 +54,27 @@ export class PageLayoutService {
return layout; return layout;
} }
async findDefaultByObject(tenantId: string, objectId: string, layoutType: PageLayoutType = 'detail') { async findDefaultByObject(tenantId: string, objectId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
const layout = await knex('page_layouts') const layout = await knex('page_layouts')
.where({ object_id: objectId, is_default: true, layout_type: layoutType }) .where({ object_id: objectId, is_default: true })
.first(); .first();
return layout || null; return layout || null;
} }
async update(tenantId: string, id: string, updateDto: UpdatePageLayoutDto) { async update(tenantId: string, id: string, updateDto: UpdatePageLayoutDto) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
// Check if layout exists // Check if layout exists
const layout = await this.findOne(tenantId, id); await this.findOne(tenantId, id);
// If setting as default, unset other defaults for the same object and layout type // If setting as default, unset other defaults for the same object
if (updateDto.isDefault) { if (updateDto.isDefault) {
const layout = await this.findOne(tenantId, id);
await knex('page_layouts') await knex('page_layouts')
.where({ object_id: layout.object_id, layout_type: layout.layout_type }) .where({ object_id: layout.object_id })
.whereNot({ id }) .whereNot({ id })
.update({ is_default: false }); .update({ is_default: false });
} }
@@ -112,7 +107,7 @@ export class PageLayoutService {
} }
async remove(tenantId: string, id: string) { async remove(tenantId: string, id: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId); const knex = await this.tenantDbService.getTenantKnex(tenantId);
await this.findOne(tenantId, id); await this.findOne(tenantId, id);

View File

@@ -16,45 +16,26 @@ import { TenantId } from './tenant.decorator';
export class TenantController { export class TenantController {
constructor(private readonly tenantDbService: TenantDatabaseService) {} constructor(private readonly tenantDbService: TenantDatabaseService) {}
/**
* Helper to find tenant by ID or domain
*/
private async findTenant(identifier: string) {
const centralPrisma = getCentralPrisma();
// Check if identifier is a CUID (tenant ID) or a domain
const isCUID = /^c[a-z0-9]{24}$/i.test(identifier);
if (isCUID) {
// Look up by tenant ID directly
return centralPrisma.tenant.findUnique({
where: { id: identifier },
select: { id: true, integrationsConfig: true },
});
} else {
// Look up by domain
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain: identifier },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
return domainRecord?.tenant;
}
}
/** /**
* Get integrations configuration for the current tenant * Get integrations configuration for the current tenant
*/ */
@Get('integrations') @Get('integrations')
async getIntegrationsConfig(@TenantId() tenantIdentifier: string) { async getIntegrationsConfig(@TenantId() domain: string) {
const tenant = await this.findTenant(tenantIdentifier); const centralPrisma = getCentralPrisma();
if (!tenant || !tenant.integrationsConfig) { // Look up tenant by domain
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
if (!domainRecord?.tenant || !domainRecord.tenant.integrationsConfig) {
return { data: null }; return { data: null };
} }
// Decrypt the config // Decrypt the config
const config = this.tenantDbService.decryptIntegrationsConfig( const config = this.tenantDbService.decryptIntegrationsConfig(
tenant.integrationsConfig as any, domainRecord.tenant.integrationsConfig as any,
); );
// Return config with sensitive fields masked // Return config with sensitive fields masked
@@ -68,26 +49,31 @@ export class TenantController {
*/ */
@Put('integrations') @Put('integrations')
async updateIntegrationsConfig( async updateIntegrationsConfig(
@TenantId() tenantIdentifier: string, @TenantId() domain: string,
@Body() body: { integrationsConfig: any }, @Body() body: { integrationsConfig: any },
) { ) {
const { integrationsConfig } = body; const { integrationsConfig } = body;
if (!tenantIdentifier) { if (!domain) {
throw new Error('Tenant identifier is missing from request'); throw new Error('Domain is missing from request');
} }
const tenant = await this.findTenant(tenantIdentifier); // Look up tenant by domain
const centralPrisma = getCentralPrisma();
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
if (!tenant) { if (!domainRecord?.tenant) {
throw new Error(`Tenant with identifier ${tenantIdentifier} not found`); throw new Error(`Tenant with domain ${domain} not found`);
} }
// Merge with existing config to preserve masked values // Merge with existing config to preserve masked values
let finalConfig = integrationsConfig; let finalConfig = integrationsConfig;
if (tenant.integrationsConfig) { if (domainRecord.tenant.integrationsConfig) {
const existingConfig = this.tenantDbService.decryptIntegrationsConfig( const existingConfig = this.tenantDbService.decryptIntegrationsConfig(
tenant.integrationsConfig as any, domainRecord.tenant.integrationsConfig as any,
); );
// Replace masked values with actual values from existing config // Replace masked values with actual values from existing config
@@ -100,9 +86,8 @@ export class TenantController {
); );
// Update in database // Update in database
const centralPrisma = getCentralPrisma();
await centralPrisma.tenant.update({ await centralPrisma.tenant.update({
where: { id: tenant.id }, where: { id: domainRecord.tenant.id },
data: { data: {
integrationsConfig: encryptedConfig as any, integrationsConfig: encryptedConfig as any,
}, },

View File

@@ -14,26 +14,23 @@ export class TenantMiddleware implements NestMiddleware {
next: () => void, next: () => void,
) { ) {
try { try {
// Priority 1: Check x-tenant-subdomain header from Nitro BFF proxy // Extract subdomain from hostname
// This is the primary method when using the BFF architecture
let subdomain = req.headers['x-tenant-subdomain'] as string | null;
let tenantId = req.headers['x-tenant-id'] as string;
if (subdomain) {
this.logger.log(`Using x-tenant-subdomain header: ${subdomain}`);
}
// Priority 2: Fall back to extracting subdomain from Origin/Host headers
// This supports direct backend access for development/testing
if (!subdomain && !tenantId) {
const host = req.headers.host || ''; const host = req.headers.host || '';
const hostname = host.split(':')[0]; const hostname = host.split(':')[0]; // Remove port if present
// Check Origin header to get frontend subdomain (for API calls)
const origin = req.headers.origin as string; const origin = req.headers.origin as string;
const referer = req.headers.referer as string; const referer = req.headers.referer as string;
let parts = hostname.split('.'); let parts = hostname.split('.');
this.logger.log(`Host header: ${host}, hostname: ${hostname}, origin: ${origin}, referer: ${referer}`); this.logger.log(`Host header: ${host}, hostname: ${hostname}, origin: ${origin}, referer: ${referer}, parts: ${JSON.stringify(parts)}`);
// For local development, accept x-tenant-id header
let tenantId = req.headers['x-tenant-id'] as string;
let subdomain: string | null = null;
this.logger.log(`Host header: ${host}, hostname: ${hostname}, parts: ${JSON.stringify(parts)}, x-tenant-id: ${tenantId}`);
// Try to extract subdomain from Origin header first (for API calls from frontend) // Try to extract subdomain from Origin header first (for API calls from frontend)
if (origin) { if (origin) {
@@ -45,7 +42,7 @@ export class TenantMiddleware implements NestMiddleware {
} catch (error) { } catch (error) {
this.logger.warn(`Failed to parse origin: ${origin}`); this.logger.warn(`Failed to parse origin: ${origin}`);
} }
} else if (referer) { } else if (referer && !tenantId) {
// Fallback to Referer if no Origin // Fallback to Referer if no Origin
try { try {
const refererUrl = new URL(referer); const refererUrl = new URL(referer);
@@ -58,17 +55,20 @@ export class TenantMiddleware implements NestMiddleware {
} }
// Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co") // Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co")
// For production domains with 3+ parts, extract first part as subdomain
if (parts.length >= 3) { if (parts.length >= 3) {
subdomain = parts[0]; subdomain = parts[0];
// Ignore www subdomain
if (subdomain === 'www') { if (subdomain === 'www') {
subdomain = null; subdomain = null;
} }
} else if (parts.length === 2 && parts[1] === 'localhost') { }
// For development (e.g., tenant1.localhost), also check 2 parts
else if (parts.length === 2 && parts[1] === 'localhost') {
subdomain = parts[0]; subdomain = parts[0];
} }
}
this.logger.log(`Extracted subdomain: ${subdomain}, x-tenant-id: ${tenantId}`); this.logger.log(`Extracted subdomain: ${subdomain}`);
// Always attach subdomain to request if present // Always attach subdomain to request if present
if (subdomain) { if (subdomain) {
@@ -122,7 +122,7 @@ export class TenantMiddleware implements NestMiddleware {
// Attach tenant info to request object // Attach tenant info to request object
(req as any).tenantId = tenantId; (req as any).tenantId = tenantId;
} else { } else {
this.logger.warn(`No tenant identified from host: ${subdomain}`); this.logger.warn(`No tenant identified from host: ${hostname}`);
} }
next(); next();

View File

@@ -98,75 +98,37 @@ export class VoiceController {
/** /**
* TwiML for outbound calls from browser (Twilio Device) * TwiML for outbound calls from browser (Twilio Device)
* Twilio sends application/x-www-form-urlencoded data
*/ */
@Post('twiml/outbound') @Post('twiml/outbound')
async outboundTwiml(@Req() req: FastifyRequest, @Res() res: FastifyReply) { async outboundTwiml(@Req() req: FastifyRequest, @Res() res: FastifyReply) {
// Parse body - Twilio sends URL-encoded form data const body = req.body as any;
let body = req.body as any;
// Handle case where body might be parsed as JSON key (URL-encoded string as key)
if (body && typeof body === 'object' && Object.keys(body).length === 1) {
const key = Object.keys(body)[0];
if (key.startsWith('{') || key.includes('=')) {
try {
// Try parsing as JSON if it looks like JSON
if (key.startsWith('{')) {
body = JSON.parse(key);
} else {
// Parse as URL-encoded
const params = new URLSearchParams(key);
body = Object.fromEntries(params.entries());
}
} catch (e) {
this.logger.warn(`Failed to re-parse body: ${e.message}`);
}
}
}
const to = body.To; const to = body.To;
const from = body.From; // Format: "client:tenantId:userId" const from = body.From;
const callSid = body.CallSid; const callSid = body.CallSid;
this.logger.log(`=== TwiML OUTBOUND REQUEST RECEIVED ===`); this.logger.log(`=== TwiML OUTBOUND REQUEST RECEIVED ===`);
this.logger.log(`CallSid: ${callSid}, From: ${from}, To: ${to}`); this.logger.log(`CallSid: ${callSid}, Body From: ${from}, Body To: ${to}`);
this.logger.log(`Full body: ${JSON.stringify(body)}`);
try { try {
// Extract tenant ID from the client identity // Extract tenant domain from Host header
// Format: "client:tenantId:userId" const host = req.headers.host || '';
let tenantId: string | null = null; const tenantDomain = host.split('.')[0]; // e.g., "tenant1" from "tenant1.routebox.co"
if (from && from.startsWith('client:')) {
const parts = from.replace('client:', '').split(':');
if (parts.length >= 2) {
tenantId = parts[0]; // First part is tenantId
this.logger.log(`Extracted tenantId from client identity: ${tenantId}`);
}
}
if (!tenantId) { this.logger.log(`Extracted tenant domain: ${tenantDomain}`);
this.logger.error(`Could not extract tenant from From: ${from}`);
throw new Error('Could not determine tenant from call');
}
// Look up tenant's Twilio phone number from config // Look up tenant's Twilio phone number from config
let callerId: string | undefined; let callerId = to; // Fallback (will cause error if not found)
try { try {
const { config } = await this.voiceService['getTwilioClient'](tenantId); // Get Twilio config to find the phone number
const { config } = await this.voiceService['getTwilioClient'](tenantDomain);
callerId = config.phoneNumber; callerId = config.phoneNumber;
this.logger.log(`Retrieved Twilio phone number for tenant: ${callerId}`); this.logger.log(`Retrieved Twilio phone number for tenant: ${callerId}`);
} catch (error: any) { } catch (error: any) {
this.logger.error(`Failed to get Twilio config: ${error.message}`); this.logger.error(`Failed to get Twilio config: ${error.message}`);
throw error;
} }
if (!callerId) { const dialNumber = to;
throw new Error('No caller ID configured for tenant');
}
const dialNumber = to?.trim();
if (!dialNumber) {
throw new Error('No destination number provided');
}
this.logger.log(`Using callerId: ${callerId}, dialNumber: ${dialNumber}`); this.logger.log(`Using callerId: ${callerId}, dialNumber: ${dialNumber}`);
@@ -183,9 +145,10 @@ export class VoiceController {
} catch (error: any) { } catch (error: any) {
this.logger.error(`=== ERROR GENERATING TWIML ===`); this.logger.error(`=== ERROR GENERATING TWIML ===`);
this.logger.error(`Error: ${error.message}`); this.logger.error(`Error: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
const errorTwiml = `<?xml version="1.0" encoding="UTF-8"?> const errorTwiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response> <Response>
<Say>An error occurred while processing your call. ${error.message}</Say> <Say>An error occurred while processing your call.</Say>
</Response>`; </Response>`;
res.type('text/xml').send(errorTwiml); res.type('text/xml').send(errorTwiml);
} }
@@ -193,33 +156,13 @@ export class VoiceController {
/** /**
* TwiML for inbound calls * TwiML for inbound calls
* Twilio sends application/x-www-form-urlencoded data
*/ */
@Post('twiml/inbound') @Post('twiml/inbound')
async inboundTwiml(@Req() req: FastifyRequest, @Res() res: FastifyReply) { async inboundTwiml(@Req() req: FastifyRequest, @Res() res: FastifyReply) {
// Parse body - Twilio sends URL-encoded form data const body = req.body as any;
let body = req.body as any;
// Handle case where body might be parsed incorrectly
if (body && typeof body === 'object' && Object.keys(body).length === 1) {
const key = Object.keys(body)[0];
if (key.startsWith('{') || key.includes('=')) {
try {
if (key.startsWith('{')) {
body = JSON.parse(key);
} else {
const params = new URLSearchParams(key);
body = Object.fromEntries(params.entries());
}
} catch (e) {
this.logger.warn(`Failed to re-parse body: ${e.message}`);
}
}
}
const callSid = body.CallSid; const callSid = body.CallSid;
const fromNumber = body.From; const fromNumber = body.From;
const toNumber = body.To; // This is the Twilio phone number that was called const toNumber = body.To;
this.logger.log(`\n\n╔════════════════════════════════════════╗`); this.logger.log(`\n\n╔════════════════════════════════════════╗`);
this.logger.log(`║ === INBOUND CALL RECEIVED ===`); this.logger.log(`║ === INBOUND CALL RECEIVED ===`);
@@ -227,28 +170,19 @@ export class VoiceController {
this.logger.log(`CallSid: ${callSid}`); this.logger.log(`CallSid: ${callSid}`);
this.logger.log(`From: ${fromNumber}`); this.logger.log(`From: ${fromNumber}`);
this.logger.log(`To: ${toNumber}`); this.logger.log(`To: ${toNumber}`);
this.logger.log(`Full body: ${JSON.stringify(body)}`);
try { try {
// Look up tenant by the Twilio phone number that was called // Extract tenant domain from Host header
const tenantInfo = await this.voiceService.findTenantByPhoneNumber(toNumber); const host = req.headers.host || '';
const tenantDomain = host.split('.')[0]; // e.g., "tenant1" from "tenant1.routebox.co"
if (!tenantInfo) { this.logger.log(`Extracted tenant domain: ${tenantDomain}`);
this.logger.error(`No tenant found for phone number: ${toNumber}`);
const twiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Sorry, this number is not configured. Please contact support.</Say>
<Hangup/>
</Response>`;
return res.type('text/xml').send(twiml);
}
const tenantId = tenantInfo.tenantId;
this.logger.log(`Found tenant: ${tenantId}`);
// Get all connected users for this tenant // Get all connected users for this tenant
const connectedUsers = this.voiceGateway.getConnectedUsers(tenantId); const connectedUsers = this.voiceGateway.getConnectedUsers(tenantDomain);
this.logger.log(`Connected users for tenant ${tenantId}: ${connectedUsers.length}`); this.logger.log(`Connected users for tenant ${tenantDomain}: ${connectedUsers.length}`);
if (connectedUsers.length > 0) { if (connectedUsers.length > 0) {
this.logger.log(`Connected user IDs: ${connectedUsers.join(', ')}`); this.logger.log(`Connected user IDs: ${connectedUsers.join(', ')}`);
} }
@@ -264,22 +198,20 @@ export class VoiceController {
return res.type('text/xml').send(twiml); return res.type('text/xml').send(twiml);
} }
// Build TwiML to dial all connected clients // Build TwiML to dial all connected clients with Media Streams for AI
// Client identity format is now: tenantId:userId const clientElements = connectedUsers.map(userId => ` <Client>${userId}</Client>`).join('\n');
const clientElements = connectedUsers.map(userId => ` <Client>${tenantId}:${userId}</Client>`).join('\n');
// Log the client identities being dialed // Use wss:// for secure WebSocket (Traefik handles HTTPS)
this.logger.log(`Client identities being dialed:`);
connectedUsers.forEach(userId => {
this.logger.log(` - ${tenantId}:${userId}`);
});
// Use wss:// for secure WebSocket
const host = req.headers.host || 'backend.routebox.co';
const streamUrl = `wss://${host}/api/voice/media-stream`; const streamUrl = `wss://${host}/api/voice/media-stream`;
this.logger.log(`Stream URL: ${streamUrl}`); this.logger.log(`Stream URL: ${streamUrl}`);
this.logger.log(`Dialing ${connectedUsers.length} client(s)...`); this.logger.log(`Dialing ${connectedUsers.length} client(s)...`);
this.logger.log(`Client IDs to dial: ${connectedUsers.join(', ')}`);
// Verify we have client IDs in proper format
if (connectedUsers.length > 0) {
this.logger.log(`First Client ID format check: "${connectedUsers[0]}" (length: ${connectedUsers[0].length})`);
}
// Notify connected users about incoming call via Socket.IO // Notify connected users about incoming call via Socket.IO
connectedUsers.forEach(userId => { connectedUsers.forEach(userId => {
@@ -287,7 +219,7 @@ export class VoiceController {
callSid, callSid,
fromNumber, fromNumber,
toNumber, toNumber,
tenantId, tenantDomain,
}); });
}); });
@@ -295,7 +227,7 @@ export class VoiceController {
<Response> <Response>
<Start> <Start>
<Stream url="${streamUrl}"> <Stream url="${streamUrl}">
<Parameter name="tenantId" value="${tenantId}"/> <Parameter name="tenantId" value="${tenantDomain}"/>
<Parameter name="userId" value="${connectedUsers[0]}"/> <Parameter name="userId" value="${connectedUsers[0]}"/>
</Stream> </Stream>
</Start> </Start>
@@ -304,7 +236,7 @@ ${clientElements}
</Dial> </Dial>
</Response>`; </Response>`;
this.logger.log(`✓ Returning inbound TwiML - dialing ${connectedUsers.length} client(s)`); this.logger.log(`✓ Returning inbound TwiML with Media Streams - dialing ${connectedUsers.length} client(s)`);
this.logger.log(`Generated TwiML:\n${twiml}\n`); this.logger.log(`Generated TwiML:\n${twiml}\n`);
res.type('text/xml').send(twiml); res.type('text/xml').send(twiml);
} catch (error: any) { } catch (error: any) {

View File

@@ -61,41 +61,33 @@ export class VoiceGateway
const payload = await this.jwtService.verifyAsync(token); const payload = await this.jwtService.verifyAsync(token);
// Extract domain from origin header (e.g., http://tenant1.routebox.co:3001) // Extract domain from origin header (e.g., http://tenant1.routebox.co:3001)
// The domains table stores just the subdomain part (e.g., "tenant1")
const origin = client.handshake.headers.origin || client.handshake.headers.referer; const origin = client.handshake.headers.origin || client.handshake.headers.referer;
let subdomain = 'localhost'; let domain = 'localhost';
if (origin) { if (origin) {
try { try {
const url = new URL(origin); const url = new URL(origin);
const hostname = url.hostname; const hostname = url.hostname; // e.g., tenant1.routebox.co or localhost
subdomain = hostname.split('.')[0];
// Extract first part of subdomain as domain
// tenant1.routebox.co -> tenant1
// localhost -> localhost
domain = hostname.split('.')[0];
} catch (error) { } catch (error) {
this.logger.warn(`Failed to parse origin: ${origin}`); this.logger.warn(`Failed to parse origin: ${origin}`);
} }
} }
// Resolve the actual tenantId (UUID) from the subdomain client.tenantId = domain; // Store the subdomain as tenantId
let tenantId: string | null = null;
try {
const tenant = await this.tenantDbService.getTenantByDomain(subdomain);
if (tenant) {
tenantId = tenant.id;
this.logger.log(`Resolved tenant ${subdomain} -> ${tenantId}`);
}
} catch (error) {
this.logger.warn(`Failed to resolve tenant for subdomain ${subdomain}: ${error.message}`);
}
// Fall back to subdomain if tenant lookup fails
client.tenantId = tenantId || subdomain;
client.userId = payload.sub; client.userId = payload.sub;
client.tenantSlug = subdomain; client.tenantSlug = domain; // Same as subdomain
this.connectedUsers.set(client.userId, client); this.connectedUsers.set(client.userId, client);
this.logger.log( this.logger.log(
`✓ Client connected: ${client.id} (User: ${client.userId}, TenantId: ${client.tenantId}, Subdomain: ${subdomain})`, `✓ Client connected: ${client.id} (User: ${client.userId}, Domain: ${domain})`,
); );
this.logger.log(`Total connected users in tenant ${client.tenantId}: ${this.getConnectedUsers(client.tenantId).length}`); this.logger.log(`Total connected users in ${domain}: ${this.getConnectedUsers(domain).length}`);
// Send current call state if any active call // Send current call state if any active call
const activeCallSid = this.activeCallsByUser.get(client.userId); const activeCallSid = this.activeCallsByUser.get(client.userId);
@@ -311,14 +303,13 @@ export class VoiceGateway
/** /**
* Get connected users for a tenant * Get connected users for a tenant
* @param tenantId - The tenant UUID to filter by
*/ */
getConnectedUsers(tenantId?: string): string[] { getConnectedUsers(tenantDomain?: string): string[] {
const userIds: string[] = []; const userIds: string[] = [];
for (const [userId, socket] of this.connectedUsers.entries()) { for (const [userId, socket] of this.connectedUsers.entries()) {
// If tenantId specified, filter by tenant // If tenantDomain specified, filter by tenant
if (!tenantId || socket.tenantId === tenantId) { if (!tenantDomain || socket.tenantSlug === tenantDomain) {
userIds.push(userId); userIds.push(userId);
} }
} }

View File

@@ -31,46 +31,46 @@ export class VoiceService {
/** /**
* Get Twilio client for a tenant * Get Twilio client for a tenant
*/ */
private async getTwilioClient(tenantId: string): Promise<{ client: Twilio.Twilio; config: TwilioConfig; tenantId: string }> { private async getTwilioClient(tenantIdOrDomain: string): Promise<{ client: Twilio.Twilio; config: TwilioConfig; tenantId: string }> {
// Check cache first // Check cache first
if (this.twilioClients.has(tenantId)) { if (this.twilioClients.has(tenantIdOrDomain)) {
const centralPrisma = getCentralPrisma(); const centralPrisma = getCentralPrisma();
// Look up tenant by ID // Look up tenant by domain
const tenant = await centralPrisma.tenant.findUnique({ const domainRecord = await centralPrisma.domain.findUnique({
where: { id: tenantId }, where: { domain: tenantIdOrDomain },
select: { id: true, integrationsConfig: true }, include: { tenant: { select: { id: true, integrationsConfig: true } } },
}); });
const config = this.getIntegrationConfig(tenant?.integrationsConfig as any); const config = this.getIntegrationConfig(domainRecord?.tenant?.integrationsConfig as any);
return { return {
client: this.twilioClients.get(tenantId), client: this.twilioClients.get(tenantIdOrDomain),
config: config.twilio, config: config.twilio,
tenantId: tenant.id tenantId: domainRecord.tenant.id
}; };
} }
// Fetch tenant integrations config // Fetch tenant integrations config
const centralPrisma = getCentralPrisma(); const centralPrisma = getCentralPrisma();
this.logger.log(`Looking up tenant: ${tenantId}`); this.logger.log(`Looking up domain: ${tenantIdOrDomain}`);
const tenant = await centralPrisma.tenant.findUnique({ const domainRecord = await centralPrisma.domain.findUnique({
where: { id: tenantId }, where: { domain: tenantIdOrDomain },
select: { id: true, integrationsConfig: true }, include: { tenant: { select: { id: true, integrationsConfig: true } } },
}); });
this.logger.log(`Tenant found: ${!!tenant}, Config: ${!!tenant?.integrationsConfig}`); this.logger.log(`Domain record found: ${!!domainRecord}, Tenant: ${!!domainRecord?.tenant}, Config: ${!!domainRecord?.tenant?.integrationsConfig}`);
if (!tenant) { if (!domainRecord?.tenant) {
throw new Error(`Tenant ${tenantId} not found`); throw new Error(`Domain ${tenantIdOrDomain} not found`);
} }
if (!tenant.integrationsConfig) { if (!domainRecord.tenant.integrationsConfig) {
throw new Error('Tenant integrations config not found. Please configure Twilio credentials in Settings > Integrations'); throw new Error('Tenant integrations config not found. Please configure Twilio credentials in Settings > Integrations');
} }
const config = this.getIntegrationConfig(tenant.integrationsConfig as any); const config = this.getIntegrationConfig(domainRecord.tenant.integrationsConfig as any);
this.logger.log(`Config decrypted: ${!!config.twilio}, AccountSid: ${config.twilio?.accountSid?.substring(0, 10)}..., AuthToken: ${config.twilio?.authToken?.substring(0, 10)}..., Phone: ${config.twilio?.phoneNumber}`); this.logger.log(`Config decrypted: ${!!config.twilio}, AccountSid: ${config.twilio?.accountSid?.substring(0, 10)}..., AuthToken: ${config.twilio?.authToken?.substring(0, 10)}..., Phone: ${config.twilio?.phoneNumber}`);
@@ -79,9 +79,9 @@ export class VoiceService {
} }
const client = Twilio.default(config.twilio.accountSid, config.twilio.authToken); const client = Twilio.default(config.twilio.accountSid, config.twilio.authToken);
this.twilioClients.set(tenantId, client); this.twilioClients.set(tenantIdOrDomain, client);
return { client, config: config.twilio, tenantId: tenant.id }; return { client, config: config.twilio, tenantId: domainRecord.tenant.id };
} }
/** /**
@@ -105,64 +105,22 @@ export class VoiceService {
return {}; return {};
} }
/**
* Find tenant by their configured Twilio phone number
* Used for inbound call routing
*/
async findTenantByPhoneNumber(phoneNumber: string): Promise<{ tenantId: string; config: TwilioConfig } | null> {
const centralPrisma = getCentralPrisma();
// Normalize phone number (remove spaces, ensure + prefix for comparison)
const normalizedPhone = phoneNumber.replace(/\s+/g, '').replace(/^(\d)/, '+$1');
this.logger.log(`Looking up tenant by phone number: ${normalizedPhone}`);
// Get all tenants with integrations config
const tenants = await centralPrisma.tenant.findMany({
where: {
integrationsConfig: { not: null },
},
select: { id: true, integrationsConfig: true },
});
for (const tenant of tenants) {
const config = this.getIntegrationConfig(tenant.integrationsConfig as any);
if (config.twilio?.phoneNumber) {
const tenantPhone = config.twilio.phoneNumber.replace(/\s+/g, '').replace(/^(\d)/, '+$1');
if (tenantPhone === normalizedPhone) {
this.logger.log(`Found tenant ${tenant.id} for phone number ${normalizedPhone}`);
return { tenantId: tenant.id, config: config.twilio };
}
}
}
this.logger.warn(`No tenant found for phone number: ${normalizedPhone}`);
return null;
}
/** /**
* Generate Twilio access token for browser Voice SDK * Generate Twilio access token for browser Voice SDK
*/ */
async generateAccessToken(tenantId: string, userId: string): Promise<string> { async generateAccessToken(tenantDomain: string, userId: string): Promise<string> {
const { config, tenantId: resolvedTenantId } = await this.getTwilioClient(tenantId); const { config, tenantId } = await this.getTwilioClient(tenantDomain);
if (!config.accountSid || !config.apiKey || !config.apiSecret) { if (!config.accountSid || !config.apiKey || !config.apiSecret) {
throw new Error('Twilio API credentials not configured. Please add API Key and Secret in Settings > Integrations'); throw new Error('Twilio API credentials not configured. Please add API Key and Secret in Settings > Integrations');
} }
// Include tenantId in the identity so we can extract it in TwiML webhooks
// Format: tenantId:userId
const identity = `${resolvedTenantId}:${userId}`;
this.logger.log(`Generating access token with identity: ${identity}`);
this.logger.log(` Input tenantId: ${tenantId}, Resolved tenantId: ${resolvedTenantId}, userId: ${userId}`);
// Create an access token // Create an access token
const token = new AccessToken( const token = new AccessToken(
config.accountSid, config.accountSid,
config.apiKey, config.apiKey,
config.apiSecret, config.apiSecret,
{ identity, ttl: 3600 } // 1 hour expiry { identity: userId, ttl: 3600 } // 1 hour expiry
); );
// Create a Voice grant // Create a Voice grant
@@ -478,28 +436,20 @@ export class VoiceService {
const { callSid, tenantId, userId } = params; const { callSid, tenantId, userId } = params;
try { try {
// Get OpenAI config - tenantId might be a domain or a tenant ID (UUID or CUID) // Get OpenAI config - tenantId might be a domain, so look it up
const centralPrisma = getCentralPrisma(); const centralPrisma = getCentralPrisma();
// Detect if tenantId looks like an ID (UUID or CUID) or a domain name // Try to find tenant by domain first (if tenantId is like "tenant1")
// UUIDs: 8-4-4-4-12 hex format
// CUIDs: 25 character alphanumeric starting with 'c'
const isUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(tenantId);
const isCUID = /^c[a-z0-9]{24}$/i.test(tenantId);
const isId = isUUID || isCUID;
let tenant; let tenant;
if (!isId) { if (!tenantId.match(/^[0-9a-f]{8}-[0-9a-f]{4}-/i)) {
// Looks like a domain, not an ID // Looks like a domain, not a UUID
this.logger.log(`Looking up tenant by domain: ${tenantId}`);
const domainRecord = await centralPrisma.domain.findUnique({ const domainRecord = await centralPrisma.domain.findUnique({
where: { domain: tenantId }, where: { domain: tenantId },
include: { tenant: { select: { id: true, integrationsConfig: true } } }, include: { tenant: { select: { id: true, integrationsConfig: true } } },
}); });
tenant = domainRecord?.tenant; tenant = domainRecord?.tenant;
} else { } else {
// It's an ID (UUID or CUID) // It's a UUID
this.logger.log(`Looking up tenant by ID: ${tenantId}`);
tenant = await centralPrisma.tenant.findUnique({ tenant = await centralPrisma.tenant.findUnique({
where: { id: tenantId }, where: { id: tenantId },
select: { id: true, integrationsConfig: true }, select: { id: true, integrationsConfig: true },

View File

@@ -1,264 +0,0 @@
<template>
<div class="list-view-layout-editor">
<div class="flex h-full">
<!-- Selected Fields Area -->
<div class="flex-1 p-4 overflow-auto">
<div class="mb-4 flex justify-between items-center">
<h3 class="text-lg font-semibold">{{ layoutName || 'List View Layout' }}</h3>
<div class="flex gap-2">
<Button variant="outline" size="sm" @click="handleClear">
Clear All
</Button>
<Button size="sm" @click="handleSave">
Save Layout
</Button>
</div>
</div>
<div class="border rounded-lg bg-slate-50 dark:bg-slate-900 p-4 min-h-[400px]">
<p class="text-sm text-muted-foreground mb-4">
Drag fields to reorder them. Fields will appear in the list view in this order.
</p>
<div v-if="selectedFields.length === 0" class="text-center py-8 text-muted-foreground">
<p>No fields selected.</p>
<p class="text-sm">Click or drag fields from the right panel to add them.</p>
</div>
<div
v-else
ref="sortableContainer"
class="space-y-2"
>
<div
v-for="(field, index) in selectedFields"
:key="field.id"
class="p-3 border rounded cursor-move bg-white dark:bg-slate-800 hover:border-primary transition-colors flex items-center justify-between"
draggable="true"
@dragstart="handleDragStart($event, index)"
@dragover.prevent="handleDragOver($event, index)"
@drop="handleDrop($event, index)"
>
<div class="flex items-center gap-3">
<span class="text-muted-foreground cursor-grab">
<GripVertical class="w-4 h-4" />
</span>
<div>
<div class="font-medium text-sm">{{ field.label }}</div>
<div class="text-xs text-muted-foreground">
{{ field.apiName }} {{ formatFieldType(field.type) }}
</div>
</div>
</div>
<Button
variant="ghost"
size="sm"
class="text-destructive hover:text-destructive"
@click="removeField(field.id)"
>
<X class="w-4 h-4" />
</Button>
</div>
</div>
</div>
</div>
<!-- Available Fields Sidebar -->
<div class="w-80 border-l bg-white dark:bg-slate-950 p-4 overflow-auto">
<h3 class="text-lg font-semibold mb-4">Available Fields</h3>
<p class="text-xs text-muted-foreground mb-4">Click or drag to add field to list</p>
<div v-if="availableFields.length === 0" class="text-center py-4 text-muted-foreground text-sm">
All fields have been added to the layout.
</div>
<div v-else class="space-y-2">
<div
v-for="field in availableFields"
:key="field.id"
class="p-3 border rounded cursor-pointer bg-white dark:bg-slate-900 hover:border-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors"
draggable="true"
@dragstart="handleAvailableFieldDragStart($event, field)"
@click="addField(field)"
>
<div class="font-medium text-sm">{{ field.label }}</div>
<div class="text-xs text-muted-foreground">
{{ field.apiName }} {{ formatFieldType(field.type) }}
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { GripVertical, X } from 'lucide-vue-next'
import type { FieldLayoutItem } from '~/types/page-layout'
import type { FieldConfig } from '~/types/field-types'
import { Button } from '@/components/ui/button'
const props = defineProps<{
fields: FieldConfig[]
initialLayout?: FieldLayoutItem[]
layoutName?: string
}>()
const emit = defineEmits<{
save: [layout: { fields: FieldLayoutItem[] }]
}>()
// Selected fields in order
const selectedFieldIds = ref<string[]>([])
const draggedIndex = ref<number | null>(null)
const draggedAvailableField = ref<FieldConfig | null>(null)
// Initialize with initial layout
watch(() => props.initialLayout, (layout) => {
if (layout && layout.length > 0) {
// Sort by order if available, otherwise use array order
const sorted = [...layout].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
selectedFieldIds.value = sorted.map(item => item.fieldId)
}
}, { immediate: true })
// Computed selected fields in order
const selectedFields = computed(() => {
return selectedFieldIds.value
.map(id => props.fields.find(f => f.id === id))
.filter((f): f is FieldConfig => f !== undefined)
})
// Available fields (not selected)
const availableFields = computed(() => {
const selectedSet = new Set(selectedFieldIds.value)
return props.fields.filter(field => !selectedSet.has(field.id))
})
const formatFieldType = (type: string): string => {
const typeNames: Record<string, string> = {
'TEXT': 'Text',
'LONG_TEXT': 'Textarea',
'EMAIL': 'Email',
'PHONE': 'Phone',
'NUMBER': 'Number',
'CURRENCY': 'Currency',
'PERCENT': 'Percent',
'PICKLIST': 'Picklist',
'MULTI_PICKLIST': 'Multi-select',
'BOOLEAN': 'Checkbox',
'DATE': 'Date',
'DATE_TIME': 'DateTime',
'TIME': 'Time',
'URL': 'URL',
'LOOKUP': 'Lookup',
'FILE': 'File',
'IMAGE': 'Image',
'JSON': 'JSON',
'text': 'Text',
'textarea': 'Textarea',
'email': 'Email',
'number': 'Number',
'currency': 'Currency',
'select': 'Picklist',
'multiSelect': 'Multi-select',
'boolean': 'Checkbox',
'date': 'Date',
'datetime': 'DateTime',
'url': 'URL',
'lookup': 'Lookup',
'belongsTo': 'Lookup',
}
return typeNames[type] || type
}
const addField = (field: FieldConfig) => {
if (!selectedFieldIds.value.includes(field.id)) {
selectedFieldIds.value.push(field.id)
}
}
const removeField = (fieldId: string) => {
selectedFieldIds.value = selectedFieldIds.value.filter(id => id !== fieldId)
}
// Drag and drop for reordering
const handleDragStart = (event: DragEvent, index: number) => {
draggedIndex.value = index
draggedAvailableField.value = null
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move'
}
}
const handleDragOver = (event: DragEvent, index: number) => {
event.preventDefault()
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'move'
}
}
const handleDrop = (event: DragEvent, targetIndex: number) => {
event.preventDefault()
// Handle drop from available fields
if (draggedAvailableField.value) {
addField(draggedAvailableField.value)
// Move the newly added field to the target position
const newFieldId = draggedAvailableField.value.id
const currentIndex = selectedFieldIds.value.indexOf(newFieldId)
if (currentIndex !== -1 && currentIndex !== targetIndex) {
const ids = [...selectedFieldIds.value]
ids.splice(currentIndex, 1)
ids.splice(targetIndex, 0, newFieldId)
selectedFieldIds.value = ids
}
draggedAvailableField.value = null
return
}
// Handle reordering within selected fields
if (draggedIndex.value === null || draggedIndex.value === targetIndex) {
draggedIndex.value = null
return
}
const ids = [...selectedFieldIds.value]
const [removed] = ids.splice(draggedIndex.value, 1)
ids.splice(targetIndex, 0, removed)
selectedFieldIds.value = ids
draggedIndex.value = null
}
// Drag from available fields
const handleAvailableFieldDragStart = (event: DragEvent, field: FieldConfig) => {
draggedAvailableField.value = field
draggedIndex.value = null
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'copy'
}
}
const handleClear = () => {
if (confirm('Are you sure you want to clear all fields from the layout?')) {
selectedFieldIds.value = []
}
}
const handleSave = () => {
const layout: FieldLayoutItem[] = selectedFieldIds.value.map((fieldId, index) => ({
fieldId,
order: index,
}))
emit('save', { fields: layout })
}
</script>
<style scoped>
.list-view-layout-editor {
height: calc(100vh - 300px);
min-height: 500px;
}
</style>

View File

@@ -3,32 +3,90 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
const config = useRuntimeConfig()
const router = useRouter() const router = useRouter()
const { toast } = useToast() const { toast } = useToast()
const { login, isLoading } = useAuth()
// Cookie for server-side auth check
const tokenCookie = useCookie('token')
// Extract subdomain from hostname (e.g., tenant1.localhost → tenant1)
const getSubdomain = () => {
if (!import.meta.client) return null
const hostname = window.location.hostname
const parts = hostname.split('.')
console.log('Extracting subdomain from:', hostname, 'parts:', parts)
// For localhost development: tenant1.localhost or localhost
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return null // Use default tenant for plain localhost
}
// For subdomains like tenant1.routebox.co or tenant1.localhost
if (parts.length >= 2 && parts[0] !== 'www') {
console.log('Using subdomain:', parts[0])
return parts[0] // Return subdomain
}
return null
}
const subdomain = ref(getSubdomain())
const email = ref('') const email = ref('')
const password = ref('') const password = ref('')
const loading = ref(false)
const error = ref('') const error = ref('')
const handleLogin = async () => { const handleLogin = async () => {
try { try {
loading.value = true
error.value = '' error.value = ''
// Use the BFF login endpoint via useAuth const headers: Record<string, string> = {
const result = await login(email.value, password.value) 'Content-Type': 'application/json',
}
// Only send x-tenant-id if we have a subdomain
if (subdomain.value) {
headers['x-tenant-id'] = subdomain.value
}
const response = await fetch(`${config.public.apiBaseUrl}/api/auth/login`, {
method: 'POST',
headers,
body: JSON.stringify({
email: email.value,
password: password.value,
}),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.message || 'Login failed')
}
const data = await response.json()
// Store credentials in localStorage
// Store the tenant ID that was used for login
const tenantToStore = subdomain.value || data.user?.tenantId || 'tenant1'
localStorage.setItem('tenantId', tenantToStore)
localStorage.setItem('token', data.access_token)
localStorage.setItem('user', JSON.stringify(data.user))
// Also store token in cookie for server-side auth check
tokenCookie.value = data.access_token
if (result.success) {
toast.success('Login successful!') toast.success('Login successful!')
// Redirect to home // Redirect to home
router.push('/') router.push('/')
} else {
error.value = result.error || 'Login failed'
toast.error(result.error || 'Login failed')
}
} catch (e: any) { } catch (e: any) {
error.value = e.message || 'Login failed' error.value = e.message || 'Login failed'
toast.error(e.message || 'Login failed') toast.error(e.message || 'Login failed')
} finally {
loading.value = false
} }
} }
</script> </script>
@@ -60,8 +118,8 @@ const handleLogin = async () => {
</div> </div>
<Input id="password" v-model="password" type="password" required /> <Input id="password" v-model="password" type="password" required />
</div> </div>
<Button type="submit" class="w-full" :disabled="isLoading"> <Button type="submit" class="w-full" :disabled="loading">
{{ isLoading ? 'Logging in...' : 'Login' }} {{ loading ? 'Logging in...' : 'Login' }}
</Button> </Button>
</div> </div>
<div class="text-center text-sm"> <div class="text-center text-sm">

View File

@@ -1,25 +1,40 @@
export const useApi = () => { export const useApi = () => {
const config = useRuntimeConfig()
const router = useRouter() const router = useRouter()
const { toast } = useToast() const { toast } = useToast()
const { isLoggedIn, logout } = useAuth() const { isLoggedIn, logout } = useAuth()
/** // Use current domain for API calls (same subdomain routing)
* API calls now go through the Nitro BFF proxy at /api/*
* The proxy handles:
* - Auth token injection from HTTP-only cookies
* - Tenant subdomain extraction and forwarding
* - Forwarding requests to the NestJS backend
*/
const getApiBaseUrl = () => { const getApiBaseUrl = () => {
// All API calls go through Nitro proxy - works for both SSR and client if (import.meta.client) {
return '' // In browser, use current hostname but with port 3000 for API
const currentHost = window.location.hostname
const protocol = window.location.protocol
//return `${protocol}//${currentHost}:3000`
return `${protocol}//${currentHost}`
}
// Fallback for SSR
return config.public.apiBaseUrl
} }
const getHeaders = () => { const getHeaders = () => {
// Headers are now minimal - auth and tenant are handled by the Nitro proxy
const headers: Record<string, string> = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
// Add tenant ID from localStorage or state
if (import.meta.client) {
const tenantId = localStorage.getItem('tenantId')
if (tenantId) {
headers['x-tenant-id'] = tenantId
}
const token = localStorage.getItem('token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
}
return headers return headers
} }

View File

@@ -1,70 +1,43 @@
/**
* Authentication composable using BFF (Backend for Frontend) pattern
* Auth tokens are stored in HTTP-only cookies managed by Nitro server
* Tenant context is stored in a readable cookie for client-side access
*/
export const useAuth = () => { export const useAuth = () => {
const tokenCookie = useCookie('token')
const authMessageCookie = useCookie('authMessage') const authMessageCookie = useCookie('authMessage')
const tenantCookie = useCookie('routebox_tenant')
const router = useRouter() const router = useRouter()
const config = useRuntimeConfig()
// Reactive user state - populated from /api/auth/me
const user = useState<any>('auth_user', () => null)
const isAuthenticated = useState<boolean>('auth_is_authenticated', () => false)
const isLoading = useState<boolean>('auth_is_loading', () => false)
/**
* Check if user is logged in
* Uses server-side session validation via /api/auth/me
*/
const isLoggedIn = () => { const isLoggedIn = () => {
return isAuthenticated.value if (!import.meta.client) return false
const token = localStorage.getItem('token')
const tenantId = localStorage.getItem('tenantId')
return !!(token && tenantId)
} }
/**
* Login with email and password
* Calls the Nitro BFF login endpoint which sets HTTP-only cookies
*/
const login = async (email: string, password: string) => {
isLoading.value = true
try {
const response = await $fetch('/api/auth/login', {
method: 'POST',
body: { email, password },
})
if (response.success) {
user.value = response.user
isAuthenticated.value = true
return { success: true, user: response.user }
}
return { success: false, error: 'Login failed' }
} catch (error: any) {
const message = error.data?.message || error.message || 'Login failed'
return { success: false, error: message }
} finally {
isLoading.value = false
}
}
/**
* Logout user
* Calls the Nitro BFF logout endpoint which clears HTTP-only cookies
*/
const logout = async () => { const logout = async () => {
if (import.meta.client) {
// Call backend logout endpoint
try { try {
await $fetch('/api/auth/logout', { const token = localStorage.getItem('token')
const tenantId = localStorage.getItem('tenantId')
if (token) {
await fetch(`${config.public.apiBaseUrl}/api/auth/logout`, {
method: 'POST', method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
...(tenantId && { 'x-tenant-id': tenantId }),
},
}) })
}
} catch (error) { } catch (error) {
console.error('Logout error:', error) console.error('Logout error:', error)
} }
// Clear local state // Clear local storage
user.value = null localStorage.removeItem('token')
isAuthenticated.value = false localStorage.removeItem('tenantId')
localStorage.removeItem('user')
// Clear cookie for server-side check
tokenCookie.value = null
// Set flash message for login page // Set flash message for login page
authMessageCookie.value = 'Logged out successfully' authMessageCookie.value = 'Logged out successfully'
@@ -72,60 +45,17 @@ export const useAuth = () => {
// Redirect to login page // Redirect to login page
router.push('/login') router.push('/login')
} }
/**
* Check current authentication status
* Validates session with backend via Nitro BFF
*/
const checkAuth = async () => {
isLoading.value = true
try {
const response = await $fetch('/api/auth/me', {
method: 'GET',
})
if (response.authenticated && response.user) {
user.value = response.user
isAuthenticated.value = true
return true
}
} catch (error) {
// Session invalid or expired
user.value = null
isAuthenticated.value = false
} finally {
isLoading.value = false
} }
return false
}
/**
* Get current user
*/
const getUser = () => { const getUser = () => {
return user.value if (!import.meta.client) return null
} const userStr = localStorage.getItem('user')
return userStr ? JSON.parse(userStr) : null
/**
* Get current tenant ID from cookie
*/
const getTenantId = () => {
return tenantCookie.value
} }
return { return {
// State
user,
isAuthenticated,
isLoading,
// Methods
isLoggedIn, isLoggedIn,
login,
logout, logout,
checkAuth,
getUser, getUser,
getTenantId,
} }
} }

View File

@@ -70,36 +70,12 @@ export const useFields = () => {
/** /**
* Build a ListView configuration from object definition * Build a ListView configuration from object definition
* @param objectDef - The object definition containing fields
* @param customConfig - Optional custom configuration
* @param listLayoutConfig - Optional list view layout configuration from page_layouts
*/ */
const buildListViewConfig = ( const buildListViewConfig = (
objectDef: any, objectDef: any,
customConfig?: Partial<ListViewConfig>, customConfig?: Partial<ListViewConfig>
listLayoutConfig?: { fields: Array<{ fieldId: string; order?: number }> } | null
): ListViewConfig => { ): ListViewConfig => {
let fields = objectDef.fields?.map(mapFieldDefinitionToConfig) || [] const fields = objectDef.fields?.map(mapFieldDefinitionToConfig) || []
// If a list layout is provided, filter and order fields according to it
if (listLayoutConfig && listLayoutConfig.fields && listLayoutConfig.fields.length > 0) {
// Sort layout fields by order
const sortedLayoutFields = [...listLayoutConfig.fields].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
// Map layout fields to actual field configs, preserving order
const orderedFields: FieldConfig[] = []
for (const layoutField of sortedLayoutFields) {
const fieldConfig = fields.find((f: FieldConfig) => f.id === layoutField.fieldId)
if (fieldConfig) {
orderedFields.push(fieldConfig)
}
}
// Use ordered fields if we found any, otherwise fall back to all fields
if (orderedFields.length > 0) {
fields = orderedFields
}
}
return { return {
objectApiName: objectDef.apiName, objectApiName: objectDef.apiName,

View File

@@ -1,13 +1,11 @@
import type { PageLayout, CreatePageLayoutRequest, UpdatePageLayoutRequest, PageLayoutType } from '~/types/page-layout' import type { PageLayout, CreatePageLayoutRequest, UpdatePageLayoutRequest } from '~/types/page-layout'
export const usePageLayouts = () => { export const usePageLayouts = () => {
const { api } = useApi() const { api } = useApi()
const getPageLayouts = async (objectId?: string, layoutType?: PageLayoutType) => { const getPageLayouts = async (objectId?: string) => {
try { try {
const params: Record<string, string> = {} const params = objectId ? { objectId } : {}
if (objectId) params.objectId = objectId
if (layoutType) params.layoutType = layoutType
const response = await api.get('/page-layouts', { params }) const response = await api.get('/page-layouts', { params })
return response return response
} catch (error) { } catch (error) {
@@ -26,11 +24,9 @@ export const usePageLayouts = () => {
} }
} }
const getDefaultPageLayout = async (objectId: string, layoutType: PageLayoutType = 'detail') => { const getDefaultPageLayout = async (objectId: string) => {
try { try {
const response = await api.get(`/page-layouts/default/${objectId}`, { const response = await api.get(`/page-layouts/default/${objectId}`)
params: { layoutType }
})
return response return response
} catch (error) { } catch (error) {
console.error('Error fetching default page layout:', error) console.error('Error fetching default page layout:', error)

View File

@@ -1,4 +1,4 @@
import { ref, computed, onMounted, onUnmounted, shallowRef, watch } from 'vue'; import { ref, computed, onMounted, onUnmounted, shallowRef } from 'vue';
import { io, Socket } from 'socket.io-client'; import { io, Socket } from 'socket.io-client';
import { Device, Call as TwilioCall } from '@twilio/voice-sdk'; import { Device, Call as TwilioCall } from '@twilio/voice-sdk';
import { useAuth } from './useAuth'; import { useAuth } from './useAuth';
@@ -44,6 +44,17 @@ const volume = ref(100);
export function useSoftphone() { export function useSoftphone() {
const auth = useAuth(); const auth = useAuth();
// Get token and tenantId from localStorage
const getToken = () => {
if (typeof window === 'undefined') return null;
return localStorage.getItem('token');
};
const getTenantId = () => {
if (typeof window === 'undefined') return null;
return localStorage.getItem('tenantId');
};
// Computed properties // Computed properties
const isInCall = computed(() => currentCall.value !== null); const isInCall = computed(() => currentCall.value !== null);
const hasIncomingCall = computed(() => incomingCall.value !== null); const hasIncomingCall = computed(() => incomingCall.value !== null);
@@ -82,12 +93,6 @@ export function useSoftphone() {
* Initialize Twilio Device * Initialize Twilio Device
*/ */
const initializeTwilioDevice = async () => { const initializeTwilioDevice = async () => {
// Prevent re-initialization if device already exists and is registered
if (twilioDevice.value) {
console.log('Twilio Device already exists, skipping initialization');
return;
}
try { try {
// First, explicitly request microphone permission // First, explicitly request microphone permission
const hasPermission = await requestMicrophonePermission(); const hasPermission = await requestMicrophonePermission();
@@ -102,14 +107,12 @@ export function useSoftphone() {
// Log the token payload to see what identity is being used // Log the token payload to see what identity is being used
try { try {
const tokenPayload = JSON.parse(atob(token.split('.')[1])); const tokenPayload = JSON.parse(atob(token.split('.')[1]));
console.log('📱 Twilio Device identity:', tokenPayload.grants?.identity || tokenPayload.sub);
} catch (e) { } catch (e) {
console.log('Could not parse token payload'); console.log('Could not parse token payload');
} }
console.log('📱 Creating new Twilio Device...');
twilioDevice.value = new Device(token, { twilioDevice.value = new Device(token, {
logLevel: 1, // Reduce log level (1 = errors only, 3 = debug) logLevel: 3,
codecPreferences: ['opus', 'pcmu'], codecPreferences: ['opus', 'pcmu'],
enableImprovedSignalingErrorPrecision: true, enableImprovedSignalingErrorPrecision: true,
edge: 'ashburn', edge: 'ashburn',
@@ -117,12 +120,10 @@ export function useSoftphone() {
// Device events // Device events
twilioDevice.value.on('registered', () => { twilioDevice.value.on('registered', () => {
console.log('✅ Twilio Device registered successfully');
toast.success('Softphone ready'); toast.success('Softphone ready');
}); });
twilioDevice.value.on('unregistered', () => { twilioDevice.value.on('unregistered', () => {
console.log('📱 Twilio Device unregistered');
}); });
twilioDevice.value.on('error', (error) => { twilioDevice.value.on('error', (error) => {
@@ -131,11 +132,6 @@ export function useSoftphone() {
}); });
twilioDevice.value.on('incoming', (call: TwilioCall) => { twilioDevice.value.on('incoming', (call: TwilioCall) => {
console.log('📞 Twilio Device incoming call event!', {
callSid: call.parameters.CallSid,
from: call.parameters.From,
to: call.parameters.To,
});
twilioCall.value = call; twilioCall.value = call;
// Update state // Update state
@@ -214,29 +210,10 @@ export function useSoftphone() {
/** /**
* Initialize WebSocket connection * Initialize WebSocket connection
*/ */
const connect = async () => { const connect = () => {
// Guard against multiple connection attempts const token = getToken();
if (socket.value) {
console.log('Softphone: Socket already exists, skipping connection');
return;
}
// Check if user is authenticated if (socket.value?.connected || !token) {
if (!auth.isAuthenticated.value) {
// Try to verify authentication first
const isValid = await auth.checkAuth();
if (!isValid) {
console.log('Softphone: User not authenticated, skipping connection');
return;
}
}
try {
// Get WebSocket token from BFF (this retrieves the token from HTTP-only cookie server-side)
const wsAuth = await $fetch('/api/auth/ws-token');
if (!wsAuth.token) {
console.log('Softphone: No WebSocket token available');
return; return;
} }
@@ -253,7 +230,7 @@ export function useSoftphone() {
// Connect to /voice namespace with proper auth header // Connect to /voice namespace with proper auth header
socket.value = io(`${getBackendUrl()}/voice`, { socket.value = io(`${getBackendUrl()}/voice`, {
auth: { auth: {
token: wsAuth.token, token: token,
}, },
transports: ['websocket', 'polling'], transports: ['websocket', 'polling'],
reconnection: true, reconnection: true,
@@ -302,10 +279,6 @@ export function useSoftphone() {
socket.value.on('ai:action', handleAiAction); socket.value.on('ai:action', handleAiAction);
isInitialized.value = true; isInitialized.value = true;
} catch (error: any) {
console.error('Softphone: Failed to connect:', error);
toast.error('Failed to initialize voice service');
}
}; };
/** /**
@@ -596,25 +569,14 @@ export function useSoftphone() {
} }
}; };
// Only set up auto-connect and watchers once (not for every component that uses this composable) // Auto-connect on mount if token is available
// Use a module-level flag to track if watchers are already set up onMounted(() => {
if (process.client && !isInitialized.value && !socket.value) { if (getToken() && !isInitialized.value) {
// Auto-connect if authenticated
if (auth.isAuthenticated.value) {
connect(); connect();
} }
// Watch for authentication changes to connect/disconnect
watch(() => auth.isAuthenticated.value, async (isAuth) => {
if (isAuth && !isInitialized.value && !socket.value) {
await connect();
} else if (!isAuth && isInitialized.value) {
disconnect();
}
}); });
}
// Cleanup on unmount - only stop ringtone, don't disconnect shared socket // Cleanup on unmount
onUnmounted(() => { onUnmounted(() => {
stopRingtone(); stopRingtone();
}); });

View File

@@ -1,4 +1,4 @@
export default defineNuxtRouteMiddleware(async (to, from) => { export default defineNuxtRouteMiddleware((to, from) => {
// Allow pages to opt-out of auth with definePageMeta({ auth: false }) // Allow pages to opt-out of auth with definePageMeta({ auth: false })
if (to.meta.auth === false) { if (to.meta.auth === false) {
return return
@@ -11,45 +11,28 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
return return
} }
const token = useCookie('token')
const authMessage = useCookie('authMessage') const authMessage = useCookie('authMessage')
// Check for tenant cookie (set alongside session cookie on login)
const tenantCookie = useCookie('routebox_tenant')
// Also check for session cookie (HTTP-only, but readable in SSR context)
const sessionCookie = useCookie('routebox_session')
// Routes that don't need a toast message (user knows they need to login) // Routes that don't need a toast message (user knows they need to login)
const silentRoutes = ['/'] const silentRoutes = ['/']
// On client side, check the reactive auth state // Check token cookie (works on both server and client)
if (!token.value) {
if (!silentRoutes.includes(to.path)) {
authMessage.value = 'Please login to access this page'
}
return navigateTo('/login')
}
// On client side, also verify localStorage is in sync
if (import.meta.client) { if (import.meta.client) {
const { isAuthenticated, checkAuth } = useAuth() const { isLoggedIn } = useAuth()
if (!isLoggedIn()) {
// If we already know we're authenticated, allow
if (isAuthenticated.value) {
return
}
// If we have a tenant cookie, try to validate the session
if (tenantCookie.value) {
const isValid = await checkAuth()
if (isValid) {
return
}
}
// Not authenticated
if (!silentRoutes.includes(to.path)) { if (!silentRoutes.includes(to.path)) {
authMessage.value = 'Please login to access this page' authMessage.value = 'Please login to access this page'
} }
return navigateTo('/login') return navigateTo('/login')
} }
// Server-side: check for both session and tenant cookies
// The session cookie is HTTP-only but can be read in SSR context
if (!sessionCookie.value || !tenantCookie.value) {
if (!silentRoutes.includes(to.path)) {
authMessage.value = 'Please login to access this page'
}
return navigateTo('/login')
} }
}) })

View File

@@ -24,9 +24,9 @@ export default defineNuxtConfig({
}, },
runtimeConfig: { runtimeConfig: {
// Server-only config (not exposed to client) public: {
// Used by Nitro BFF to proxy requests to the NestJS backend apiBaseUrl: process.env.NUXT_PUBLIC_API_BASE_URL || 'http://localhost:3000',
backendUrl: process.env.BACKEND_URL || 'http://localhost:3000', },
}, },
app: { app: {

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,6 @@ import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi' import { useApi } from '@/composables/useApi'
import { useFields, useViewState } from '@/composables/useFieldViews' import { useFields, useViewState } from '@/composables/useFieldViews'
import { usePageLayouts } from '@/composables/usePageLayouts'
import ListView from '@/components/views/ListView.vue' import ListView from '@/components/views/ListView.vue'
import DetailView from '@/components/views/DetailViewEnhanced.vue' import DetailView from '@/components/views/DetailViewEnhanced.vue'
import EditView from '@/components/views/EditViewEnhanced.vue' import EditView from '@/components/views/EditViewEnhanced.vue'
@@ -20,7 +19,6 @@ const route = useRoute()
const router = useRouter() const router = useRouter()
const { api } = useApi() const { api } = useApi()
const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields() const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields()
const { getDefaultPageLayout } = usePageLayouts()
// Use breadcrumbs composable // Use breadcrumbs composable
const { setBreadcrumbs } = useBreadcrumbs() const { setBreadcrumbs } = useBreadcrumbs()
@@ -42,7 +40,6 @@ const view = computed(() => {
// State // State
const objectDefinition = ref<any>(null) const objectDefinition = ref<any>(null)
const listViewLayout = ref<any>(null)
const loading = ref(true) const loading = ref(true)
const error = ref<string | null>(null) const error = ref<string | null>(null)
@@ -137,13 +134,11 @@ watch([objectDefinition, currentRecord, recordId], () => {
// View configs // View configs
const listConfig = computed(() => { const listConfig = computed(() => {
if (!objectDefinition.value) return null if (!objectDefinition.value) return null
// Pass the list view layout config to buildListViewConfig if available
const layoutConfig = listViewLayout.value?.layout_config || listViewLayout.value?.layoutConfig
return buildListViewConfig(objectDefinition.value, { return buildListViewConfig(objectDefinition.value, {
searchable: true, searchable: true,
exportable: true, exportable: true,
filterable: true, filterable: true,
}, layoutConfig) })
}) })
const detailConfig = computed(() => { const detailConfig = computed(() => {
@@ -177,16 +172,6 @@ const fetchObjectDefinition = async () => {
error.value = null error.value = null
const response = await api.get(`/setup/objects/${objectApiName.value}`) const response = await api.get(`/setup/objects/${objectApiName.value}`)
objectDefinition.value = response objectDefinition.value = response
// Fetch the default list view layout for this object
if (response?.id) {
try {
listViewLayout.value = await getDefaultPageLayout(response.id, 'list')
} catch (e) {
// No list view layout configured, will use default behavior
listViewLayout.value = null
}
}
} catch (e: any) { } catch (e: any) {
error.value = e.message || 'Failed to load object definition' error.value = e.message || 'Failed to load object definition'
console.error('Error fetching object definition:', e) console.error('Error fetching object definition:', e)

View File

@@ -3,7 +3,6 @@ import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi' import { useApi } from '@/composables/useApi'
import { useFields, useViewState } from '@/composables/useFieldViews' import { useFields, useViewState } from '@/composables/useFieldViews'
import { usePageLayouts } from '@/composables/usePageLayouts'
import ListView from '@/components/views/ListView.vue' import ListView from '@/components/views/ListView.vue'
import DetailView from '@/components/views/DetailView.vue' import DetailView from '@/components/views/DetailView.vue'
import EditView from '@/components/views/EditView.vue' import EditView from '@/components/views/EditView.vue'
@@ -12,7 +11,6 @@ const route = useRoute()
const router = useRouter() const router = useRouter()
const { api } = useApi() const { api } = useApi()
const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields() const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields()
const { getDefaultPageLayout } = usePageLayouts()
// Get object API name from route // Get object API name from route
const objectApiName = computed(() => route.params.objectName as string) const objectApiName = computed(() => route.params.objectName as string)
@@ -27,7 +25,6 @@ const view = computed(() => {
// State // State
const objectDefinition = ref<any>(null) const objectDefinition = ref<any>(null)
const listViewLayout = ref<any>(null)
const loading = ref(true) const loading = ref(true)
const error = ref<string | null>(null) const error = ref<string | null>(null)
@@ -69,13 +66,11 @@ onBeforeUnmount(() => {
// View configs // View configs
const listConfig = computed(() => { const listConfig = computed(() => {
if (!objectDefinition.value) return null if (!objectDefinition.value) return null
// Pass the list view layout config to buildListViewConfig if available
const layoutConfig = listViewLayout.value?.layout_config || listViewLayout.value?.layoutConfig
return buildListViewConfig(objectDefinition.value, { return buildListViewConfig(objectDefinition.value, {
searchable: true, searchable: true,
exportable: true, exportable: true,
filterable: true, filterable: true,
}, layoutConfig) })
}) })
const detailConfig = computed(() => { const detailConfig = computed(() => {
@@ -98,16 +93,6 @@ const fetchObjectDefinition = async () => {
error.value = null error.value = null
const response = await api.get(`/setup/objects/${objectApiName.value}`) const response = await api.get(`/setup/objects/${objectApiName.value}`)
objectDefinition.value = response objectDefinition.value = response
// Fetch the default list view layout for this object
if (response?.id) {
try {
listViewLayout.value = await getDefaultPageLayout(response.id, 'list')
} catch (e) {
// No list view layout configured, will use default behavior
listViewLayout.value = null
}
}
} catch (e: any) { } catch (e: any) {
error.value = e.message || 'Failed to load object definition' error.value = e.message || 'Failed to load object definition'
console.error('Error fetching object definition:', e) console.error('Error fetching object definition:', e)

View File

@@ -74,8 +74,24 @@ definePageMeta({
auth: false auth: false
}) })
const config = useRuntimeConfig()
const router = useRouter() const router = useRouter()
// Extract subdomain from hostname
const getSubdomain = () => {
if (!import.meta.client) return null
const hostname = window.location.hostname
const parts = hostname.split('.')
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return null
}
if (parts.length > 1 && parts[0] !== 'www') {
return parts[0]
}
return null
}
const subdomain = ref(getSubdomain())
const email = ref('') const email = ref('')
const password = ref('') const password = ref('')
const firstName = ref('') const firstName = ref('')
@@ -90,17 +106,30 @@ const handleRegister = async () => {
error.value = '' error.value = ''
success.value = false success.value = false
// Use BFF proxy - subdomain/tenant is handled automatically by Nitro const headers: Record<string, string> = {
await $fetch('/api/auth/register', { 'Content-Type': 'application/json',
}
if (subdomain.value) {
headers['x-tenant-id'] = subdomain.value
}
const response = await fetch(`${config.public.apiBaseUrl}/api/auth/register`, {
method: 'POST', method: 'POST',
body: { headers,
body: JSON.stringify({
email: email.value, email: email.value,
password: password.value, password: password.value,
firstName: firstName.value || undefined, firstName: firstName.value || undefined,
lastName: lastName.value || undefined, lastName: lastName.value || undefined,
}, }),
}) })
if (!response.ok) {
const data = await response.json()
throw new Error(data.message || 'Registration failed')
}
success.value = true success.value = true
// Redirect to login after 2 seconds // Redirect to login after 2 seconds
@@ -108,10 +137,9 @@ const handleRegister = async () => {
router.push('/login') router.push('/login')
}, 2000) }, 2000)
} catch (e: any) { } catch (e: any) {
error.value = e.data?.message || e.message || 'Registration failed' error.value = e.message || 'Registration failed'
} finally { } finally {
loading.value = false loading.value = false
} }
} }
</script> </script>

View File

@@ -16,11 +16,10 @@
<!-- Tabs --> <!-- Tabs -->
<div class="mb-8"> <div class="mb-8">
<Tabs v-model="activeTab" default-value="fields" class="w-full"> <Tabs v-model="activeTab" default-value="fields" class="w-full">
<TabsList class="grid w-full grid-cols-4 max-w-2xl"> <TabsList class="grid w-full grid-cols-3 max-w-2xl">
<TabsTrigger value="fields">Fields</TabsTrigger> <TabsTrigger value="fields">Fields</TabsTrigger>
<TabsTrigger value="access">Access</TabsTrigger> <TabsTrigger value="access">Access</TabsTrigger>
<TabsTrigger value="layouts">Page Layouts</TabsTrigger> <TabsTrigger value="layouts">Page Layouts</TabsTrigger>
<TabsTrigger value="listLayouts">List View Layouts</TabsTrigger>
</TabsList> </TabsList>
<!-- Fields Tab --> <!-- Fields Tab -->
@@ -149,7 +148,7 @@
</div> </div>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<span <span
v-if="layout.isDefault || layout.is_default" v-if="layout.isDefault"
class="px-2 py-1 bg-primary/10 text-primary rounded text-xs" class="px-2 py-1 bg-primary/10 text-primary rounded text-xs"
> >
Default Default
@@ -186,84 +185,6 @@
/> />
</div> </div>
</TabsContent> </TabsContent>
<!-- List View Layouts Tab -->
<TabsContent value="listLayouts" class="mt-6">
<div v-if="!selectedListLayout" class="space-y-4">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-semibold">List View Layouts</h2>
<Button @click="handleCreateListLayout">
<Plus class="w-4 h-4 mr-2" />
New List Layout
</Button>
</div>
<p class="text-sm text-muted-foreground mb-4">
Configure which fields appear in list views and their order.
</p>
<div v-if="loadingListLayouts" class="text-center py-8">
Loading list layouts...
</div>
<div v-else-if="listLayouts.length === 0" class="text-center py-8 text-muted-foreground">
No list view layouts yet. Create one to customize your list views.
</div>
<div v-else class="space-y-2">
<div
v-for="layout in listLayouts"
:key="layout.id"
class="p-4 border rounded-lg bg-card hover:border-primary cursor-pointer transition-colors"
@click="handleSelectListLayout(layout)"
>
<div class="flex items-center justify-between">
<div>
<h3 class="font-semibold">{{ layout.name }}</h3>
<p v-if="layout.description" class="text-sm text-muted-foreground">
{{ layout.description }}
</p>
<p class="text-xs text-muted-foreground mt-1">
{{ getListLayoutFieldCount(layout) }} fields configured
</p>
</div>
<div class="flex items-center gap-2">
<span
v-if="layout.isDefault || layout.is_default"
class="px-2 py-1 bg-primary/10 text-primary rounded text-xs"
>
Default
</span>
<Button
variant="ghost"
size="sm"
@click.stop="handleDeleteListLayout(layout.id)"
>
<Trash2 class="w-4 h-4" />
</Button>
</div>
</div>
</div>
</div>
</div>
<!-- List Layout Editor -->
<div v-else>
<div class="mb-4">
<Button variant="outline" @click="selectedListLayout = null">
<ArrowLeft class="w-4 h-4 mr-2" />
Back to List Layouts
</Button>
</div>
<ListViewLayoutEditor
:fields="object.fields"
:initial-layout="(selectedListLayout.layoutConfig || selectedListLayout.layout_config)?.fields || []"
:layout-name="selectedListLayout.name"
@save="handleSaveListLayout"
/>
</div>
</TabsContent>
</Tabs> </Tabs>
</div> </div>
</div> </div>
@@ -378,7 +299,6 @@ import { Plus, Trash2, ArrowLeft } from 'lucide-vue-next'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import PageLayoutEditor from '@/components/PageLayoutEditor.vue' import PageLayoutEditor from '@/components/PageLayoutEditor.vue'
import ListViewLayoutEditor from '@/components/ListViewLayoutEditor.vue'
import ObjectAccessSettings from '@/components/ObjectAccessSettings.vue' import ObjectAccessSettings from '@/components/ObjectAccessSettings.vue'
import FieldTypeSelector from '@/components/fields/FieldTypeSelector.vue' import FieldTypeSelector from '@/components/fields/FieldTypeSelector.vue'
import FieldAttributesCommon from '@/components/fields/FieldAttributesCommon.vue' import FieldAttributesCommon from '@/components/fields/FieldAttributesCommon.vue'
@@ -395,16 +315,11 @@ const loading = ref(true)
const error = ref<string | null>(null) const error = ref<string | null>(null)
const activeTab = ref('fields') const activeTab = ref('fields')
// Page layouts state (detail/edit layouts) // Page layouts state
const layouts = ref<PageLayout[]>([]) const layouts = ref<PageLayout[]>([])
const loadingLayouts = ref(false) const loadingLayouts = ref(false)
const selectedLayout = ref<PageLayout | null>(null) const selectedLayout = ref<PageLayout | null>(null)
// List view layouts state
const listLayouts = ref<PageLayout[]>([])
const loadingListLayouts = ref(false)
const selectedListLayout = ref<PageLayout | null>(null)
// Field management state // Field management state
const showFieldDialog = ref(false) const showFieldDialog = ref(false)
const fieldDialogMode = ref<'create' | 'edit'>('create') const fieldDialogMode = ref<'create' | 'edit'>('create')
@@ -505,8 +420,7 @@ const fetchLayouts = async () => {
try { try {
loadingLayouts.value = true loadingLayouts.value = true
// Fetch only detail layouts (default type) layouts.value = await getPageLayouts(object.value.id)
layouts.value = await getPageLayouts(object.value.id, 'detail')
} catch (e: any) { } catch (e: any) {
console.error('Error fetching layouts:', e) console.error('Error fetching layouts:', e)
toast.error('Failed to load page layouts') toast.error('Failed to load page layouts')
@@ -515,20 +429,6 @@ const fetchLayouts = async () => {
} }
} }
const fetchListLayouts = async () => {
if (!object.value) return
try {
loadingListLayouts.value = true
listLayouts.value = await getPageLayouts(object.value.id, 'list')
} catch (e: any) {
console.error('Error fetching list layouts:', e)
toast.error('Failed to load list view layouts')
} finally {
loadingListLayouts.value = false
}
}
const openFieldDialog = async (mode: 'create' | 'edit', field?: any) => { const openFieldDialog = async (mode: 'create' | 'edit', field?: any) => {
fieldDialogMode.value = mode fieldDialogMode.value = mode
fieldDialogError.value = null fieldDialogError.value = null
@@ -784,7 +684,6 @@ const handleCreateLayout = async () => {
const newLayout = await createPageLayout({ const newLayout = await createPageLayout({
name, name,
objectId: object.value.id, objectId: object.value.id,
layoutType: 'detail',
isDefault: layouts.value.length === 0, isDefault: layouts.value.length === 0,
layoutConfig: { fields: [], relatedLists: [] }, layoutConfig: { fields: [], relatedLists: [] },
}) })
@@ -837,73 +736,6 @@ const handleDeleteLayout = async (layoutId: string) => {
} }
} }
// List View Layout methods
const handleCreateListLayout = async () => {
const name = prompt('Enter a name for the new list view layout:')
if (!name) return
try {
const newLayout = await createPageLayout({
name,
objectId: object.value.id,
layoutType: 'list',
isDefault: listLayouts.value.length === 0,
layoutConfig: { fields: [] },
})
listLayouts.value.push(newLayout)
selectedListLayout.value = newLayout
toast.success('List view layout created successfully')
} catch (e: any) {
console.error('Error creating list layout:', e)
toast.error('Failed to create list view layout')
}
}
const handleSelectListLayout = (layout: PageLayout) => {
selectedListLayout.value = layout
}
const handleSaveListLayout = async (layoutConfig: { fields: FieldLayoutItem[] }) => {
if (!selectedListLayout.value) return
try {
const updated = await updatePageLayout(selectedListLayout.value.id, {
layoutConfig,
})
// Update the layout in the list
const index = listLayouts.value.findIndex(l => l.id === selectedListLayout.value!.id)
if (index !== -1) {
listLayouts.value[index] = updated
}
selectedListLayout.value = updated
toast.success('List view layout saved successfully')
} catch (e: any) {
console.error('Error saving list layout:', e)
toast.error('Failed to save list view layout')
}
}
const handleDeleteListLayout = async (layoutId: string) => {
if (!confirm('Are you sure you want to delete this list view layout?')) return
try {
await deletePageLayout(layoutId)
listLayouts.value = listLayouts.value.filter(l => l.id !== layoutId)
toast.success('List view layout deleted successfully')
} catch (e: any) {
console.error('Error deleting list layout:', e)
toast.error('Failed to delete list view layout')
}
}
const getListLayoutFieldCount = (layout: PageLayout): number => {
const config = layout.layoutConfig || layout.layout_config
return config?.fields?.length || 0
}
const handleAccessUpdate = (orgWideDefault: string) => { const handleAccessUpdate = (orgWideDefault: string) => {
if (object.value) { if (object.value) {
object.value.orgWideDefault = orgWideDefault object.value.orgWideDefault = orgWideDefault
@@ -915,9 +747,6 @@ watch(activeTab, (newTab) => {
if (newTab === 'layouts' && layouts.value.length === 0 && !loadingLayouts.value) { if (newTab === 'layouts' && layouts.value.length === 0 && !loadingLayouts.value) {
fetchLayouts() fetchLayouts()
} }
if (newTab === 'listLayouts' && listLayouts.value.length === 0 && !loadingListLayouts.value) {
fetchListLayouts()
}
}) })
onMounted(async () => { onMounted(async () => {
@@ -926,8 +755,5 @@ onMounted(async () => {
if (activeTab.value === 'layouts') { if (activeTab.value === 'layouts') {
await fetchLayouts() await fetchLayouts()
} }
if (activeTab.value === 'listLayouts') {
await fetchListLayouts()
}
}) })
</script> </script>

View File

@@ -1,119 +0,0 @@
import { defineEventHandler, getMethod, readBody, getQuery, createError, getHeader } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken } from '~/server/utils/session'
/**
* Catch-all API proxy that forwards requests to the NestJS backend
* Injects x-tenant-subdomain header and Authorization from HTTP-only cookie
*/
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const method = getMethod(event)
const path = event.context.params?.path || ''
// Get subdomain and session token
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
const backendUrl = config.backendUrl || 'http://localhost:3000'
// Build the full URL with query parameters
const query = getQuery(event)
const queryString = new URLSearchParams(query as Record<string, string>).toString()
const fullUrl = `${backendUrl}/api/${path}${queryString ? `?${queryString}` : ''}`
console.log(`[BFF Proxy] ${method} ${fullUrl} (subdomain: ${subdomain}, hasToken: ${!!token})`)
// Build headers to forward
const headers: Record<string, string> = {
'Content-Type': getHeader(event, 'content-type') || 'application/json',
}
// Add subdomain header for backend tenant resolution
if (subdomain) {
headers['x-tenant-subdomain'] = subdomain
}
// Add auth token from HTTP-only cookie
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
// Forward additional headers that might be needed
const acceptHeader = getHeader(event, 'accept')
if (acceptHeader) {
headers['Accept'] = acceptHeader
}
try {
// Prepare fetch options
const fetchOptions: RequestInit = {
method,
headers,
}
// Add body for methods that support it
if (['POST', 'PUT', 'PATCH'].includes(method)) {
const body = await readBody(event)
if (body) {
fetchOptions.body = JSON.stringify(body)
}
}
// Make request to backend
const response = await fetch(fullUrl, fetchOptions)
// Handle non-JSON responses (like file downloads)
const contentType = response.headers.get('content-type')
if (!response.ok) {
// Try to get error details
let errorMessage = `Backend error: ${response.status}`
let errorData = null
try {
errorData = await response.json()
errorMessage = errorData.message || errorMessage
} catch {
// Response wasn't JSON
try {
const text = await response.text()
console.error(`[BFF Proxy] Backend error (non-JSON): ${text}`)
} catch {}
}
console.error(`[BFF Proxy] Backend returned ${response.status}: ${errorMessage}`, errorData)
throw createError({
statusCode: response.status,
statusMessage: errorMessage,
data: errorData,
})
}
// Return empty response for 204 No Content
if (response.status === 204) {
return null
}
// Handle JSON responses
if (contentType?.includes('application/json')) {
return await response.json()
}
// Handle other content types (text, etc.)
return await response.text()
} catch (error: any) {
// Re-throw H3 errors
if (error.statusCode) {
throw error
}
console.error(`Proxy error for ${method} /api/${path}:`, error)
throw createError({
statusCode: 502,
statusMessage: 'Failed to connect to backend service',
})
}
})

View File

@@ -1,81 +0,0 @@
import { defineEventHandler, readBody, createError } from 'h3'
import { getSubdomainFromRequest, isCentralSubdomain } from '~/server/utils/tenant'
import { setSessionCookie, setTenantIdCookie } from '~/server/utils/session'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const body = await readBody(event)
// Extract subdomain from the request
const subdomain = getSubdomainFromRequest(event)
if (!subdomain) {
throw createError({
statusCode: 400,
statusMessage: 'Unable to determine tenant from subdomain',
})
}
// Determine the backend URL based on whether this is central admin or tenant
const isCentral = isCentralSubdomain(subdomain)
const backendUrl = config.backendUrl || 'http://localhost:3000'
const loginEndpoint = isCentral ? '/api/auth/central/login' : '/api/auth/login'
try {
// Forward login request to NestJS backend with subdomain header
const response = await fetch(`${backendUrl}${loginEndpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-tenant-subdomain': subdomain,
},
body: JSON.stringify(body),
})
const data = await response.json()
if (!response.ok) {
throw createError({
statusCode: response.status,
statusMessage: data.message || 'Login failed',
data: data,
})
}
// Extract token and tenant info from response
const { access_token, user, tenantId } = data
if (!access_token) {
throw createError({
statusCode: 500,
statusMessage: 'No access token received from backend',
})
}
// Set HTTP-only cookie with the JWT token
setSessionCookie(event, access_token)
// Set tenant ID cookie (readable by client for context)
// Use tenantId from response, or fall back to subdomain
const tenantToStore = tenantId || subdomain
setTenantIdCookie(event, tenantToStore)
// Return user info (but NOT the token - it's in HTTP-only cookie)
return {
success: true,
user,
tenantId: tenantToStore,
}
} catch (error: any) {
// Re-throw H3 errors
if (error.statusCode) {
throw error
}
console.error('Login proxy error:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to connect to authentication service',
})
}
})

View File

@@ -1,37 +0,0 @@
import { defineEventHandler, createError } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken, clearSessionCookie, clearTenantIdCookie } from '~/server/utils/session'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
const backendUrl = config.backendUrl || 'http://localhost:3000'
try {
// Call backend logout endpoint if we have a token
if (token) {
await fetch(`${backendUrl}/api/auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
...(subdomain && { 'x-tenant-subdomain': subdomain }),
},
})
}
} catch (error) {
// Log but don't fail - we still want to clear cookies
console.error('Backend logout error:', error)
}
// Always clear cookies regardless of backend response
clearSessionCookie(event)
clearTenantIdCookie(event)
return {
success: true,
message: 'Logged out successfully',
}
})

View File

@@ -1,60 +0,0 @@
import { defineEventHandler, createError } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken } from '~/server/utils/session'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
if (!token) {
throw createError({
statusCode: 401,
statusMessage: 'Not authenticated',
})
}
const backendUrl = config.backendUrl || 'http://localhost:3000'
try {
// Fetch current user from backend
const response = await fetch(`${backendUrl}/api/auth/me`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
...(subdomain && { 'x-tenant-subdomain': subdomain }),
},
})
if (!response.ok) {
if (response.status === 401) {
throw createError({
statusCode: 401,
statusMessage: 'Session expired',
})
}
throw createError({
statusCode: response.status,
statusMessage: 'Failed to fetch user',
})
}
const user = await response.json()
return {
authenticated: true,
user,
}
} catch (error: any) {
if (error.statusCode) {
throw error
}
console.error('Auth check error:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to verify authentication',
})
}
})

View File

@@ -1,26 +0,0 @@
import { defineEventHandler, createError } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken } from '~/server/utils/session'
/**
* Get a short-lived token for WebSocket authentication
* This is needed because socket.io cannot use HTTP-only cookies directly
*/
export default defineEventHandler(async (event) => {
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
if (!token) {
throw createError({
statusCode: 401,
statusMessage: 'Not authenticated',
})
}
// Return the token for WebSocket use
// The token is already validated by being in the HTTP-only cookie
return {
token,
subdomain,
}
})

View File

@@ -1,94 +0,0 @@
import type { H3Event } from 'h3'
import { getCookie, setCookie, deleteCookie, getHeader } from 'h3'
const SESSION_COOKIE_NAME = 'routebox_session'
const SESSION_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
export interface SessionData {
token: string
tenantId: string
userId: string
email: string
}
/**
* Determine if the request is over a secure connection
* Checks both direct HTTPS and proxy headers
*/
function isSecureRequest(event: H3Event): boolean {
// Check x-forwarded-proto header (set by reverse proxies)
const forwardedProto = getHeader(event, 'x-forwarded-proto')
if (forwardedProto === 'https') {
return true
}
// Check if NODE_ENV is production (assume HTTPS in production)
if (process.env.NODE_ENV === 'production') {
return true
}
return false
}
/**
* Get the session token from HTTP-only cookie
*/
export function getSessionToken(event: H3Event): string | null {
return getCookie(event, SESSION_COOKIE_NAME) || null
}
/**
* Set the session token in an HTTP-only cookie
*/
export function setSessionCookie(event: H3Event, token: string): void {
const secure = isSecureRequest(event)
setCookie(event, SESSION_COOKIE_NAME, token, {
httpOnly: true,
secure,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE,
path: '/',
})
}
/**
* Clear the session cookie
*/
export function clearSessionCookie(event: H3Event): void {
deleteCookie(event, SESSION_COOKIE_NAME, {
path: '/',
})
}
/**
* Get tenant ID from a separate cookie (for SSR access)
* This is NOT the auth token - just tenant context
*/
export function getTenantIdFromCookie(event: H3Event): string | null {
return getCookie(event, 'routebox_tenant') || null
}
/**
* Set tenant ID cookie (readable by client for context)
*/
export function setTenantIdCookie(event: H3Event, tenantId: string): void {
const secure = isSecureRequest(event)
setCookie(event, 'routebox_tenant', tenantId, {
httpOnly: false, // Allow client to read tenant context
secure,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE,
path: '/',
})
}
/**
* Clear tenant ID cookie
*/
export function clearTenantIdCookie(event: H3Event): void {
deleteCookie(event, 'routebox_tenant', {
path: '/',
})
}

View File

@@ -1,39 +0,0 @@
import type { H3Event } from 'h3'
import { getHeader } from 'h3'
/**
* Extract subdomain from the request Host header
* Handles production domains (tenant1.routebox.co) and development (tenant1.localhost)
*/
export function getSubdomainFromRequest(event: H3Event): string | null {
const host = getHeader(event, 'host') || ''
const hostname = host.split(':')[0] // Remove port if present
const parts = hostname.split('.')
// For production domains with 3+ parts (e.g., tenant1.routebox.co)
if (parts.length >= 3) {
const subdomain = parts[0]
// Ignore www subdomain
if (subdomain === 'www') {
return null
}
return subdomain
}
// For development (e.g., tenant1.localhost)
if (parts.length === 2 && parts[1] === 'localhost') {
return parts[0]
}
return null
}
/**
* Check if the subdomain is a central/admin subdomain
*/
export function isCentralSubdomain(subdomain: string | null): boolean {
if (!subdomain) return false
const centralSubdomains = (process.env.CENTRAL_SUBDOMAINS || 'central,admin').split(',')
return centralSubdomains.includes(subdomain)
}

View File

@@ -1,15 +1,11 @@
export interface FieldLayoutItem { export interface FieldLayoutItem {
fieldId: string; fieldId: string;
x?: number; x: number;
y?: number; y: number;
w?: number; w: number;
h?: number; h: number;
// For list layouts: field order (optional)
order?: number;
} }
export type PageLayoutType = 'detail' | 'list';
export interface PageLayoutConfig { export interface PageLayoutConfig {
fields: FieldLayoutItem[]; fields: FieldLayoutItem[];
relatedLists?: string[]; relatedLists?: string[];
@@ -19,23 +15,16 @@ export interface PageLayout {
id: string; id: string;
name: string; name: string;
objectId: string; objectId: string;
layoutType: PageLayoutType;
isDefault: boolean; isDefault: boolean;
layoutConfig: PageLayoutConfig; layoutConfig: PageLayoutConfig;
description?: string; description?: string;
createdAt?: string; createdAt?: string;
updatedAt?: string; updatedAt?: string;
// Database column names (snake_case) - used when data comes directly from DB
layout_type?: PageLayoutType;
layout_config?: PageLayoutConfig;
object_id?: string;
is_default?: boolean;
} }
export interface CreatePageLayoutRequest { export interface CreatePageLayoutRequest {
name: string; name: string;
objectId: string; objectId: string;
layoutType?: PageLayoutType;
isDefault?: boolean; isDefault?: boolean;
layoutConfig: PageLayoutConfig; layoutConfig: PageLayoutConfig;
description?: string; description?: string;