Compare commits
7 Commits
master
...
copilot-wo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97fc235636 | ||
|
|
c7282ee2a0 | ||
|
|
ce65817670 | ||
|
|
fe51355d29 | ||
|
|
4f466d7992 | ||
|
|
c822017ef1 | ||
|
|
8b192ba7f5 |
4
.env.web
4
.env.web
@@ -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
|
||||||
|
|||||||
@@ -2,94 +2,24 @@
|
|||||||
* @param { import("knex").Knex } knex
|
* @param { import("knex").Knex } knex
|
||||||
* @returns { Promise<void> }
|
* @returns { Promise<void> }
|
||||||
*/
|
*/
|
||||||
exports.up = async function(knex) {
|
exports.up = function(knex) {
|
||||||
// Check if layout_type column already exists (in case of partial migration)
|
return knex.schema.alterTable('page_layouts', (table) => {
|
||||||
const hasLayoutType = await knex.schema.hasColumn('page_layouts', 'layout_type');
|
// Add layout_type column to distinguish between detail/edit layouts and list view layouts
|
||||||
|
// Default to 'detail' for existing layouts
|
||||||
// Check if the old index exists
|
table.enum('layout_type', ['detail', 'list']).notNullable().defaultTo('detail').after('name');
|
||||||
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;
|
// Update the unique index to include layout_type so we can have both a default detail and default list layout
|
||||||
|
table.dropIndex(['object_id', 'is_default']);
|
||||||
// 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
|
* @param { import("knex").Knex } knex
|
||||||
* @returns { Promise<void> }
|
* @returns { Promise<void> }
|
||||||
*/
|
*/
|
||||||
exports.down = async function(knex) {
|
exports.down = function(knex) {
|
||||||
// Drop the foreign key first
|
return knex.schema.alterTable('page_layouts', (table) => {
|
||||||
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.dropColumn('layout_type');
|
||||||
table.index(['object_id', 'is_default']);
|
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');
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
/**
|
|
||||||
* Creates the saved_list_views table.
|
|
||||||
* Each row stores a named, reusable search/filter configuration for a specific
|
|
||||||
* CRM object type. Views can be private to the owning user or shared with the
|
|
||||||
* whole tenant.
|
|
||||||
*
|
|
||||||
* @param { import("knex").Knex } knex
|
|
||||||
* @returns { Promise<void> }
|
|
||||||
*/
|
|
||||||
exports.up = function (knex) {
|
|
||||||
return knex.schema.createTable('saved_list_views', (table) => {
|
|
||||||
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
|
|
||||||
|
|
||||||
// Human-readable name given by the user (or AI-suggested)
|
|
||||||
table.string('name').notNullable();
|
|
||||||
|
|
||||||
// The object this view belongs to (e.g. "Dog", "Contact")
|
|
||||||
table.string('object_api_name').notNullable();
|
|
||||||
|
|
||||||
// The user who created/owns this view
|
|
||||||
table.uuid('user_id').notNullable();
|
|
||||||
|
|
||||||
// When true the view is visible to all users in the tenant
|
|
||||||
table.boolean('is_shared').notNullable().defaultTo(false);
|
|
||||||
|
|
||||||
// Strategy is always "query" for saved views (keyword views are not saved)
|
|
||||||
table.string('strategy').notNullable().defaultTo('query');
|
|
||||||
|
|
||||||
// Resolved filters as JSON array of AiSearchFilter objects
|
|
||||||
table.json('filters').notNullable();
|
|
||||||
|
|
||||||
// Optional sort: { field: string, direction: "asc" | "desc" }
|
|
||||||
table.json('sort').nullable();
|
|
||||||
|
|
||||||
// AI-generated plain-language explanation of what this view shows
|
|
||||||
table.text('description').nullable();
|
|
||||||
|
|
||||||
table.timestamps(true, true);
|
|
||||||
|
|
||||||
// Foreign key to users
|
|
||||||
table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
|
|
||||||
|
|
||||||
// Primary lookup: all views for an object visible to a user
|
|
||||||
table.index(['object_api_name', 'user_id']);
|
|
||||||
table.index(['object_api_name', 'is_shared']);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param { import("knex").Knex } knex
|
|
||||||
* @returns { Promise<void> }
|
|
||||||
*/
|
|
||||||
exports.down = function (knex) {
|
|
||||||
return knex.schema.dropTableIfExists('saved_list_views');
|
|
||||||
};
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
/**
|
|
||||||
* Inserts a system object_definition row for SavedListView.
|
|
||||||
* This allows saved_list_views records to be shared via record_shares
|
|
||||||
* (which requires a valid objectDefinitionId FK).
|
|
||||||
*
|
|
||||||
* @param { import("knex").Knex } knex
|
|
||||||
* @returns { Promise<void> }
|
|
||||||
*/
|
|
||||||
exports.up = async function (knex) {
|
|
||||||
// Only insert if it doesn't already exist (idempotent)
|
|
||||||
const existing = await knex('object_definitions')
|
|
||||||
.where({ apiName: 'SavedListView' })
|
|
||||||
.first();
|
|
||||||
|
|
||||||
if (!existing) {
|
|
||||||
await knex('object_definitions').insert({
|
|
||||||
apiName: 'SavedListView',
|
|
||||||
label: 'Saved List View',
|
|
||||||
pluralLabel: 'Saved List Views',
|
|
||||||
description: 'System object for sharing saved list views via record_shares',
|
|
||||||
isSystem: true,
|
|
||||||
isCustom: false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param { import("knex").Knex } knex
|
|
||||||
* @returns { Promise<void> }
|
|
||||||
*/
|
|
||||||
exports.down = async function (knex) {
|
|
||||||
await knex('object_definitions')
|
|
||||||
.where({ apiName: 'SavedListView' })
|
|
||||||
.delete();
|
|
||||||
};
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
/**
|
|
||||||
* Add 'alias' and virtual 'name' column to users table.
|
|
||||||
*
|
|
||||||
* - alias: a user-editable display name / nickname
|
|
||||||
* - name: a generated column that returns COALESCE(alias, CONCAT(firstName, ' ', lastName), email)
|
|
||||||
* so that lookup fields referencing User.name always resolve.
|
|
||||||
*/
|
|
||||||
exports.up = function (knex) {
|
|
||||||
return knex.schema.alterTable('users', (table) => {
|
|
||||||
table.string('alias', 255).nullable().after('lastName');
|
|
||||||
table.string('name', 512).nullable().after('alias');
|
|
||||||
}).then(() => {
|
|
||||||
// Backfill existing rows: name = alias, or firstName + lastName, or email
|
|
||||||
return knex.raw(`
|
|
||||||
UPDATE users
|
|
||||||
SET name = COALESCE(
|
|
||||||
NULLIF(alias, ''),
|
|
||||||
NULLIF(TRIM(CONCAT(COALESCE(firstName, ''), ' ', COALESCE(lastName, ''))), ''),
|
|
||||||
email
|
|
||||||
)
|
|
||||||
`);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.down = function (knex) {
|
|
||||||
return knex.schema.alterTable('users', (table) => {
|
|
||||||
table.dropColumn('name');
|
|
||||||
table.dropColumn('alias');
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -20,8 +20,6 @@ model User {
|
|||||||
password String
|
password String
|
||||||
firstName String?
|
firstName String?
|
||||||
lastName String?
|
lastName String?
|
||||||
alias String?
|
|
||||||
name String?
|
|
||||||
isActive Boolean @default(true)
|
isActive Boolean @default(true)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|||||||
@@ -38,12 +38,4 @@ export class AiAssistantController {
|
|||||||
payload,
|
payload,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('suggest-view-name')
|
|
||||||
async suggestViewName(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@Body() payload: { objectLabel: string; filters: any[]; explanation?: string },
|
|
||||||
) {
|
|
||||||
return this.aiAssistantService.suggestViewName(tenantId, payload);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ type AiSearchPayload = {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class AiAssistantService {
|
export class AiAssistantService {
|
||||||
private readonly logger = new Logger(AiAssistantService.name);
|
private readonly logger = new Logger(AiAssistantService.name);
|
||||||
private readonly defaultModel = process.env.OPENAI_MODEL || 'gpt-5.4-mini';
|
private readonly defaultModel = process.env.OPENAI_MODEL || 'gpt-4o';
|
||||||
private readonly conversationState = new Map<
|
private readonly conversationState = new Map<
|
||||||
string,
|
string,
|
||||||
{ fields: Record<string, any>; updatedAt: number }
|
{ fields: Record<string, any>; updatedAt: number }
|
||||||
@@ -688,8 +688,6 @@ export class AiAssistantService {
|
|||||||
totalCount: meiliResults.total ?? records.totalCount ?? 0,
|
totalCount: meiliResults.total ?? records.totalCount ?? 0,
|
||||||
strategy: plan.strategy,
|
strategy: plan.strategy,
|
||||||
explanation: plan.explanation,
|
explanation: plan.explanation,
|
||||||
filters: [],
|
|
||||||
sort: null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -704,28 +702,16 @@ export class AiAssistantService {
|
|||||||
...fallback,
|
...fallback,
|
||||||
strategy: plan.strategy,
|
strategy: plan.strategy,
|
||||||
explanation: plan.explanation,
|
explanation: plan.explanation,
|
||||||
filters: [],
|
|
||||||
sort: null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('AI search plan (query):', plan);
|
console.log('AI search plan (query):', plan);
|
||||||
|
|
||||||
// Resolve any LOOKUP filter values (user typed a name, we find the related record ID)
|
|
||||||
const resolvedFilters = await this.resolveRelatedFilters(
|
|
||||||
resolvedTenantId,
|
|
||||||
userId,
|
|
||||||
objectDefinition,
|
|
||||||
plan.filters || [],
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log('Resolved filters for query strategy:', resolvedFilters);
|
|
||||||
|
|
||||||
const filtered = await this.objectService.searchRecordsWithFilters(
|
const filtered = await this.objectService.searchRecordsWithFilters(
|
||||||
resolvedTenantId,
|
resolvedTenantId,
|
||||||
payload.objectApiName,
|
payload.objectApiName,
|
||||||
userId,
|
userId,
|
||||||
resolvedFilters,
|
plan.filters || [],
|
||||||
{ page, pageSize },
|
{ page, pageSize },
|
||||||
plan.sort || undefined,
|
plan.sort || undefined,
|
||||||
);
|
);
|
||||||
@@ -734,53 +720,9 @@ export class AiAssistantService {
|
|||||||
...filtered,
|
...filtered,
|
||||||
strategy: plan.strategy,
|
strategy: plan.strategy,
|
||||||
explanation: plan.explanation,
|
explanation: plan.explanation,
|
||||||
filters: resolvedFilters,
|
|
||||||
sort: plan.sort || null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Asks the LLM to suggest a short, human-friendly name for a saved list view
|
|
||||||
* based on the resolved filters / explanation.
|
|
||||||
*/
|
|
||||||
async suggestViewName(
|
|
||||||
tenantId: string,
|
|
||||||
payload: { objectLabel: string; filters: AiSearchFilter[]; explanation?: string },
|
|
||||||
): Promise<{ suggestedName: string }> {
|
|
||||||
const openAiConfig = await this.getOpenAiConfig(tenantId);
|
|
||||||
if (!openAiConfig) {
|
|
||||||
return { suggestedName: `${payload.objectLabel} View` };
|
|
||||||
}
|
|
||||||
|
|
||||||
const model = new ChatOpenAI({
|
|
||||||
apiKey: openAiConfig.apiKey,
|
|
||||||
model: this.normalizeChatModel(openAiConfig.model),
|
|
||||||
temperature: 0.4,
|
|
||||||
});
|
|
||||||
|
|
||||||
const filterSummary = payload.explanation?.trim()
|
|
||||||
|| payload.filters.map(f => `${f.field} ${f.operator} ${f.value ?? ''}`).join(', ')
|
|
||||||
|| 'no filters';
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await model.invoke([
|
|
||||||
new SystemMessage(
|
|
||||||
'You are a CRM assistant. Suggest a very short (2–5 words), descriptive, and human-friendly name for a saved list view. ' +
|
|
||||||
'Reply with ONLY the name, no quotes or punctuation.',
|
|
||||||
),
|
|
||||||
new HumanMessage(
|
|
||||||
`Object: ${payload.objectLabel}.\nFilter summary: ${filterSummary}`,
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const raw = typeof response.content === 'string' ? response.content.trim() : '';
|
|
||||||
const suggestedName = raw || `${payload.objectLabel} View`;
|
|
||||||
return { suggestedName };
|
|
||||||
} catch {
|
|
||||||
return { suggestedName: `${payload.objectLabel} View` };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================
|
// ============================================
|
||||||
// Planning-Based LangGraph Workflow
|
// Planning-Based LangGraph Workflow
|
||||||
// ============================================
|
// ============================================
|
||||||
@@ -2265,59 +2207,6 @@ export class AiAssistantService {
|
|||||||
return extracted;
|
return extracted;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves LOOKUP filter values from human-readable names to actual record IDs.
|
|
||||||
* When the AI produces a filter like { field: "familyId", operator: "eq", value: "Gaona Family" },
|
|
||||||
* this method looks up "Gaona Family" in the referenced object and replaces the value with its ID.
|
|
||||||
*/
|
|
||||||
private async resolveRelatedFilters(
|
|
||||||
tenantId: string,
|
|
||||||
userId: string,
|
|
||||||
objectDefinition: any,
|
|
||||||
filters: AiSearchFilter[],
|
|
||||||
): Promise<AiSearchFilter[]> {
|
|
||||||
if (!filters || filters.length === 0) return filters;
|
|
||||||
|
|
||||||
const lookupFieldMap = new Map<string, string>(); // apiName → referenceObject
|
|
||||||
for (const field of objectDefinition.fields || []) {
|
|
||||||
if (field.type === 'LOOKUP' && field.referenceObject) {
|
|
||||||
lookupFieldMap.set(field.apiName, field.referenceObject);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolved: AiSearchFilter[] = [];
|
|
||||||
for (const filter of filters) {
|
|
||||||
const referenceObject = lookupFieldMap.get(filter.field);
|
|
||||||
if (
|
|
||||||
referenceObject &&
|
|
||||||
filter.value &&
|
|
||||||
typeof filter.value === 'string' &&
|
|
||||||
!this.isUuid(filter.value)
|
|
||||||
) {
|
|
||||||
// Try to resolve the name to an ID in the referenced object
|
|
||||||
try {
|
|
||||||
console.log(`Resolving LOOKUP filter: ${filter.field} → searching "${filter.value}" in ${referenceObject}`);
|
|
||||||
const relatedRecord = await this.searchForExistingRecord(tenantId, userId, referenceObject, filter.value);
|
|
||||||
if (relatedRecord?.id) {
|
|
||||||
console.log(`Resolved "${filter.value}" → ID: ${relatedRecord.id}`);
|
|
||||||
resolved.push({ ...filter, operator: 'eq', value: relatedRecord.id });
|
|
||||||
} else {
|
|
||||||
// Could not resolve; keep as-is so we get 0 results rather than wrong ones
|
|
||||||
console.warn(`Could not resolve related record "${filter.value}" in ${referenceObject}; keeping original filter`);
|
|
||||||
resolved.push(filter);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.warn(`Failed to resolve lookup filter for ${filter.field}: ${err.message}`);
|
|
||||||
resolved.push(filter);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
resolved.push(filter);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async buildSearchPlan(
|
private async buildSearchPlan(
|
||||||
tenantId: string,
|
tenantId: string,
|
||||||
message: string,
|
message: string,
|
||||||
@@ -2361,65 +2250,25 @@ export class AiAssistantService {
|
|||||||
apiName: field.apiName,
|
apiName: field.apiName,
|
||||||
label: field.label,
|
label: field.label,
|
||||||
type: field.type,
|
type: field.type,
|
||||||
...(field.referenceObject ? { referenceObject: field.referenceObject } : {}),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const formatInstructions = parser.getFormatInstructions();
|
const formatInstructions = parser.getFormatInstructions();
|
||||||
const today = new Date().toISOString();
|
const today = new Date().toISOString();
|
||||||
|
|
||||||
const systemPromptLines = [
|
|
||||||
`You are a CRM search assistant. The user is browsing a list of "${objectDefinition.label || objectDefinition.apiName}" records.`,
|
|
||||||
``,
|
|
||||||
`Your task: decide whether the user input is a KEYWORD search or a STRUCTURED QUERY, then return the correct JSON plan.`,
|
|
||||||
``,
|
|
||||||
`=== STRATEGY DECISION RULES ===`,
|
|
||||||
`Use strategy="query" when the user:`,
|
|
||||||
` - Describes a record attribute or property value (e.g. "list all golden retrievers" → filter the race field)`,
|
|
||||||
` - Uses phrases like "list all X", "show all X", "find all X", "filter by X", "where X is Y"`,
|
|
||||||
` - Mentions a specific field value, status, category, type, breed, color, size, or any distinguishing characteristic`,
|
|
||||||
` - Requests records matching a condition (e.g. "created this week", "price > 100", "active only")`,
|
|
||||||
` - Asks for sorted or ordered results (e.g. "newest first", "alphabetically")`,
|
|
||||||
``,
|
|
||||||
`Use strategy="keyword" ONLY when the user types a bare search term with no clear field or attribute intent`,
|
|
||||||
` - e.g. a lone name or identifier: "rex", "john", "acme corp"`,
|
|
||||||
``,
|
|
||||||
`=== HOW TO MAP USER LANGUAGE TO FIELDS ===`,
|
|
||||||
`When the user describes a characteristic or property value, find the best-matching field from the Fields list`,
|
|
||||||
`and apply a "contains" filter (or "eq" for exact values). Do NOT fall back to keyword just because the`,
|
|
||||||
`field name is not explicitly mentioned — infer the intent from context.`,
|
|
||||||
``,
|
|
||||||
`EXAMPLES (Object = Dog, fields include: name, race, size, color, createdAt, familyId[LOOKUP→Family]):`,
|
|
||||||
` "list all cocker spaniels" → strategy=query, filter: race contains "cocker spaniel"`,
|
|
||||||
` "show golden retrievers" → strategy=query, filter: race contains "golden retriever"`,
|
|
||||||
` "large dogs" → strategy=query, filter: size contains "large"`,
|
|
||||||
` "dogs added this week" → strategy=query, filter: createdAt between <monday> <today>`,
|
|
||||||
` "dogs belonging to Gaona Family" → strategy=query, filter: familyId eq "Gaona Family"`,
|
|
||||||
` "rex" → strategy=keyword, keyword="rex"`,
|
|
||||||
``,
|
|
||||||
`=== LOOKUP FIELDS ===`,
|
|
||||||
`Fields with type LOOKUP store a reference (ID) to another object (referenceObject).`,
|
|
||||||
`When the user refers to a related record by its name (e.g. "belonging to Gaona Family"),`,
|
|
||||||
`output the human-readable name as the filter value — the system will resolve it to the correct ID.`,
|
|
||||||
`Use the LOOKUP field apiName (e.g. familyId) as the filter field.`,
|
|
||||||
``,
|
|
||||||
`=== OUTPUT FORMAT ===`,
|
|
||||||
`Return a JSON object with these keys:`,
|
|
||||||
` strategy : "keyword" or "query"`,
|
|
||||||
` explanation : short plain-language description of what the search does`,
|
|
||||||
` keyword : the search term when strategy is "keyword", otherwise null`,
|
|
||||||
` filters : array of filter objects for strategy="query" (empty array otherwise)`,
|
|
||||||
` sort : {field, direction} when sorting is requested, otherwise null`,
|
|
||||||
``,
|
|
||||||
`Each filter object: { field: <apiName>, operator: <op>, value?, values?, from?, to? }`,
|
|
||||||
`Valid operators: eq | neq | gt | gte | lt | lte | contains | startsWith | endsWith | in | notIn | isNull | notNull | between`,
|
|
||||||
`Use "between" with {from, to} for date ranges.`,
|
|
||||||
`Only use field apiName values exactly as they appear in the Fields list provided.`,
|
|
||||||
``,
|
|
||||||
formatInstructions,
|
|
||||||
].join('\n');
|
|
||||||
|
|
||||||
const response = await model.invoke([
|
const response = await model.invoke([
|
||||||
new SystemMessage(systemPromptLines),
|
new SystemMessage(
|
||||||
|
`You are a CRM search assistant. Decide whether the user input is a keyword search or a structured query.` +
|
||||||
|
`\nReturn a JSON object with keys: strategy, explanation, keyword, filters, sort.` +
|
||||||
|
`\n- strategy must be "keyword" or "query".` +
|
||||||
|
`\n- explanation must be a short sentence explaining the approach.` +
|
||||||
|
`\n- keyword should be the search term when strategy is "keyword", otherwise null.` +
|
||||||
|
`\n- filters is an array of {field, operator, value, values, from, to}.` +
|
||||||
|
`\n- operators must be one of eq, neq, gt, gte, lt, lte, contains, startsWith, endsWith, in, notIn, isNull, notNull, between.` +
|
||||||
|
`\n- Use between with from/to when the user gives date ranges like "yesterday" or "last week".` +
|
||||||
|
`\n- sort should be {field, direction} when sorting is requested.` +
|
||||||
|
`\n- Only use field apiName values exactly as provided.` +
|
||||||
|
`\n${formatInstructions}`,
|
||||||
|
),
|
||||||
new HumanMessage(
|
new HumanMessage(
|
||||||
`Object: ${objectDefinition.label || objectDefinition.apiName}.\n` +
|
`Object: ${objectDefinition.label || objectDefinition.apiName}.\n` +
|
||||||
`Fields: ${JSON.stringify(fields)}.\n` +
|
`Fields: ${JSON.stringify(fields)}.\n` +
|
||||||
@@ -2430,30 +2279,10 @@ export class AiAssistantService {
|
|||||||
|
|
||||||
const content = typeof response.content === 'string' ? response.content : '{}';
|
const content = typeof response.content === 'string' ? response.content : '{}';
|
||||||
const parsed = await parser.parse(content);
|
const parsed = await parser.parse(content);
|
||||||
const normalizedPlan = this.normalizeSearchPlan(parsed, message, objectDefinition);
|
return this.normalizeSearchPlan(parsed, message);
|
||||||
|
|
||||||
console.log('AI search plan:', normalizedPlan);
|
|
||||||
|
|
||||||
if (normalizedPlan.strategy === 'query') {
|
|
||||||
const aiExplanation = await this.generateQueryExplanationWithAi(
|
|
||||||
model,
|
|
||||||
message,
|
|
||||||
objectDefinition,
|
|
||||||
normalizedPlan,
|
|
||||||
);
|
|
||||||
if (aiExplanation) {
|
|
||||||
normalizedPlan.explanation = aiExplanation;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return normalizedPlan;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeSearchPlan(
|
private normalizeSearchPlan(plan: AiSearchPlan, message: string): AiSearchPlan {
|
||||||
plan: AiSearchPlan,
|
|
||||||
message: string,
|
|
||||||
objectDefinition?: any,
|
|
||||||
): AiSearchPlan {
|
|
||||||
if (!plan || typeof plan !== 'object') {
|
if (!plan || typeof plan !== 'object') {
|
||||||
return this.buildSearchPlanFallback(message);
|
return this.buildSearchPlanFallback(message);
|
||||||
}
|
}
|
||||||
@@ -2473,158 +2302,15 @@ export class AiAssistantService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryExplanation = this.buildQueryExplanation(
|
|
||||||
message,
|
|
||||||
objectDefinition,
|
|
||||||
Array.isArray(plan.filters) ? plan.filters : [],
|
|
||||||
plan.sort || null,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
strategy,
|
strategy,
|
||||||
explanation: queryExplanation || explanation,
|
explanation,
|
||||||
keyword: null,
|
keyword: null,
|
||||||
filters: Array.isArray(plan.filters) ? plan.filters : [],
|
filters: Array.isArray(plan.filters) ? plan.filters : [],
|
||||||
sort: plan.sort || null,
|
sort: plan.sort || null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildQueryExplanation(
|
|
||||||
message: string,
|
|
||||||
objectDefinition: any,
|
|
||||||
filters: AiSearchFilter[],
|
|
||||||
sort: { field: string; direction: 'asc' | 'desc' } | null,
|
|
||||||
): string {
|
|
||||||
const fieldLabelByApiName = new Map<string, string>(
|
|
||||||
(objectDefinition?.fields || []).map((field: any) => [field.apiName, field.label || field.apiName]),
|
|
||||||
);
|
|
||||||
const objectLabel = objectDefinition?.label || objectDefinition?.apiName || 'records';
|
|
||||||
|
|
||||||
const filterParts = filters
|
|
||||||
.map((filter) => this.describeFilter(filter, fieldLabelByApiName))
|
|
||||||
.filter(Boolean) as string[];
|
|
||||||
|
|
||||||
const sortLabel = sort?.field
|
|
||||||
? fieldLabelByApiName.get(sort.field) || sort.field
|
|
||||||
: null;
|
|
||||||
const sortPart =
|
|
||||||
sortLabel && sort?.direction
|
|
||||||
? `sorted by ${sortLabel} (${sort.direction === 'desc' ? 'newest/highest first' : 'oldest/lowest first'})`
|
|
||||||
: '';
|
|
||||||
|
|
||||||
if (filterParts.length > 0 && sortPart) {
|
|
||||||
return `Showing ${objectLabel} where ${filterParts.join(' and ')}, ${sortPart}.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filterParts.length > 0) {
|
|
||||||
return `Showing ${objectLabel} where ${filterParts.join(' and ')}.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sortPart) {
|
|
||||||
return `Showing ${objectLabel} ${sortPart}.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `Applied filters based on: "${message.trim()}".`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private describeFilter(filter: AiSearchFilter, fieldLabelByApiName: Map<string, string>): string {
|
|
||||||
const fieldLabel = fieldLabelByApiName.get(filter.field) || filter.field;
|
|
||||||
const formatValue = (value: any) =>
|
|
||||||
value === null || value === undefined || value === ''
|
|
||||||
? 'empty'
|
|
||||||
: typeof value === 'string'
|
|
||||||
? `"${value}"`
|
|
||||||
: String(value);
|
|
||||||
|
|
||||||
switch (filter.operator) {
|
|
||||||
case 'eq':
|
|
||||||
return `${fieldLabel} is ${formatValue(filter.value)}`;
|
|
||||||
case 'neq':
|
|
||||||
return `${fieldLabel} is not ${formatValue(filter.value)}`;
|
|
||||||
case 'gt':
|
|
||||||
return `${fieldLabel} is greater than ${formatValue(filter.value)}`;
|
|
||||||
case 'gte':
|
|
||||||
return `${fieldLabel} is at least ${formatValue(filter.value)}`;
|
|
||||||
case 'lt':
|
|
||||||
return `${fieldLabel} is less than ${formatValue(filter.value)}`;
|
|
||||||
case 'lte':
|
|
||||||
return `${fieldLabel} is at most ${formatValue(filter.value)}`;
|
|
||||||
case 'contains':
|
|
||||||
return `${fieldLabel} contains ${formatValue(filter.value)}`;
|
|
||||||
case 'startsWith':
|
|
||||||
return `${fieldLabel} starts with ${formatValue(filter.value)}`;
|
|
||||||
case 'endsWith':
|
|
||||||
return `${fieldLabel} ends with ${formatValue(filter.value)}`;
|
|
||||||
case 'in':
|
|
||||||
return `${fieldLabel} is one of ${(filter.values || []).map(formatValue).join(', ')}`;
|
|
||||||
case 'notIn':
|
|
||||||
return `${fieldLabel} is not one of ${(filter.values || []).map(formatValue).join(', ')}`;
|
|
||||||
case 'isNull':
|
|
||||||
return `${fieldLabel} is empty`;
|
|
||||||
case 'notNull':
|
|
||||||
return `${fieldLabel} is not empty`;
|
|
||||||
case 'between':
|
|
||||||
if (filter.from && filter.to) {
|
|
||||||
return `${fieldLabel} is between ${formatValue(filter.from)} and ${formatValue(filter.to)}`;
|
|
||||||
}
|
|
||||||
if (filter.from) {
|
|
||||||
return `${fieldLabel} is from ${formatValue(filter.from)} onward`;
|
|
||||||
}
|
|
||||||
if (filter.to) {
|
|
||||||
return `${fieldLabel} is up to ${formatValue(filter.to)}`;
|
|
||||||
}
|
|
||||||
return `${fieldLabel} uses a date range filter`;
|
|
||||||
default:
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async generateQueryExplanationWithAi(
|
|
||||||
model: ChatOpenAI,
|
|
||||||
message: string,
|
|
||||||
objectDefinition: any,
|
|
||||||
plan: AiSearchPlan,
|
|
||||||
): Promise<string | null> {
|
|
||||||
try {
|
|
||||||
const fields = (objectDefinition?.fields || []).map((field: any) => ({
|
|
||||||
apiName: field.apiName,
|
|
||||||
label: field.label || field.apiName,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const response = await model.invoke([
|
|
||||||
new SystemMessage(
|
|
||||||
`You explain CRM list query results in plain language for end users.` +
|
|
||||||
`\nWrite one short sentence (max 25 words).` +
|
|
||||||
`\nDescribe the resulting filters/sort in business language.` +
|
|
||||||
`\nDo NOT mention SQL, JSON, "strategy", "query mode", or AI decision process.` +
|
|
||||||
`\nIf values are present, mention the most important ones clearly.`,
|
|
||||||
),
|
|
||||||
new HumanMessage(
|
|
||||||
`Object: ${objectDefinition?.label || objectDefinition?.apiName || 'records'}\n` +
|
|
||||||
`User request: ${message}\n` +
|
|
||||||
`Available fields: ${JSON.stringify(fields)}\n` +
|
|
||||||
`Applied filters: ${JSON.stringify(plan.filters || [])}\n` +
|
|
||||||
`Applied sort: ${JSON.stringify(plan.sort || null)}\n` +
|
|
||||||
`Current explanation draft: ${plan.explanation}`,
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const content = Array.isArray(response.content)
|
|
||||||
? response.content
|
|
||||||
.map((part: any) => (typeof part === 'string' ? part : part?.text || ''))
|
|
||||||
.join(' ')
|
|
||||||
: String(response.content || '');
|
|
||||||
const cleaned = content.trim().replace(/\s+/g, ' ');
|
|
||||||
|
|
||||||
console.log('AI-generated query explanation:', cleaned);
|
|
||||||
|
|
||||||
return cleaned || null;
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.warn(`AI query explanation refinement failed: ${error.message}`);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private sanitizeUserOwnerFields(
|
private sanitizeUserOwnerFields(
|
||||||
fields: Record<string, any>,
|
fields: Record<string, any>,
|
||||||
fieldDefinitions: any[],
|
fieldDefinitions: any[],
|
||||||
|
|||||||
@@ -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({
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { AppBuilderModule } from './app-builder/app-builder.module';
|
|||||||
import { PageLayoutModule } from './page-layout/page-layout.module';
|
import { PageLayoutModule } from './page-layout/page-layout.module';
|
||||||
import { VoiceModule } from './voice/voice.module';
|
import { VoiceModule } from './voice/voice.module';
|
||||||
import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
|
import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
|
||||||
import { SavedListViewModule } from './saved-list-view/saved-list-view.module';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -25,7 +24,6 @@ import { SavedListViewModule } from './saved-list-view/saved-list-view.module';
|
|||||||
PageLayoutModule,
|
PageLayoutModule,
|
||||||
VoiceModule,
|
VoiceModule,
|
||||||
AiAssistantModule,
|
AiAssistantModule,
|
||||||
SavedListViewModule,
|
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,8 +29,8 @@ 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 })
|
||||||
.first();
|
.first();
|
||||||
@@ -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);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { BaseModel } from './base.model';
|
import { BaseModel } from './base.model';
|
||||||
import { ModelOptions, QueryContext } from 'objection';
|
|
||||||
|
|
||||||
export class User extends BaseModel {
|
export class User extends BaseModel {
|
||||||
static tableName = 'users';
|
static tableName = 'users';
|
||||||
@@ -9,8 +8,6 @@ export class User extends BaseModel {
|
|||||||
password: string;
|
password: string;
|
||||||
firstName?: string;
|
firstName?: string;
|
||||||
lastName?: string;
|
lastName?: string;
|
||||||
alias?: string;
|
|
||||||
name?: string;
|
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
@@ -25,37 +22,11 @@ export class User extends BaseModel {
|
|||||||
password: { type: 'string' },
|
password: { type: 'string' },
|
||||||
firstName: { type: 'string' },
|
firstName: { type: 'string' },
|
||||||
lastName: { type: 'string' },
|
lastName: { type: 'string' },
|
||||||
alias: { type: 'string' },
|
|
||||||
name: { type: 'string' },
|
|
||||||
isActive: { type: 'boolean' },
|
isActive: { type: 'boolean' },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Compute the `name` column before insert/update so lookup fields
|
|
||||||
* referencing User.name always have a value.
|
|
||||||
*/
|
|
||||||
private computeName() {
|
|
||||||
if (this.alias) {
|
|
||||||
this.name = this.alias;
|
|
||||||
} else if (this.firstName || this.lastName) {
|
|
||||||
this.name = [this.firstName, this.lastName].filter(Boolean).join(' ');
|
|
||||||
} else if (this.email) {
|
|
||||||
this.name = this.email;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$beforeInsert(queryContext: QueryContext) {
|
|
||||||
super.$beforeInsert(queryContext);
|
|
||||||
this.computeName();
|
|
||||||
}
|
|
||||||
|
|
||||||
$beforeUpdate(opt: ModelOptions, queryContext: QueryContext) {
|
|
||||||
super.$beforeUpdate(opt, queryContext);
|
|
||||||
this.computeName();
|
|
||||||
}
|
|
||||||
|
|
||||||
static get relationMappings() {
|
static get relationMappings() {
|
||||||
const { UserRole } = require('./user-role.model');
|
const { UserRole } = require('./user-role.model');
|
||||||
const { Role } = require('./role.model');
|
const { Role } = require('./role.model');
|
||||||
|
|||||||
@@ -152,7 +152,6 @@ export class FieldMapperService {
|
|||||||
'phone': 'text',
|
'phone': 'text',
|
||||||
'picklist': 'select',
|
'picklist': 'select',
|
||||||
'multipicklist': 'multiSelect',
|
'multipicklist': 'multiSelect',
|
||||||
'multi_picklist': 'multiSelect',
|
|
||||||
'lookup': 'belongsTo',
|
'lookup': 'belongsTo',
|
||||||
'master-detail': 'belongsTo',
|
'master-detail': 'belongsTo',
|
||||||
'currency': 'currency',
|
'currency': 'currency',
|
||||||
|
|||||||
@@ -336,27 +336,13 @@ export class ObjectService {
|
|||||||
updated_at: knex.fn.now(),
|
updated_at: knex.fn.now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Build UI metadata from all sources
|
// Store relationDisplayField in UI metadata if provided
|
||||||
const uiMetadataObj: any = {};
|
if (data.relationDisplayField || data.relationObjects || data.relationTypeField) {
|
||||||
|
fieldData.ui_metadata = JSON.stringify({
|
||||||
// Merge general uiMetadata (options, placeholder, helpText, etc.)
|
relationDisplayField: data.relationDisplayField,
|
||||||
if (data.uiMetadata && typeof data.uiMetadata === 'object') {
|
relationObjects: data.relationObjects,
|
||||||
Object.assign(uiMetadataObj, data.uiMetadata);
|
relationTypeField: data.relationTypeField,
|
||||||
}
|
});
|
||||||
|
|
||||||
// Store relation-specific fields in UI metadata if provided
|
|
||||||
if (data.relationDisplayField) {
|
|
||||||
uiMetadataObj.relationDisplayField = data.relationDisplayField;
|
|
||||||
}
|
|
||||||
if (data.relationObjects) {
|
|
||||||
uiMetadataObj.relationObjects = data.relationObjects;
|
|
||||||
}
|
|
||||||
if (data.relationTypeField) {
|
|
||||||
uiMetadataObj.relationTypeField = data.relationTypeField;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(uiMetadataObj).length > 0) {
|
|
||||||
fieldData.ui_metadata = JSON.stringify(uiMetadataObj);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await knex('field_definitions').insert(fieldData);
|
await knex('field_definitions').insert(fieldData);
|
||||||
|
|||||||
@@ -111,33 +111,4 @@ export class RuntimeObjectController {
|
|||||||
user.userId,
|
user.userId,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Direct filter-based search — used when applying a saved list view.
|
|
||||||
* Bypasses the AI planning step; accepts pre-resolved structured filters.
|
|
||||||
*/
|
|
||||||
@Post(':objectApiName/records/search')
|
|
||||||
async searchRecords(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@Param('objectApiName') objectApiName: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Body() body: {
|
|
||||||
filters?: Array<{ field: string; operator: string; value?: any; values?: any[]; from?: string; to?: string }>;
|
|
||||||
sort?: { field: string; direction: 'asc' | 'desc' } | null;
|
|
||||||
page?: number;
|
|
||||||
pageSize?: number;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
const page = Number.isFinite(Number(body?.page)) ? Number(body.page) : 1;
|
|
||||||
const pageSize = Number.isFinite(Number(body?.pageSize)) ? Number(body.pageSize) : 25;
|
|
||||||
|
|
||||||
return this.objectService.searchRecordsWithFilters(
|
|
||||||
tenantId,
|
|
||||||
objectApiName,
|
|
||||||
user.userId,
|
|
||||||
body?.filters || [],
|
|
||||||
{ page, pageSize },
|
|
||||||
body?.sort || undefined,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ 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';
|
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 and layout type
|
||||||
@@ -32,7 +32,7 @@ export class PageLayoutService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findAll(tenantId: string, objectId?: string, layoutType?: PageLayoutType) {
|
async findAll(tenantId: string, objectId?: string, layoutType?: PageLayoutType) {
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
|
const knex = await this.tenantDbService.getTenantKnex(tenantId);
|
||||||
|
|
||||||
let query = knex('page_layouts');
|
let query = knex('page_layouts');
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ export class PageLayoutService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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();
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ export class PageLayoutService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findDefaultByObject(tenantId: string, objectId: string, layoutType: PageLayoutType = 'detail') {
|
async findDefaultByObject(tenantId: string, objectId: string, layoutType: PageLayoutType = 'detail') {
|
||||||
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, layout_type: layoutType })
|
||||||
@@ -71,7 +71,7 @@ export class PageLayoutService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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);
|
const layout = await this.findOne(tenantId, id);
|
||||||
@@ -112,7 +112,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);
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ export class SetupUsersController {
|
|||||||
@Post()
|
@Post()
|
||||||
async createUser(
|
async createUser(
|
||||||
@TenantId() tenantId: string,
|
@TenantId() tenantId: string,
|
||||||
@Body() data: { email: string; password: string; firstName?: string; lastName?: string; alias?: string },
|
@Body() data: { email: string; password: string; firstName?: string; lastName?: string },
|
||||||
) {
|
) {
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
||||||
@@ -52,7 +52,6 @@ export class SetupUsersController {
|
|||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
firstName: data.firstName,
|
firstName: data.firstName,
|
||||||
lastName: data.lastName,
|
lastName: data.lastName,
|
||||||
alias: data.alias,
|
|
||||||
isActive: true,
|
isActive: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -63,7 +62,7 @@ export class SetupUsersController {
|
|||||||
async updateUser(
|
async updateUser(
|
||||||
@TenantId() tenantId: string,
|
@TenantId() tenantId: string,
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() data: { email?: string; password?: string; firstName?: string; lastName?: string; alias?: string },
|
@Body() data: { email?: string; password?: string; firstName?: string; lastName?: string },
|
||||||
) {
|
) {
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
||||||
@@ -73,7 +72,6 @@ export class SetupUsersController {
|
|||||||
if (data.email) updateData.email = data.email;
|
if (data.email) updateData.email = data.email;
|
||||||
if (data.firstName !== undefined) updateData.firstName = data.firstName;
|
if (data.firstName !== undefined) updateData.firstName = data.firstName;
|
||||||
if (data.lastName !== undefined) updateData.lastName = data.lastName;
|
if (data.lastName !== undefined) updateData.lastName = data.lastName;
|
||||||
if (data.alias !== undefined) updateData.alias = data.alias;
|
|
||||||
|
|
||||||
// Hash password if provided
|
// Hash password if provided
|
||||||
if (data.password) {
|
if (data.password) {
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
import { IsString, IsNotEmpty, IsArray, IsOptional } from 'class-validator';
|
|
||||||
|
|
||||||
export class CreateSavedViewDto {
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
objectApiName: string;
|
|
||||||
|
|
||||||
@IsArray()
|
|
||||||
filters: Array<{
|
|
||||||
field: string;
|
|
||||||
operator: string;
|
|
||||||
value?: any;
|
|
||||||
values?: any[];
|
|
||||||
from?: string;
|
|
||||||
to?: string;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
sort?: { field: string; direction: 'asc' | 'desc' } | null;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
description?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class UpdateSavedViewDto {
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
name?: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsArray()
|
|
||||||
filters?: Array<{
|
|
||||||
field: string;
|
|
||||||
operator: string;
|
|
||||||
value?: any;
|
|
||||||
values?: any[];
|
|
||||||
from?: string;
|
|
||||||
to?: string;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
sort?: { field: string; direction: 'asc' | 'desc' } | null;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
description?: string;
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import {
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Post,
|
|
||||||
Patch,
|
|
||||||
Delete,
|
|
||||||
Body,
|
|
||||||
Param,
|
|
||||||
UseGuards,
|
|
||||||
ForbiddenException,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
|
||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
|
||||||
import { TenantId } from '../tenant/tenant.decorator';
|
|
||||||
import { SavedListViewService } from './saved-list-view.service';
|
|
||||||
import { CreateSavedViewDto, UpdateSavedViewDto } from './dto/saved-list-view.dto';
|
|
||||||
import { CreateRecordShareDto } from '../rbac/dto/create-record-share.dto';
|
|
||||||
|
|
||||||
@Controller('saved-views')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
export class SavedListViewController {
|
|
||||||
constructor(private readonly savedListViewService: SavedListViewService) {}
|
|
||||||
|
|
||||||
@Get(':objectApiName')
|
|
||||||
findByObject(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Param('objectApiName') objectApiName: string,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.findByObject(tenantId, user.userId, objectApiName);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
create(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Body() dto: CreateSavedViewDto,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.create(tenantId, user.userId, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id')
|
|
||||||
update(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Param('id') id: string,
|
|
||||||
@Body() dto: UpdateSavedViewDto,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.update(tenantId, user.userId, id, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete(':id')
|
|
||||||
remove(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Param('id') id: string,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.remove(tenantId, user.userId, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Sharing endpoints (reuse record_shares table) ────────────────────────
|
|
||||||
|
|
||||||
@Get(':id/shares')
|
|
||||||
getShares(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Param('id') id: string,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.getShares(tenantId, user.userId, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':id/shares')
|
|
||||||
createShare(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Param('id') id: string,
|
|
||||||
@Body() dto: CreateRecordShareDto,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.createShare(tenantId, user.userId, id, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete(':id/shares/:shareId')
|
|
||||||
removeShare(
|
|
||||||
@TenantId() tenantId: string,
|
|
||||||
@CurrentUser() user: any,
|
|
||||||
@Param('id') id: string,
|
|
||||||
@Param('shareId') shareId: string,
|
|
||||||
) {
|
|
||||||
return this.savedListViewService.removeShare(tenantId, user.userId, id, shareId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { SavedListViewService } from './saved-list-view.service';
|
|
||||||
import { SavedListViewController } from './saved-list-view.controller';
|
|
||||||
import { TenantModule } from '../tenant/tenant.module';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [TenantModule],
|
|
||||||
controllers: [SavedListViewController],
|
|
||||||
providers: [SavedListViewService],
|
|
||||||
exports: [SavedListViewService],
|
|
||||||
})
|
|
||||||
export class SavedListViewModule {}
|
|
||||||
@@ -1,264 +0,0 @@
|
|||||||
import { Injectable, NotFoundException, ForbiddenException, BadRequestException } from '@nestjs/common';
|
|
||||||
import { TenantDatabaseService } from '../tenant/tenant-database.service';
|
|
||||||
import { CreateSavedViewDto, UpdateSavedViewDto } from './dto/saved-list-view.dto';
|
|
||||||
import { RecordShare } from '../models/record-share.model';
|
|
||||||
import { ObjectDefinition } from '../models/object-definition.model';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class SavedListViewService {
|
|
||||||
constructor(private readonly tenantDbService: TenantDatabaseService) {}
|
|
||||||
|
|
||||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves the system object_definition ID for SavedListView.
|
|
||||||
* This is needed to create record_shares rows for saved views.
|
|
||||||
*/
|
|
||||||
private async getSavedViewObjectDefId(knex: any): Promise<string> {
|
|
||||||
const objectDef = await ObjectDefinition.query(knex)
|
|
||||||
.findOne({ apiName: 'SavedListView' });
|
|
||||||
if (!objectDef) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'SavedListView system object not found. Please run migrations.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return objectDef.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── CRUD ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns all saved views visible to the user for a given object:
|
|
||||||
* - Views owned by the user
|
|
||||||
* - Views shared with the user via record_shares
|
|
||||||
*/
|
|
||||||
async findByObject(tenantId: string, userId: string, objectApiName: string) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const objectDefId = await this.getSavedViewObjectDefId(knex);
|
|
||||||
|
|
||||||
// IDs of views shared with this user via record_shares
|
|
||||||
const sharedViewIds = await RecordShare.query(knex)
|
|
||||||
.where({ objectDefinitionId: objectDefId, granteeUserId: userId })
|
|
||||||
.whereNull('revokedAt')
|
|
||||||
.where(builder => {
|
|
||||||
builder.whereNull('expiresAt').orWhere('expiresAt', '>', new Date());
|
|
||||||
})
|
|
||||||
.select('recordId');
|
|
||||||
|
|
||||||
const sharedIds = sharedViewIds.map((s: any) => s.recordId);
|
|
||||||
|
|
||||||
const rows = await knex('saved_list_views')
|
|
||||||
.where({ object_api_name: objectApiName })
|
|
||||||
.andWhere(function () {
|
|
||||||
this.where({ user_id: userId });
|
|
||||||
if (sharedIds.length > 0) {
|
|
||||||
this.orWhereIn('id', sharedIds);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.orderBy('created_at', 'asc');
|
|
||||||
|
|
||||||
return rows.map((r: any) => this.deserialize(r, userId));
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(tenantId: string, userId: string, dto: CreateSavedViewDto) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const id = require('crypto').randomUUID();
|
|
||||||
|
|
||||||
await knex('saved_list_views').insert({
|
|
||||||
id,
|
|
||||||
name: dto.name,
|
|
||||||
object_api_name: dto.objectApiName,
|
|
||||||
user_id: userId,
|
|
||||||
is_shared: false,
|
|
||||||
strategy: 'query',
|
|
||||||
filters: JSON.stringify(dto.filters || []),
|
|
||||||
sort: dto.sort ? JSON.stringify(dto.sort) : null,
|
|
||||||
description: dto.description || null,
|
|
||||||
});
|
|
||||||
|
|
||||||
const row = await knex('saved_list_views').where({ id }).first();
|
|
||||||
return this.deserialize(row, userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(tenantId: string, userId: string, id: string, dto: UpdateSavedViewDto) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const existing = await knex('saved_list_views').where({ id }).first();
|
|
||||||
if (!existing) throw new NotFoundException(`Saved view ${id} not found`);
|
|
||||||
if (existing.user_id !== userId) {
|
|
||||||
throw new ForbiddenException('You can only modify views you own');
|
|
||||||
}
|
|
||||||
|
|
||||||
const updates: Record<string, any> = { updated_at: knex.fn.now() };
|
|
||||||
if (dto.name !== undefined) updates.name = dto.name;
|
|
||||||
if (dto.filters !== undefined) updates.filters = JSON.stringify(dto.filters);
|
|
||||||
if (dto.sort !== undefined) updates.sort = dto.sort ? JSON.stringify(dto.sort) : null;
|
|
||||||
if (dto.description !== undefined) updates.description = dto.description;
|
|
||||||
|
|
||||||
await knex('saved_list_views').where({ id }).update(updates);
|
|
||||||
|
|
||||||
const row = await knex('saved_list_views').where({ id }).first();
|
|
||||||
return this.deserialize(row, userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async remove(tenantId: string, userId: string, id: string) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const existing = await knex('saved_list_views').where({ id }).first();
|
|
||||||
if (!existing) throw new NotFoundException(`Saved view ${id} not found`);
|
|
||||||
if (existing.user_id !== userId) {
|
|
||||||
throw new ForbiddenException('You can only delete views you own');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also clean up any record_shares for this view
|
|
||||||
const objectDefId = await this.getSavedViewObjectDefId(knex);
|
|
||||||
await RecordShare.query(knex)
|
|
||||||
.where({ objectDefinitionId: objectDefId, recordId: id })
|
|
||||||
.delete();
|
|
||||||
|
|
||||||
await knex('saved_list_views').where({ id }).delete();
|
|
||||||
return { deleted: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Sharing via record_shares ────────────────────────────────────────────
|
|
||||||
|
|
||||||
async getShares(tenantId: string, userId: string, viewId: string) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const view = await knex('saved_list_views').where({ id: viewId }).first();
|
|
||||||
if (!view) throw new NotFoundException('Saved view not found');
|
|
||||||
if (view.user_id !== userId) {
|
|
||||||
throw new ForbiddenException('Only the view owner can manage sharing');
|
|
||||||
}
|
|
||||||
|
|
||||||
const objectDefId = await this.getSavedViewObjectDefId(knex);
|
|
||||||
|
|
||||||
const shares = await RecordShare.query(knex)
|
|
||||||
.where({ objectDefinitionId: objectDefId, recordId: viewId })
|
|
||||||
.whereNull('revokedAt')
|
|
||||||
.where(builder => {
|
|
||||||
builder.whereNull('expiresAt').orWhere('expiresAt', '>', new Date());
|
|
||||||
})
|
|
||||||
.withGraphFetched('[granteeUser]')
|
|
||||||
.orderBy('createdAt', 'desc');
|
|
||||||
|
|
||||||
return shares;
|
|
||||||
}
|
|
||||||
|
|
||||||
async createShare(
|
|
||||||
tenantId: string,
|
|
||||||
userId: string,
|
|
||||||
viewId: string,
|
|
||||||
dto: { granteeUserId: string; canRead: boolean; canEdit: boolean; canDelete: boolean; expiresAt?: string },
|
|
||||||
) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const view = await knex('saved_list_views').where({ id: viewId }).first();
|
|
||||||
if (!view) throw new NotFoundException('Saved view not found');
|
|
||||||
if (view.user_id !== userId) {
|
|
||||||
throw new ForbiddenException('Only the view owner can share it');
|
|
||||||
}
|
|
||||||
if (dto.granteeUserId === userId) {
|
|
||||||
throw new BadRequestException('Cannot share a view with yourself');
|
|
||||||
}
|
|
||||||
|
|
||||||
const objectDefId = await this.getSavedViewObjectDefId(knex);
|
|
||||||
|
|
||||||
// Upsert: if non-revoked share already exists for this grantee, update it
|
|
||||||
const existing = await RecordShare.query(knex)
|
|
||||||
.where({
|
|
||||||
objectDefinitionId: objectDefId,
|
|
||||||
recordId: viewId,
|
|
||||||
granteeUserId: dto.granteeUserId,
|
|
||||||
})
|
|
||||||
.whereNull('revokedAt')
|
|
||||||
.first();
|
|
||||||
|
|
||||||
if (existing) {
|
|
||||||
await RecordShare.query(knex)
|
|
||||||
.patchAndFetchById(existing.id, {
|
|
||||||
accessLevel: {
|
|
||||||
canRead: dto.canRead,
|
|
||||||
canEdit: dto.canEdit,
|
|
||||||
canDelete: dto.canDelete,
|
|
||||||
},
|
|
||||||
expiresAt: dto.expiresAt
|
|
||||||
? (knex.raw('?', [new Date(dto.expiresAt).toISOString().slice(0, 19).replace('T', ' ')]) as any)
|
|
||||||
: null,
|
|
||||||
} as any);
|
|
||||||
|
|
||||||
return RecordShare.query(knex)
|
|
||||||
.findById(existing.id)
|
|
||||||
.withGraphFetched('[granteeUser]');
|
|
||||||
}
|
|
||||||
|
|
||||||
const share = await RecordShare.query(knex).insertAndFetch({
|
|
||||||
objectDefinitionId: objectDefId,
|
|
||||||
recordId: viewId,
|
|
||||||
granteeUserId: dto.granteeUserId,
|
|
||||||
grantedByUserId: userId,
|
|
||||||
accessLevel: {
|
|
||||||
canRead: dto.canRead,
|
|
||||||
canEdit: dto.canEdit,
|
|
||||||
canDelete: dto.canDelete,
|
|
||||||
},
|
|
||||||
expiresAt: dto.expiresAt
|
|
||||||
? (knex.raw('?', [new Date(dto.expiresAt).toISOString().slice(0, 19).replace('T', ' ')]) as any)
|
|
||||||
: null,
|
|
||||||
} as any);
|
|
||||||
|
|
||||||
return RecordShare.query(knex)
|
|
||||||
.findById(share.id)
|
|
||||||
.withGraphFetched('[granteeUser]');
|
|
||||||
}
|
|
||||||
|
|
||||||
async removeShare(tenantId: string, userId: string, viewId: string, shareId: string) {
|
|
||||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
|
||||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
|
||||||
|
|
||||||
const view = await knex('saved_list_views').where({ id: viewId }).first();
|
|
||||||
if (!view) throw new NotFoundException('Saved view not found');
|
|
||||||
if (view.user_id !== userId) {
|
|
||||||
throw new ForbiddenException('Only the view owner can manage sharing');
|
|
||||||
}
|
|
||||||
|
|
||||||
const share = await RecordShare.query(knex).findById(shareId);
|
|
||||||
if (!share) throw new NotFoundException('Share not found');
|
|
||||||
|
|
||||||
// Soft-revoke
|
|
||||||
await RecordShare.query(knex)
|
|
||||||
.findById(shareId)
|
|
||||||
.patch({ revokedAt: knex.fn.now() } as any);
|
|
||||||
|
|
||||||
return { revoked: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Serialisation ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
private deserialize(row: any, currentUserId: string) {
|
|
||||||
return {
|
|
||||||
id: row.id,
|
|
||||||
name: row.name,
|
|
||||||
objectApiName: row.object_api_name,
|
|
||||||
userId: row.user_id,
|
|
||||||
isOwner: row.user_id === currentUserId,
|
|
||||||
isShared: Boolean(row.is_shared),
|
|
||||||
strategy: row.strategy,
|
|
||||||
filters: typeof row.filters === 'string' ? JSON.parse(row.filters) : (row.filters ?? []),
|
|
||||||
sort: row.sort
|
|
||||||
? (typeof row.sort === 'string' ? JSON.parse(row.sort) : row.sort)
|
|
||||||
: null,
|
|
||||||
description: row.description,
|
|
||||||
createdAt: row.created_at,
|
|
||||||
updatedAt: row.updated_at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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();
|
||||||
|
|
||||||
|
// Look up tenant by domain
|
||||||
|
const domainRecord = await centralPrisma.domain.findUnique({
|
||||||
|
where: { domain },
|
||||||
|
include: { tenant: { select: { id: true, integrationsConfig: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
if (!tenant || !tenant.integrationsConfig) {
|
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,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -14,61 +14,61 @@ 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
|
const host = req.headers.host || '';
|
||||||
let subdomain = req.headers['x-tenant-subdomain'] as string | null;
|
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 referer = req.headers.referer as string;
|
||||||
|
|
||||||
|
let parts = hostname.split('.');
|
||||||
|
|
||||||
|
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 tenantId = req.headers['x-tenant-id'] as string;
|
||||||
|
let subdomain: string | null = null;
|
||||||
|
|
||||||
if (subdomain) {
|
this.logger.log(`Host header: ${host}, hostname: ${hostname}, parts: ${JSON.stringify(parts)}, x-tenant-id: ${tenantId}`);
|
||||||
this.logger.log(`Using x-tenant-subdomain header: ${subdomain}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Priority 2: Fall back to extracting subdomain from Origin/Host headers
|
// Try to extract subdomain from Origin header first (for API calls from frontend)
|
||||||
// This supports direct backend access for development/testing
|
if (origin) {
|
||||||
if (!subdomain && !tenantId) {
|
try {
|
||||||
const host = req.headers.host || '';
|
const originUrl = new URL(origin);
|
||||||
const hostname = host.split(':')[0];
|
const originHost = originUrl.hostname;
|
||||||
const origin = req.headers.origin as string;
|
parts = originHost.split('.');
|
||||||
const referer = req.headers.referer as string;
|
this.logger.log(`Using Origin header hostname: ${originHost}, parts: ${JSON.stringify(parts)}`);
|
||||||
|
} catch (error) {
|
||||||
let parts = hostname.split('.');
|
this.logger.warn(`Failed to parse origin: ${origin}`);
|
||||||
|
|
||||||
this.logger.log(`Host header: ${host}, hostname: ${hostname}, origin: ${origin}, referer: ${referer}`);
|
|
||||||
|
|
||||||
// Try to extract subdomain from Origin header first (for API calls from frontend)
|
|
||||||
if (origin) {
|
|
||||||
try {
|
|
||||||
const originUrl = new URL(origin);
|
|
||||||
const originHost = originUrl.hostname;
|
|
||||||
parts = originHost.split('.');
|
|
||||||
this.logger.log(`Using Origin header hostname: ${originHost}, parts: ${JSON.stringify(parts)}`);
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.warn(`Failed to parse origin: ${origin}`);
|
|
||||||
}
|
|
||||||
} else if (referer) {
|
|
||||||
// Fallback to Referer if no Origin
|
|
||||||
try {
|
|
||||||
const refererUrl = new URL(referer);
|
|
||||||
const refererHost = refererUrl.hostname;
|
|
||||||
parts = refererHost.split('.');
|
|
||||||
this.logger.log(`Using Referer header hostname: ${refererHost}, parts: ${JSON.stringify(parts)}`);
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.warn(`Failed to parse referer: ${referer}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
} else if (referer && !tenantId) {
|
||||||
// Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co")
|
// Fallback to Referer if no Origin
|
||||||
if (parts.length >= 3) {
|
try {
|
||||||
subdomain = parts[0];
|
const refererUrl = new URL(referer);
|
||||||
if (subdomain === 'www') {
|
const refererHost = refererUrl.hostname;
|
||||||
subdomain = null;
|
parts = refererHost.split('.');
|
||||||
}
|
this.logger.log(`Using Referer header hostname: ${refererHost}, parts: ${JSON.stringify(parts)}`);
|
||||||
} else if (parts.length === 2 && parts[1] === 'localhost') {
|
} catch (error) {
|
||||||
subdomain = parts[0];
|
this.logger.warn(`Failed to parse referer: ${referer}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logger.log(`Extracted subdomain: ${subdomain}, x-tenant-id: ${tenantId}`);
|
// Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co")
|
||||||
|
// For production domains with 3+ parts, extract first part as subdomain
|
||||||
|
if (parts.length >= 3) {
|
||||||
|
subdomain = parts[0];
|
||||||
|
// Ignore www subdomain
|
||||||
|
if (subdomain === 'www') {
|
||||||
|
subdomain = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// For development (e.g., tenant1.localhost), also check 2 parts
|
||||||
|
else if (parts.length === 2 && parts[1] === 'localhost') {
|
||||||
|
subdomain = parts[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|||||||
@@ -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(':');
|
this.logger.log(`Extracted tenant domain: ${tenantDomain}`);
|
||||||
if (parts.length >= 2) {
|
|
||||||
tenantId = parts[0]; // First part is tenantId
|
|
||||||
this.logger.log(`Extracted tenantId from client identity: ${tenantId}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tenantId) {
|
|
||||||
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) {
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 },
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
toast.success('Login successful!')
|
|
||||||
// Redirect to home
|
|
||||||
router.push('/')
|
|
||||||
} else {
|
|
||||||
error.value = result.error || 'Login failed'
|
|
||||||
toast.error(result.error || 'Login failed')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
toast.success('Login successful!')
|
||||||
|
|
||||||
|
// Redirect to home
|
||||||
|
router.push('/')
|
||||||
} 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">
|
||||||
|
|||||||
@@ -186,8 +186,6 @@ interface Props {
|
|||||||
objectApiName: string;
|
objectApiName: string;
|
||||||
recordId: string;
|
recordId: string;
|
||||||
ownerId?: string;
|
ownerId?: string;
|
||||||
/** Optional base URL override for shares API. Defaults to /runtime/objects/{objectApiName}/records/{recordId}/shares */
|
|
||||||
basePath?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = defineProps<Props>();
|
const props = defineProps<Props>();
|
||||||
@@ -195,11 +193,6 @@ const props = defineProps<Props>();
|
|||||||
const { api } = useApi();
|
const { api } = useApi();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
/** Computed base path for all share API calls */
|
|
||||||
const sharesBasePath = computed(() =>
|
|
||||||
props.basePath || `/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`
|
|
||||||
);
|
|
||||||
|
|
||||||
const loading = ref(true);
|
const loading = ref(true);
|
||||||
const sharing = ref(false);
|
const sharing = ref(false);
|
||||||
const removing = ref<string | null>(null);
|
const removing = ref<string | null>(null);
|
||||||
@@ -243,7 +236,9 @@ const loadShares = async () => {
|
|||||||
try {
|
try {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = null;
|
error.value = null;
|
||||||
const response = await api.get(sharesBasePath.value);
|
const response = await api.get(
|
||||||
|
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`
|
||||||
|
);
|
||||||
shares.value = response || [];
|
shares.value = response || [];
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error('Failed to load shares:', e);
|
console.error('Failed to load shares:', e);
|
||||||
@@ -291,7 +286,7 @@ const createShare = async () => {
|
|||||||
console.log('Final payload:', payload);
|
console.log('Final payload:', payload);
|
||||||
|
|
||||||
await api.post(
|
await api.post(
|
||||||
sharesBasePath.value,
|
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`,
|
||||||
payload
|
payload
|
||||||
);
|
);
|
||||||
toast.success('Record shared successfully');
|
toast.success('Record shared successfully');
|
||||||
@@ -318,7 +313,7 @@ const removeShare = async (shareId: string) => {
|
|||||||
try {
|
try {
|
||||||
removing.value = shareId;
|
removing.value = shareId;
|
||||||
await api.delete(
|
await api.delete(
|
||||||
`${sharesBasePath.value}/${shareId}`
|
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares/${shareId}`
|
||||||
);
|
);
|
||||||
toast.success('Share removed successfully');
|
toast.success('Share removed successfully');
|
||||||
await loadShares();
|
await loadShares();
|
||||||
|
|||||||
@@ -1,234 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { ref, computed, nextTick } from 'vue'
|
|
||||||
import {
|
|
||||||
Sheet,
|
|
||||||
SheetContent,
|
|
||||||
SheetHeader,
|
|
||||||
SheetTitle,
|
|
||||||
SheetDescription,
|
|
||||||
} from '@/components/ui/sheet'
|
|
||||||
import { Button } from '@/components/ui/button'
|
|
||||||
import { Input } from '@/components/ui/input'
|
|
||||||
import { Badge } from '@/components/ui/badge'
|
|
||||||
import { Separator } from '@/components/ui/separator'
|
|
||||||
import { Pencil, Trash2, Users, Check, X, ChevronLeft } from 'lucide-vue-next'
|
|
||||||
import type { SavedView, UpdateSavedViewPayload } from '@/composables/useSavedViews'
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
open: boolean
|
|
||||||
views: SavedView[]
|
|
||||||
objectLabel: string
|
|
||||||
activeViewId?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
const props = withDefaults(defineProps<Props>(), {
|
|
||||||
activeViewId: null,
|
|
||||||
})
|
|
||||||
|
|
||||||
const emit = defineEmits<{
|
|
||||||
'update:open': [value: boolean]
|
|
||||||
'apply-view': [view: SavedView]
|
|
||||||
'update-view': [id: string, payload: UpdateSavedViewPayload]
|
|
||||||
'delete-view': [view: SavedView]
|
|
||||||
}>()
|
|
||||||
|
|
||||||
const editingId = ref<string | null>(null)
|
|
||||||
const editName = ref('')
|
|
||||||
const deletingId = ref<string | null>(null)
|
|
||||||
|
|
||||||
// Sharing sub-view: when set, renders RecordSharing for this view
|
|
||||||
const sharingView = ref<SavedView | null>(null)
|
|
||||||
|
|
||||||
const ownViews = computed(() => props.views.filter(v => v.isOwner))
|
|
||||||
const sharedViews = computed(() => props.views.filter(v => !v.isOwner))
|
|
||||||
|
|
||||||
function startEdit(view: SavedView) {
|
|
||||||
editingId.value = view.id
|
|
||||||
editName.value = view.name
|
|
||||||
}
|
|
||||||
|
|
||||||
function cancelEdit() {
|
|
||||||
editingId.value = null
|
|
||||||
editName.value = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
function commitEdit(view: SavedView) {
|
|
||||||
const name = editName.value.trim()
|
|
||||||
if (name && name !== view.name) {
|
|
||||||
emit('update-view', view.id, { name })
|
|
||||||
}
|
|
||||||
cancelEdit()
|
|
||||||
}
|
|
||||||
|
|
||||||
function openSharing(view: SavedView) {
|
|
||||||
sharingView.value = view
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeSharing() {
|
|
||||||
sharingView.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
function confirmDelete(view: SavedView) {
|
|
||||||
deletingId.value = view.id
|
|
||||||
}
|
|
||||||
|
|
||||||
function cancelDelete() {
|
|
||||||
deletingId.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
function executeDelete(view: SavedView) {
|
|
||||||
emit('delete-view', view)
|
|
||||||
deletingId.value = null
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<Sheet :open="open" @update:open="emit('update:open', $event)">
|
|
||||||
<SheetContent class="w-[420px] sm:w-[520px] overflow-y-auto">
|
|
||||||
|
|
||||||
<!-- ─── Sharing sub-view ─── -->
|
|
||||||
<template v-if="sharingView">
|
|
||||||
<SheetHeader class="mb-4">
|
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<Button size="icon" variant="ghost" class="h-7 w-7 -ml-1" @click="closeSharing">
|
|
||||||
<ChevronLeft class="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<div>
|
|
||||||
<SheetTitle>Share "{{ sharingView.name }}"</SheetTitle>
|
|
||||||
<SheetDescription>
|
|
||||||
Grant access to specific users for this saved view.
|
|
||||||
</SheetDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</SheetHeader>
|
|
||||||
|
|
||||||
<RecordSharing
|
|
||||||
object-api-name="SavedListView"
|
|
||||||
:record-id="sharingView.id"
|
|
||||||
:owner-id="sharingView.userId"
|
|
||||||
:base-path="`/saved-views/${sharingView.id}/shares`"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- ─── Main view list ─── -->
|
|
||||||
<template v-else>
|
|
||||||
<SheetHeader class="mb-4">
|
|
||||||
<SheetTitle>{{ objectLabel }} — Saved Views</SheetTitle>
|
|
||||||
<SheetDescription>
|
|
||||||
Manage your saved searches. Share views with specific users from your workspace.
|
|
||||||
</SheetDescription>
|
|
||||||
</SheetHeader>
|
|
||||||
|
|
||||||
<!-- Own Views -->
|
|
||||||
<section>
|
|
||||||
<p class="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
|
|
||||||
My Views
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div v-if="ownViews.length === 0" class="text-sm text-muted-foreground py-3">
|
|
||||||
You have no saved views yet. Run a search and click <strong>Save view</strong>.
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ul class="space-y-1">
|
|
||||||
<li
|
|
||||||
v-for="view in ownViews"
|
|
||||||
:key="view.id"
|
|
||||||
class="group rounded-md border bg-card px-3 py-2"
|
|
||||||
>
|
|
||||||
<!-- Confirm delete row -->
|
|
||||||
<div v-if="deletingId === view.id" class="flex items-center gap-2">
|
|
||||||
<span class="flex-1 text-sm text-destructive">Delete "{{ view.name }}"?</span>
|
|
||||||
<Button size="sm" variant="destructive" @click="executeDelete(view)">Delete</Button>
|
|
||||||
<Button size="sm" variant="outline" @click="cancelDelete">Cancel</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Edit name row -->
|
|
||||||
<div v-else-if="editingId === view.id" class="flex items-center gap-2">
|
|
||||||
<Input
|
|
||||||
v-model="editName"
|
|
||||||
class="h-7 flex-1 text-sm"
|
|
||||||
@keyup.enter="commitEdit(view)"
|
|
||||||
@keyup.escape="cancelEdit"
|
|
||||||
autofocus
|
|
||||||
/>
|
|
||||||
<Button size="icon" variant="ghost" class="h-7 w-7" @click="commitEdit(view)">
|
|
||||||
<Check class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
<Button size="icon" variant="ghost" class="h-7 w-7" @click="cancelEdit">
|
|
||||||
<X class="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Normal row -->
|
|
||||||
<div v-else class="flex items-center gap-2 min-h-[28px]">
|
|
||||||
<!-- View name (click to apply) -->
|
|
||||||
<button
|
|
||||||
class="flex-1 text-left text-sm truncate hover:text-primary transition-colors"
|
|
||||||
:class="{ 'font-medium text-primary': activeViewId === view.id }"
|
|
||||||
@click="emit('apply-view', view); emit('update:open', false)"
|
|
||||||
>
|
|
||||||
{{ view.name }}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<!-- Actions (visible on hover) -->
|
|
||||||
<div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
|
||||||
<Button size="icon" variant="ghost" class="h-6 w-6" title="Rename" @click="startEdit(view)">
|
|
||||||
<Pencil class="h-3 w-3" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
class="h-6 w-6"
|
|
||||||
title="Share"
|
|
||||||
@click="openSharing(view)"
|
|
||||||
>
|
|
||||||
<Users class="h-3 w-3" />
|
|
||||||
</Button>
|
|
||||||
<Button size="icon" variant="ghost" class="h-6 w-6 text-destructive hover:text-destructive" title="Delete" @click="confirmDelete(view)">
|
|
||||||
<Trash2 class="h-3 w-3" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Description -->
|
|
||||||
<p
|
|
||||||
v-if="view.description && editingId !== view.id && deletingId !== view.id"
|
|
||||||
class="text-xs text-muted-foreground mt-1 truncate"
|
|
||||||
>
|
|
||||||
{{ view.description }}
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<!-- Shared views by others -->
|
|
||||||
<template v-if="sharedViews.length > 0">
|
|
||||||
<Separator class="my-4" />
|
|
||||||
<section>
|
|
||||||
<p class="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
|
|
||||||
Shared with me
|
|
||||||
</p>
|
|
||||||
<ul class="space-y-1">
|
|
||||||
<li
|
|
||||||
v-for="view in sharedViews"
|
|
||||||
:key="view.id"
|
|
||||||
class="rounded-md border bg-card px-3 py-2"
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class="w-full text-left text-sm truncate hover:text-primary transition-colors"
|
|
||||||
:class="{ 'font-medium text-primary': activeViewId === view.id }"
|
|
||||||
@click="emit('apply-view', view); emit('update:open', false)"
|
|
||||||
>
|
|
||||||
{{ view.name }}
|
|
||||||
</button>
|
|
||||||
<p v-if="view.description" class="text-xs text-muted-foreground mt-1 truncate">
|
|
||||||
{{ view.description }}
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
</template>
|
|
||||||
</SheetContent>
|
|
||||||
</Sheet>
|
|
||||||
</template>
|
|
||||||
@@ -249,51 +249,6 @@ const handleRelationTypeUpdate = (value: string | null) => {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
<!-- Multi-Select -->
|
|
||||||
<div v-else-if="field.type === FieldType.MULTI_SELECT" class="space-y-2">
|
|
||||||
<div class="flex flex-wrap gap-1 min-h-[36px] rounded-md border border-input bg-background px-3 py-2">
|
|
||||||
<Badge
|
|
||||||
v-for="selectedVal in (Array.isArray(value) ? value : [])"
|
|
||||||
:key="String(selectedVal)"
|
|
||||||
variant="secondary"
|
|
||||||
class="gap-1 cursor-pointer"
|
|
||||||
@click="value = (value || []).filter((v: any) => v !== selectedVal)"
|
|
||||||
>
|
|
||||||
{{ field.options?.find(o => o.value === selectedVal)?.label || selectedVal }}
|
|
||||||
<span class="text-xs ml-1">×</span>
|
|
||||||
</Badge>
|
|
||||||
<span v-if="!value || (Array.isArray(value) && value.length === 0)" class="text-sm text-muted-foreground">
|
|
||||||
{{ field.placeholder || 'Select options...' }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="space-y-1">
|
|
||||||
<div
|
|
||||||
v-for="option in field.options"
|
|
||||||
:key="String(option.value)"
|
|
||||||
class="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<Checkbox
|
|
||||||
:id="`${field.id}-${option.value}`"
|
|
||||||
:checked="Array.isArray(value) && value.includes(option.value)"
|
|
||||||
@update:checked="(checked: boolean) => {
|
|
||||||
const current = Array.isArray(value) ? [...value] : []
|
|
||||||
if (checked) {
|
|
||||||
current.push(option.value)
|
|
||||||
} else {
|
|
||||||
const idx = current.indexOf(option.value)
|
|
||||||
if (idx > -1) current.splice(idx, 1)
|
|
||||||
}
|
|
||||||
value = current
|
|
||||||
}"
|
|
||||||
:disabled="field.isReadOnly"
|
|
||||||
/>
|
|
||||||
<Label :for="`${field.id}-${option.value}`" class="text-sm font-normal cursor-pointer">
|
|
||||||
{{ option.label }}
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Boolean - Checkbox -->
|
<!-- Boolean - Checkbox -->
|
||||||
<div v-else-if="field.type === FieldType.BOOLEAN" class="flex items-center gap-2">
|
<div v-else-if="field.type === FieldType.BOOLEAN" class="flex items-center gap-2">
|
||||||
<Checkbox :id="field.id" v-model:checked="value" :disabled="field.isReadOnly" />
|
<Checkbox :id="field.id" v-model:checked="value" :disabled="field.isReadOnly" />
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { DropdownMenuSeparator, type DropdownMenuSeparatorProps, useForwardProps } from 'reka-ui'
|
|
||||||
import type { HTMLAttributes } from 'vue'
|
|
||||||
import { cn } from '@/lib/utils'
|
|
||||||
|
|
||||||
const props = defineProps<DropdownMenuSeparatorProps & { class?: HTMLAttributes['class'] }>()
|
|
||||||
|
|
||||||
const forwarded = useForwardProps(props)
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<DropdownMenuSeparator
|
|
||||||
v-bind="forwarded"
|
|
||||||
:class="cn('-mx-1 my-1 h-px bg-muted', props.class)"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
@@ -2,4 +2,3 @@ export { default as DropdownMenu } from './DropdownMenu.vue'
|
|||||||
export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue'
|
export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue'
|
||||||
export { default as DropdownMenuContent } from './DropdownMenuContent.vue'
|
export { default as DropdownMenuContent } from './DropdownMenuContent.vue'
|
||||||
export { default as DropdownMenuItem } from './DropdownMenuItem.vue'
|
export { default as DropdownMenuItem } from './DropdownMenuItem.vue'
|
||||||
export { default as DropdownMenuSeparator } from './DropdownMenuSeparator.vue'
|
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, watch } from 'vue'
|
import { ref, computed, watch } from 'vue'
|
||||||
import type { CellValueChangedEvent, ColDef, GridApi, GridReadyEvent } from 'ag-grid-community'
|
|
||||||
import { AgGridVue } from 'ag-grid-vue3'
|
|
||||||
import 'ag-grid-community/styles/ag-grid.css'
|
|
||||||
import 'ag-grid-community/styles/ag-theme-alpine.css'
|
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -17,17 +13,9 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
import {
|
|
||||||
DropdownMenu,
|
|
||||||
DropdownMenuContent,
|
|
||||||
DropdownMenuItem,
|
|
||||||
DropdownMenuSeparator,
|
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from '@/components/ui/dropdown-menu'
|
|
||||||
import FieldRenderer from '@/components/fields/FieldRenderer.vue'
|
import FieldRenderer from '@/components/fields/FieldRenderer.vue'
|
||||||
import { ListViewConfig, ViewMode, FieldType, FieldConfig } from '@/types/field-types'
|
import { ListViewConfig, ViewMode, FieldType } from '@/types/field-types'
|
||||||
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit, Bookmark, BookmarkPlus, Settings2 } from 'lucide-vue-next'
|
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit } from 'lucide-vue-next'
|
||||||
import type { SavedView } from '@/composables/useSavedViews'
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
config: ListViewConfig
|
config: ListViewConfig
|
||||||
@@ -37,14 +25,6 @@ interface Props {
|
|||||||
baseUrl?: string
|
baseUrl?: string
|
||||||
totalCount?: number
|
totalCount?: number
|
||||||
searchSummary?: string
|
searchSummary?: string
|
||||||
draftEdits?: Record<string, Record<string, any>>
|
|
||||||
cellErrors?: Record<string, Record<string, string | boolean>>
|
|
||||||
savingDrafts?: boolean
|
|
||||||
// Saved views
|
|
||||||
savedViews?: SavedView[]
|
|
||||||
activeViewId?: string | null
|
|
||||||
currentSearchPlan?: { strategy: string; filters: any[]; sort: any; explanation: string } | null
|
|
||||||
savingView?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = withDefaults(defineProps<Props>(), {
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
@@ -53,13 +33,6 @@ const props = withDefaults(defineProps<Props>(), {
|
|||||||
selectable: false,
|
selectable: false,
|
||||||
baseUrl: '/runtime/objects',
|
baseUrl: '/runtime/objects',
|
||||||
searchSummary: '',
|
searchSummary: '',
|
||||||
draftEdits: () => ({}),
|
|
||||||
cellErrors: () => ({}),
|
|
||||||
savingDrafts: false,
|
|
||||||
savedViews: () => [],
|
|
||||||
activeViewId: null,
|
|
||||||
currentSearchPlan: null,
|
|
||||||
savingView: false,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
@@ -74,14 +47,6 @@ const emit = defineEmits<{
|
|||||||
'refresh': []
|
'refresh': []
|
||||||
'page-change': [page: number, pageSize: number]
|
'page-change': [page: number, pageSize: number]
|
||||||
'load-more': [page: number, pageSize: number]
|
'load-more': [page: number, pageSize: number]
|
||||||
'view-change': [mode: 'list' | 'spreadsheet']
|
|
||||||
'cell-edit': [payload: { row: any; field: FieldConfig; newValue: any; oldValue: any }]
|
|
||||||
'save-drafts': []
|
|
||||||
'discard-drafts': []
|
|
||||||
// Saved views
|
|
||||||
'apply-view': [view: SavedView]
|
|
||||||
'save-view': []
|
|
||||||
'open-view-manager': []
|
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
// State
|
// State
|
||||||
@@ -92,8 +57,6 @@ const sortField = ref<string>('')
|
|||||||
const sortDirection = ref<'asc' | 'desc'>('asc')
|
const sortDirection = ref<'asc' | 'desc'>('asc')
|
||||||
const currentPage = ref(1)
|
const currentPage = ref(1)
|
||||||
const bulkAction = ref('delete')
|
const bulkAction = ref('delete')
|
||||||
const viewMode = ref<'list' | 'spreadsheet'>('list')
|
|
||||||
const gridApi = ref<GridApi | null>(null)
|
|
||||||
|
|
||||||
// Computed
|
// Computed
|
||||||
const visibleFields = computed(() =>
|
const visibleFields = computed(() =>
|
||||||
@@ -124,7 +87,7 @@ const paginatedData = computed(() => {
|
|||||||
})
|
})
|
||||||
const pageStart = computed(() => (props.data.length === 0 ? 0 : startIndex.value + 1))
|
const pageStart = computed(() => (props.data.length === 0 ? 0 : startIndex.value + 1))
|
||||||
const pageEnd = computed(() => Math.min(startIndex.value + paginatedData.value.length, totalRecords.value))
|
const pageEnd = computed(() => Math.min(startIndex.value + paginatedData.value.length, totalRecords.value))
|
||||||
const showPagination = computed(() => viewMode.value === 'list' && totalRecords.value > pageSize.value)
|
const showPagination = computed(() => totalRecords.value > pageSize.value)
|
||||||
const canGoPrev = computed(() => currentPage.value > 1)
|
const canGoPrev = computed(() => currentPage.value > 1)
|
||||||
const canGoNext = computed(() => currentPage.value < availablePages.value)
|
const canGoNext = computed(() => currentPage.value < availablePages.value)
|
||||||
const showLoadMore = computed(() => (
|
const showLoadMore = computed(() => (
|
||||||
@@ -132,8 +95,6 @@ const showLoadMore = computed(() => (
|
|||||||
Boolean(props.totalCount) &&
|
Boolean(props.totalCount) &&
|
||||||
props.data.length < totalRecords.value
|
props.data.length < totalRecords.value
|
||||||
))
|
))
|
||||||
const draftRowCount = computed(() => Object.keys(props.draftEdits).length)
|
|
||||||
const draftCellCount = computed(() => Object.values(props.draftEdits).reduce((sum, row) => sum + Object.keys(row).length, 0))
|
|
||||||
|
|
||||||
const allSelected = computed({
|
const allSelected = computed({
|
||||||
get: () => props.data.length > 0 && selectedRowIds.value.length === props.data.length,
|
get: () => props.data.length > 0 && selectedRowIds.value.length === props.data.length,
|
||||||
@@ -198,154 +159,6 @@ const handleBulkAction = () => {
|
|||||||
emit('action', bulkAction.value, getSelectedRows())
|
emit('action', bulkAction.value, getSelectedRows())
|
||||||
}
|
}
|
||||||
|
|
||||||
const isEditableField = (field: FieldConfig) =>
|
|
||||||
field.showOnEdit !== false &&
|
|
||||||
!field.isReadOnly &&
|
|
||||||
![FieldType.BELONGS_TO, FieldType.HAS_MANY, FieldType.MANY_TO_MANY].includes(field.type)
|
|
||||||
|
|
||||||
const getRelationPropertyName = (apiName: string) => apiName.replace(/Id$/, '').toLowerCase()
|
|
||||||
|
|
||||||
const formatFieldValue = (field: FieldConfig, value: any, record?: any) => {
|
|
||||||
if (value === null || value === undefined) return ''
|
|
||||||
switch (field.type) {
|
|
||||||
case FieldType.BELONGS_TO: {
|
|
||||||
const relationPropertyName = getRelationPropertyName(field.apiName)
|
|
||||||
const relatedObject = record?.[relationPropertyName]
|
|
||||||
if (relatedObject && typeof relatedObject === 'object') {
|
|
||||||
const displayField = field.relationDisplayField || 'name'
|
|
||||||
return relatedObject[displayField] || relatedObject.id || value
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
case FieldType.DATE: {
|
|
||||||
const date = value instanceof Date ? value : new Date(value)
|
|
||||||
return Number.isNaN(date.getTime())
|
|
||||||
? String(value)
|
|
||||||
: date.toLocaleDateString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' })
|
|
||||||
}
|
|
||||||
case FieldType.DATETIME: {
|
|
||||||
const date = value instanceof Date ? value : new Date(value)
|
|
||||||
return Number.isNaN(date.getTime())
|
|
||||||
? String(value)
|
|
||||||
: date.toLocaleString(undefined, {
|
|
||||||
year: 'numeric',
|
|
||||||
month: '2-digit',
|
|
||||||
day: '2-digit',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
second: '2-digit',
|
|
||||||
hour12: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
case FieldType.BOOLEAN:
|
|
||||||
return value ? 'Yes' : 'No'
|
|
||||||
case FieldType.CURRENCY:
|
|
||||||
return `${field.prefix || '$'}${Number(value).toFixed(2)}${field.suffix || ''}`
|
|
||||||
case FieldType.SELECT: {
|
|
||||||
const option = field.options?.find(opt => opt.value === value)
|
|
||||||
return option?.label || value
|
|
||||||
}
|
|
||||||
case FieldType.MULTI_SELECT:
|
|
||||||
return Array.isArray(value)
|
|
||||||
? value
|
|
||||||
.map(v => field.options?.find(opt => opt.value === v)?.label || v)
|
|
||||||
.join(', ')
|
|
||||||
: ''
|
|
||||||
default:
|
|
||||||
return String(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasOwnProperty = (target: Record<string, any> | undefined, key: string) =>
|
|
||||||
!!target && Object.prototype.hasOwnProperty.call(target, key)
|
|
||||||
|
|
||||||
const isDraftCell = (params: any) => {
|
|
||||||
const rowId = normalizeId(params?.data?.id)
|
|
||||||
const field = String(params?.colDef?.field || '')
|
|
||||||
return hasOwnProperty(props.draftEdits[rowId], field)
|
|
||||||
}
|
|
||||||
|
|
||||||
const isErrorCell = (params: any) => {
|
|
||||||
const rowId = normalizeId(params?.data?.id)
|
|
||||||
const field = String(params?.colDef?.field || '')
|
|
||||||
return hasOwnProperty(props.cellErrors[rowId], field)
|
|
||||||
}
|
|
||||||
|
|
||||||
const getCellClasses = (params: any) => {
|
|
||||||
const classes: string[] = []
|
|
||||||
if (isDraftCell(params)) classes.push('cell-draft')
|
|
||||||
if (isErrorCell(params)) classes.push('cell-error')
|
|
||||||
return classes
|
|
||||||
}
|
|
||||||
|
|
||||||
const getCellStyle = (params: any) => {
|
|
||||||
const isDraft = isDraftCell(params)
|
|
||||||
const isError = isErrorCell(params)
|
|
||||||
if (!isDraft && !isError) return null
|
|
||||||
const style: Record<string, string> = {}
|
|
||||||
if (isDraft) {
|
|
||||||
style.backgroundColor = 'hsl(var(--accent) / 0.45)'
|
|
||||||
style.outline = '2px solid hsl(var(--accent))'
|
|
||||||
style.outlineOffset = '-2px'
|
|
||||||
}
|
|
||||||
if (isError) {
|
|
||||||
style.backgroundColor = 'hsl(var(--destructive) / 0.28)'
|
|
||||||
style.outline = '2px solid hsl(var(--destructive))'
|
|
||||||
style.outlineOffset = '-2px'
|
|
||||||
}
|
|
||||||
return style
|
|
||||||
}
|
|
||||||
|
|
||||||
const columnDefs = computed<ColDef[]>(() =>
|
|
||||||
visibleFields.value.map(field => ({
|
|
||||||
field: field.apiName,
|
|
||||||
headerName: field.label,
|
|
||||||
sortable: field.sortable !== false,
|
|
||||||
editable: isEditableField(field),
|
|
||||||
valueFormatter: params => formatFieldValue(field, params.value, params.data),
|
|
||||||
cellClass: params => getCellClasses(params),
|
|
||||||
cellStyle: params => getCellStyle(params),
|
|
||||||
cellEditor:
|
|
||||||
field.type === FieldType.SELECT
|
|
||||||
? 'agSelectCellEditor'
|
|
||||||
: field.type === FieldType.MULTI_SELECT
|
|
||||||
? 'agTextCellEditor'
|
|
||||||
: field.type === FieldType.NUMBER || field.type === FieldType.CURRENCY
|
|
||||||
? 'agTextCellEditor'
|
|
||||||
: undefined,
|
|
||||||
cellEditorParams:
|
|
||||||
field.type === FieldType.SELECT
|
|
||||||
? { values: (field.options || []).map(opt => opt.value) }
|
|
||||||
: undefined,
|
|
||||||
valueParser:
|
|
||||||
field.type === FieldType.NUMBER || field.type === FieldType.CURRENCY
|
|
||||||
? params => (params.newValue === '' ? null : Number(params.newValue))
|
|
||||||
: undefined,
|
|
||||||
flex: 1,
|
|
||||||
minWidth: 160,
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
|
|
||||||
const defaultColDef: ColDef = {
|
|
||||||
resizable: true,
|
|
||||||
sortable: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleCellValueChanged = (event: CellValueChangedEvent) => {
|
|
||||||
const field = visibleFields.value.find(item => item.apiName === event.colDef.field)
|
|
||||||
if (!field || event.newValue === event.oldValue) return
|
|
||||||
emit('cell-edit', {
|
|
||||||
row: event.data,
|
|
||||||
field,
|
|
||||||
newValue: event.newValue,
|
|
||||||
oldValue: event.oldValue,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleGridReady = (event: GridReadyEvent) => {
|
|
||||||
gridApi.value = event.api
|
|
||||||
}
|
|
||||||
|
|
||||||
const goToPage = (page: number) => {
|
const goToPage = (page: number) => {
|
||||||
const nextPage = Math.min(Math.max(page, 1), availablePages.value)
|
const nextPage = Math.min(Math.max(page, 1), availablePages.value)
|
||||||
if (nextPage !== currentPage.value) {
|
if (nextPage !== currentPage.value) {
|
||||||
@@ -380,23 +193,6 @@ watch(
|
|||||||
},
|
},
|
||||||
{ deep: true }
|
{ deep: true }
|
||||||
)
|
)
|
||||||
|
|
||||||
watch(
|
|
||||||
() => viewMode.value,
|
|
||||||
(mode) => {
|
|
||||||
emit('view-change', mode)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
watch(
|
|
||||||
() => [props.draftEdits, props.cellErrors],
|
|
||||||
() => {
|
|
||||||
if (gridApi.value) {
|
|
||||||
gridApi.value.refreshCells({ force: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ deep: true }
|
|
||||||
)
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -420,95 +216,6 @@ watch(
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<!-- Saved Views dropdown + cog -->
|
|
||||||
<div class="flex items-center gap-1">
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger as-child>
|
|
||||||
<Button variant="outline" size="sm" class="gap-2">
|
|
||||||
<Bookmark class="h-4 w-4" />
|
|
||||||
<span class="max-w-[120px] truncate">
|
|
||||||
{{ savedViews.find(v => v.id === activeViewId)?.name || 'Views' }}
|
|
||||||
</span>
|
|
||||||
<ChevronDown class="h-3 w-3 opacity-60" />
|
|
||||||
</Button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="start" class="w-56">
|
|
||||||
<DropdownMenuItem
|
|
||||||
v-if="savedViews.length === 0"
|
|
||||||
disabled
|
|
||||||
class="text-muted-foreground"
|
|
||||||
>
|
|
||||||
No saved views yet
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
v-for="view in savedViews"
|
|
||||||
:key="view.id"
|
|
||||||
:class="{ 'font-medium': view.id === activeViewId }"
|
|
||||||
@click="emit('apply-view', view)"
|
|
||||||
>
|
|
||||||
<span class="flex-1 truncate">{{ view.name }}</span>
|
|
||||||
<Badge v-if="view.isShared" variant="secondary" class="ml-2 text-[10px] px-1.5 py-0">Shared</Badge>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuSeparator v-if="savedViews.length > 0" />
|
|
||||||
<DropdownMenuItem @click="emit('open-view-manager')">
|
|
||||||
Manage views…
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
class="h-8 w-8"
|
|
||||||
title="Manage saved views"
|
|
||||||
@click="emit('open-view-manager')"
|
|
||||||
>
|
|
||||||
<Settings2 class="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Save current search as a view (only for query strategy) -->
|
|
||||||
<Button
|
|
||||||
v-if="currentSearchPlan?.strategy === 'query'"
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
:disabled="savingView"
|
|
||||||
class="gap-2"
|
|
||||||
@click="emit('save-view')"
|
|
||||||
>
|
|
||||||
<BookmarkPlus class="h-4 w-4" />
|
|
||||||
Save view
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Select v-model="viewMode">
|
|
||||||
<SelectTrigger class="h-8 w-[180px]">
|
|
||||||
<SelectValue placeholder="Select view" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="list">List view</SelectItem>
|
|
||||||
<SelectItem value="spreadsheet">Spreadsheet view</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<template v-if="viewMode === 'spreadsheet'">
|
|
||||||
<Badge v-if="draftRowCount > 0" variant="secondary" class="px-3 py-1">
|
|
||||||
{{ draftCellCount }} change{{ draftCellCount === 1 ? '' : 's' }}
|
|
||||||
</Badge>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
:disabled="draftRowCount === 0 || savingDrafts"
|
|
||||||
@click="emit('discard-drafts')"
|
|
||||||
>
|
|
||||||
Discard changes
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
:disabled="draftRowCount === 0 || savingDrafts"
|
|
||||||
@click="emit('save-drafts')"
|
|
||||||
>
|
|
||||||
Save changes ({{ draftRowCount }})
|
|
||||||
</Button>
|
|
||||||
</template>
|
|
||||||
<!-- Bulk Actions -->
|
<!-- Bulk Actions -->
|
||||||
<template v-if="selectedRowIds.length > 0">
|
<template v-if="selectedRowIds.length > 0">
|
||||||
<Badge variant="secondary" class="px-3 py-1">
|
<Badge variant="secondary" class="px-3 py-1">
|
||||||
@@ -557,7 +264,7 @@ watch(
|
|||||||
|
|
||||||
<!-- Table -->
|
<!-- Table -->
|
||||||
<div class="border rounded-lg">
|
<div class="border rounded-lg">
|
||||||
<Table v-if="viewMode === 'list'">
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableHead v-if="selectable" class="w-12">
|
<TableHead v-if="selectable" class="w-12">
|
||||||
@@ -631,19 +338,6 @@ watch(
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
<div v-else class="ag-theme-alpine">
|
|
||||||
<AgGridVue
|
|
||||||
:row-data="data"
|
|
||||||
:column-defs="columnDefs"
|
|
||||||
:default-col-def="defaultColDef"
|
|
||||||
dom-layout="autoHeight"
|
|
||||||
row-selection="multiple"
|
|
||||||
suppress-row-click-selection
|
|
||||||
single-click-edit
|
|
||||||
@cell-value-changed="handleCellValueChanged"
|
|
||||||
@grid-ready="handleGridReady"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="showPagination" class="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
|
<div v-if="showPagination" class="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
|
||||||
@@ -681,5 +375,4 @@ watch(
|
|||||||
.list-view :deep(input) {
|
.list-view :deep(input) {
|
||||||
background-color: hsl(var(--background));
|
background-color: hsl(var(--background));
|
||||||
}
|
}
|
||||||
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,131 +1,61 @@
|
|||||||
/**
|
|
||||||
* 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 () => {
|
||||||
try {
|
if (import.meta.client) {
|
||||||
await $fetch('/api/auth/logout', {
|
// Call backend logout endpoint
|
||||||
method: 'POST',
|
try {
|
||||||
})
|
const token = localStorage.getItem('token')
|
||||||
} catch (error) {
|
const tenantId = localStorage.getItem('tenantId')
|
||||||
console.error('Logout error:', error)
|
|
||||||
}
|
if (token) {
|
||||||
|
await fetch(`${config.public.apiBaseUrl}/api/auth/logout`, {
|
||||||
// Clear local state
|
method: 'POST',
|
||||||
user.value = null
|
headers: {
|
||||||
isAuthenticated.value = false
|
'Authorization': `Bearer ${token}`,
|
||||||
|
...(tenantId && { 'x-tenant-id': tenantId }),
|
||||||
// Set flash message for login page
|
},
|
||||||
authMessageCookie.value = 'Logged out successfully'
|
})
|
||||||
|
}
|
||||||
// Redirect to login page
|
} catch (error) {
|
||||||
router.push('/login')
|
console.error('Logout error:', error)
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
// Clear local storage
|
||||||
user.value = null
|
localStorage.removeItem('token')
|
||||||
isAuthenticated.value = false
|
localStorage.removeItem('tenantId')
|
||||||
} finally {
|
localStorage.removeItem('user')
|
||||||
isLoading.value = false
|
|
||||||
|
// Clear cookie for server-side check
|
||||||
|
tokenCookie.value = null
|
||||||
|
|
||||||
|
// Set flash message for login page
|
||||||
|
authMessageCookie.value = 'Logged out successfully'
|
||||||
|
|
||||||
|
// Redirect to login page
|
||||||
|
router.push('/login')
|
||||||
}
|
}
|
||||||
|
|
||||||
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,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
export interface SavedViewFilter {
|
|
||||||
field: string
|
|
||||||
operator: string
|
|
||||||
value?: any
|
|
||||||
values?: any[]
|
|
||||||
from?: string
|
|
||||||
to?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SavedViewSort {
|
|
||||||
field: string
|
|
||||||
direction: 'asc' | 'desc'
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SavedView {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
objectApiName: string
|
|
||||||
userId: string
|
|
||||||
isOwner: boolean
|
|
||||||
isShared: boolean
|
|
||||||
strategy: 'query'
|
|
||||||
filters: SavedViewFilter[]
|
|
||||||
sort: SavedViewSort | null
|
|
||||||
description: string | null
|
|
||||||
createdAt: string
|
|
||||||
updatedAt: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateSavedViewPayload {
|
|
||||||
name: string
|
|
||||||
objectApiName: string
|
|
||||||
filters: SavedViewFilter[]
|
|
||||||
sort?: SavedViewSort | null
|
|
||||||
description?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UpdateSavedViewPayload {
|
|
||||||
name?: string
|
|
||||||
filters?: SavedViewFilter[]
|
|
||||||
sort?: SavedViewSort | null
|
|
||||||
description?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useSavedViews() {
|
|
||||||
const { api } = useApi()
|
|
||||||
|
|
||||||
const savedViews = ref<SavedView[]>([])
|
|
||||||
const loading = ref(false)
|
|
||||||
|
|
||||||
async function fetchSavedViews(objectApiName: string) {
|
|
||||||
loading.value = true
|
|
||||||
try {
|
|
||||||
const data = await api.get(`/saved-views/${objectApiName}`)
|
|
||||||
savedViews.value = Array.isArray(data) ? data : []
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to fetch saved views', e)
|
|
||||||
savedViews.value = []
|
|
||||||
} finally {
|
|
||||||
loading.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function createSavedView(payload: CreateSavedViewPayload): Promise<SavedView> {
|
|
||||||
const created = await api.post('/saved-views', payload)
|
|
||||||
savedViews.value = [...savedViews.value, created]
|
|
||||||
return created
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateSavedView(id: string, payload: UpdateSavedViewPayload): Promise<SavedView> {
|
|
||||||
const updated = await api.patch(`/saved-views/${id}`, payload)
|
|
||||||
savedViews.value = savedViews.value.map(v => (v.id === id ? updated : v))
|
|
||||||
return updated
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deleteSavedView(id: string) {
|
|
||||||
await api.delete(`/saved-views/${id}`)
|
|
||||||
savedViews.value = savedViews.value.filter(v => v.id !== id)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function suggestViewName(
|
|
||||||
objectLabel: string,
|
|
||||||
filters: SavedViewFilter[],
|
|
||||||
explanation?: string,
|
|
||||||
): Promise<string> {
|
|
||||||
try {
|
|
||||||
const result = await api.post('/ai/suggest-view-name', {
|
|
||||||
objectLabel,
|
|
||||||
filters,
|
|
||||||
explanation,
|
|
||||||
})
|
|
||||||
return result?.suggestedName || `${objectLabel} View`
|
|
||||||
} catch {
|
|
||||||
return `${objectLabel} View`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
savedViews,
|
|
||||||
loading,
|
|
||||||
fetchSavedViews,
|
|
||||||
createSavedView,
|
|
||||||
updateSavedView,
|
|
||||||
deleteSavedView,
|
|
||||||
suggestViewName,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,54 +210,35 @@ 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');
|
if (socket.value?.connected || !token) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user is authenticated
|
// Use same pattern as useApi to preserve subdomain for multi-tenant
|
||||||
if (!auth.isAuthenticated.value) {
|
const getBackendUrl = () => {
|
||||||
// Try to verify authentication first
|
if (typeof window !== 'undefined') {
|
||||||
const isValid = await auth.checkAuth();
|
const currentHost = window.location.hostname;
|
||||||
if (!isValid) {
|
const protocol = window.location.protocol;
|
||||||
console.log('Softphone: User not authenticated, skipping connection');
|
return `${protocol}//${currentHost}`;
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
return 'http://localhost:3000';
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
// Connect to /voice namespace with proper auth header
|
||||||
// Get WebSocket token from BFF (this retrieves the token from HTTP-only cookie server-side)
|
socket.value = io(`${getBackendUrl()}/voice`, {
|
||||||
const wsAuth = await $fetch('/api/auth/ws-token');
|
auth: {
|
||||||
|
token: token,
|
||||||
if (!wsAuth.token) {
|
},
|
||||||
console.log('Softphone: No WebSocket token available');
|
transports: ['websocket', 'polling'],
|
||||||
return;
|
reconnection: true,
|
||||||
}
|
reconnectionDelay: 1000,
|
||||||
|
reconnectionDelayMax: 5000,
|
||||||
// Use same pattern as useApi to preserve subdomain for multi-tenant
|
reconnectionAttempts: 5,
|
||||||
const getBackendUrl = () => {
|
query: {}, // Explicitly set empty query to prevent token leaking
|
||||||
if (typeof window !== 'undefined') {
|
});
|
||||||
const currentHost = window.location.hostname;
|
|
||||||
const protocol = window.location.protocol;
|
|
||||||
return `${protocol}//${currentHost}`;
|
|
||||||
}
|
|
||||||
return 'http://localhost:3000';
|
|
||||||
};
|
|
||||||
|
|
||||||
// Connect to /voice namespace with proper auth header
|
|
||||||
socket.value = io(`${getBackendUrl()}/voice`, {
|
|
||||||
auth: {
|
|
||||||
token: wsAuth.token,
|
|
||||||
},
|
|
||||||
transports: ['websocket', 'polling'],
|
|
||||||
reconnection: true,
|
|
||||||
reconnectionDelay: 1000,
|
|
||||||
reconnectionDelayMax: 5000,
|
|
||||||
reconnectionAttempts: 5,
|
|
||||||
query: {}, // Explicitly set empty query to prevent token leaking
|
|
||||||
});
|
|
||||||
|
|
||||||
// Connection events
|
// Connection events
|
||||||
socket.value.on('connect', () => {
|
socket.value.on('connect', () => {
|
||||||
@@ -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
|
// Cleanup on unmount
|
||||||
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
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
stopRingtone();
|
stopRingtone();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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 (import.meta.client) {
|
if (!token.value) {
|
||||||
const { isAuthenticated, checkAuth } = useAuth()
|
|
||||||
|
|
||||||
// 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
|
// On client side, also verify localStorage is in sync
|
||||||
// The session cookie is HTTP-only but can be read in SSR context
|
if (import.meta.client) {
|
||||||
if (!sessionCookie.value || !tenantCookie.value) {
|
const { isLoggedIn } = useAuth()
|
||||||
if (!silentRoutes.includes(to.path)) {
|
if (!isLoggedIn()) {
|
||||||
authMessage.value = 'Please login to access this page'
|
if (!silentRoutes.includes(to.path)) {
|
||||||
|
authMessage.value = 'Please login to access this page'
|
||||||
|
}
|
||||||
|
return navigateTo('/login')
|
||||||
}
|
}
|
||||||
return navigateTo('/login')
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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: {
|
||||||
|
|||||||
27
frontend/package-lock.json
generated
27
frontend/package-lock.json
generated
@@ -13,8 +13,6 @@
|
|||||||
"@nuxtjs/tailwindcss": "^6.11.4",
|
"@nuxtjs/tailwindcss": "^6.11.4",
|
||||||
"@twilio/voice-sdk": "^2.11.2",
|
"@twilio/voice-sdk": "^2.11.2",
|
||||||
"@vueuse/core": "^10.11.1",
|
"@vueuse/core": "^10.11.1",
|
||||||
"ag-grid-community": "^32.3.4",
|
|
||||||
"ag-grid-vue3": "^32.3.4",
|
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.1.0",
|
"clsx": "^2.1.0",
|
||||||
"gridstack": "^12.4.1",
|
"gridstack": "^12.4.1",
|
||||||
@@ -4978,31 +4976,6 @@
|
|||||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/ag-charts-types": {
|
|
||||||
"version": "10.3.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/ag-charts-types/-/ag-charts-types-10.3.9.tgz",
|
|
||||||
"integrity": "sha512-drcRiJVencliC8LnRwk4MmeQDNNBg5GzmOoLFihO3/k0CUK0VF/N+2nc7iFozwaNG0btSB9vAhYuJLjqHMtRrQ==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/ag-grid-community": {
|
|
||||||
"version": "32.3.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/ag-grid-community/-/ag-grid-community-32.3.9.tgz",
|
|
||||||
"integrity": "sha512-l07SB0mCbGPkC1R8rQQFgBtI5+1FoXBi3RUk1+dHKV/UPeorMEFAzCokcsOhz0qwcWCPrHauUsbRa1SIxfVEJQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"ag-charts-types": "10.3.9"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/ag-grid-vue3": {
|
|
||||||
"version": "32.3.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/ag-grid-vue3/-/ag-grid-vue3-32.3.9.tgz",
|
|
||||||
"integrity": "sha512-86Xynbfg8bq/tGW0Yfl2O8HSUgT7nDtNzioMs4r8hNfPiqOfKUUWrTveP5S4Acs8Astr495ZdKKFDIcQVLx3Yg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"ag-grid-community": "32.3.9",
|
|
||||||
"vue": "^3.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/agent-base": {
|
"node_modules/agent-base": {
|
||||||
"version": "7.1.4",
|
"version": "7.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||||
|
|||||||
@@ -19,8 +19,6 @@
|
|||||||
"@nuxtjs/tailwindcss": "^6.11.4",
|
"@nuxtjs/tailwindcss": "^6.11.4",
|
||||||
"@twilio/voice-sdk": "^2.11.2",
|
"@twilio/voice-sdk": "^2.11.2",
|
||||||
"@vueuse/core": "^10.11.1",
|
"@vueuse/core": "^10.11.1",
|
||||||
"ag-grid-community": "^32.3.4",
|
|
||||||
"ag-grid-vue3": "^32.3.4",
|
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.1.0",
|
"clsx": "^2.1.0",
|
||||||
"gridstack": "^12.4.1",
|
"gridstack": "^12.4.1",
|
||||||
|
|||||||
@@ -4,12 +4,9 @@ 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 { usePageLayouts } from '@/composables/usePageLayouts'
|
||||||
import { useSavedViews } from '@/composables/useSavedViews'
|
|
||||||
import type { SavedView } from '@/composables/useSavedViews'
|
|
||||||
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'
|
||||||
import SavedViewPanel from '@/components/SavedViewPanel.vue'
|
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
@@ -18,23 +15,12 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from '@/components/ui/dialog'
|
} from '@/components/ui/dialog'
|
||||||
import { Button } from '@/components/ui/button'
|
|
||||||
import { Input } from '@/components/ui/input'
|
|
||||||
import { Label } from '@/components/ui/label'
|
|
||||||
|
|
||||||
const route = useRoute()
|
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()
|
const { getDefaultPageLayout } = usePageLayouts()
|
||||||
const {
|
|
||||||
savedViews,
|
|
||||||
fetchSavedViews,
|
|
||||||
createSavedView,
|
|
||||||
updateSavedView,
|
|
||||||
deleteSavedView,
|
|
||||||
suggestViewName,
|
|
||||||
} = useSavedViews()
|
|
||||||
|
|
||||||
// Use breadcrumbs composable
|
// Use breadcrumbs composable
|
||||||
const { setBreadcrumbs } = useBreadcrumbs()
|
const { setBreadcrumbs } = useBreadcrumbs()
|
||||||
@@ -71,7 +57,6 @@ const {
|
|||||||
fetchRecord,
|
fetchRecord,
|
||||||
deleteRecord,
|
deleteRecord,
|
||||||
deleteRecords,
|
deleteRecords,
|
||||||
updateRecord,
|
|
||||||
handleSave,
|
handleSave,
|
||||||
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
|
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
|
||||||
|
|
||||||
@@ -180,27 +165,11 @@ const deleteDialogOpen = ref(false)
|
|||||||
const deleteSubmitting = ref(false)
|
const deleteSubmitting = ref(false)
|
||||||
const pendingDeleteRows = ref<any[]>([])
|
const pendingDeleteRows = ref<any[]>([])
|
||||||
const deleteSummary = ref<{ deletedIds: string[]; deniedIds: string[] } | null>(null)
|
const deleteSummary = ref<{ deletedIds: string[]; deniedIds: string[] } | null>(null)
|
||||||
const normalizeRecordId = (id: any) => String(id)
|
|
||||||
|
|
||||||
const draftEdits = ref<Record<string, Record<string, any>>>({})
|
|
||||||
const draftOriginals = ref<Record<string, Record<string, any>>>({})
|
|
||||||
const cellErrors = ref<Record<string, Record<string, string>>>({})
|
|
||||||
const savingDrafts = ref(false)
|
|
||||||
|
|
||||||
const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
|
const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
|
||||||
const pendingDeleteCount = computed(() => pendingDeleteRows.value.length)
|
const pendingDeleteCount = computed(() => pendingDeleteRows.value.length)
|
||||||
const deniedDeleteCount = computed(() => deleteSummary.value?.deniedIds.length ?? 0)
|
const deniedDeleteCount = computed(() => deleteSummary.value?.deniedIds.length ?? 0)
|
||||||
|
|
||||||
// ── Saved views state ──────────────────────────────────────────────────────
|
|
||||||
const activeViewId = ref<string | null>(null)
|
|
||||||
const currentSearchPlan = ref<{
|
|
||||||
strategy: string; filters: any[]; sort: any; explanation: string
|
|
||||||
} | null>(null)
|
|
||||||
const viewPanelOpen = ref(false)
|
|
||||||
const saveViewDialogOpen = ref(false)
|
|
||||||
const saveViewName = ref('')
|
|
||||||
const savingView = ref(false)
|
|
||||||
|
|
||||||
// Fetch object definition
|
// Fetch object definition
|
||||||
const fetchObjectDefinition = async () => {
|
const fetchObjectDefinition = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -347,19 +316,6 @@ const searchListRecords = async (
|
|||||||
records.value = options?.append ? [...records.value, ...data] : data
|
records.value = options?.append ? [...records.value, ...data] : data
|
||||||
totalCount.value = total
|
totalCount.value = total
|
||||||
searchSummary.value = response?.explanation || ''
|
searchSummary.value = response?.explanation || ''
|
||||||
|
|
||||||
// Capture the plan for the "Save view" feature (only when strategy is query)
|
|
||||||
if (response?.strategy === 'query') {
|
|
||||||
currentSearchPlan.value = {
|
|
||||||
strategy: response.strategy,
|
|
||||||
filters: response.filters || [],
|
|
||||||
sort: response.sort || null,
|
|
||||||
explanation: response.explanation || '',
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
currentSearchPlan.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
return response
|
return response
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
error.value = e.message || 'Failed to search records'
|
error.value = e.message || 'Failed to search records'
|
||||||
@@ -399,266 +355,17 @@ const handleLoadMore = async (page: number, pageSize: number) => {
|
|||||||
await loadListRecords(page, { append: true, pageSize })
|
await loadListRecords(page, { append: true, pageSize })
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadAllListRecords = async () => {
|
|
||||||
if (!records.value.length) {
|
|
||||||
await loadListRecords(1)
|
|
||||||
}
|
|
||||||
const resolvedTotal = totalCount.value ?? records.value.length
|
|
||||||
if (resolvedTotal > records.value.length) {
|
|
||||||
await loadListRecords(1, { append: false, pageSize: resolvedTotal })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleViewChange = async (mode: 'list' | 'spreadsheet') => {
|
|
||||||
if (mode === 'spreadsheet' && !isSearchActive.value) {
|
|
||||||
await loadAllListRecords()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSearch = async (query: string) => {
|
const handleSearch = async (query: string) => {
|
||||||
const trimmed = query.trim()
|
const trimmed = query.trim()
|
||||||
searchQuery.value = trimmed
|
searchQuery.value = trimmed
|
||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
searchSummary.value = ''
|
searchSummary.value = ''
|
||||||
currentSearchPlan.value = null
|
|
||||||
activeViewId.value = null
|
|
||||||
await initializeListRecords()
|
await initializeListRecords()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await searchListRecords(1, { append: false, pageSize: listPageSize.value })
|
await searchListRecords(1, { append: false, pageSize: listPageSize.value })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCellEdit = async (payload: { row: any; field: any; newValue: any; oldValue: any }) => {
|
|
||||||
if (!payload?.row?.id || payload.newValue === payload.oldValue) return
|
|
||||||
const recordKey = normalizeRecordId(payload.row.id)
|
|
||||||
const fieldName = payload.field.apiName
|
|
||||||
const originalRow = draftOriginals.value[recordKey]
|
|
||||||
const originalValue = originalRow && Object.prototype.hasOwnProperty.call(originalRow, fieldName)
|
|
||||||
? originalRow[fieldName]
|
|
||||||
: payload.oldValue
|
|
||||||
|
|
||||||
if (Object.is(payload.newValue, originalValue)) {
|
|
||||||
const nextDrafts = { ...draftEdits.value }
|
|
||||||
const nextRowDrafts = { ...(nextDrafts[recordKey] || {}) }
|
|
||||||
delete nextRowDrafts[fieldName]
|
|
||||||
if (Object.keys(nextRowDrafts).length === 0) {
|
|
||||||
delete nextDrafts[recordKey]
|
|
||||||
} else {
|
|
||||||
nextDrafts[recordKey] = nextRowDrafts
|
|
||||||
}
|
|
||||||
draftEdits.value = nextDrafts
|
|
||||||
|
|
||||||
const nextOriginals = { ...draftOriginals.value }
|
|
||||||
const nextRowOriginals = { ...(nextOriginals[recordKey] || {}) }
|
|
||||||
delete nextRowOriginals[fieldName]
|
|
||||||
if (Object.keys(nextRowOriginals).length === 0) {
|
|
||||||
delete nextOriginals[recordKey]
|
|
||||||
} else {
|
|
||||||
nextOriginals[recordKey] = nextRowOriginals
|
|
||||||
}
|
|
||||||
draftOriginals.value = nextOriginals
|
|
||||||
} else {
|
|
||||||
draftEdits.value = {
|
|
||||||
...draftEdits.value,
|
|
||||||
[recordKey]: {
|
|
||||||
...(draftEdits.value[recordKey] || {}),
|
|
||||||
[fieldName]: payload.newValue,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
if (!originalRow || !Object.prototype.hasOwnProperty.call(originalRow, fieldName)) {
|
|
||||||
draftOriginals.value = {
|
|
||||||
...draftOriginals.value,
|
|
||||||
[recordKey]: {
|
|
||||||
...(draftOriginals.value[recordKey] || {}),
|
|
||||||
[fieldName]: payload.oldValue,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cellErrors.value[recordKey]?.[fieldName]) {
|
|
||||||
const nextErrors = { ...cellErrors.value }
|
|
||||||
const nextRowErrors = { ...(nextErrors[recordKey] || {}) }
|
|
||||||
delete nextRowErrors[fieldName]
|
|
||||||
if (Object.keys(nextRowErrors).length === 0) {
|
|
||||||
delete nextErrors[recordKey]
|
|
||||||
} else {
|
|
||||||
nextErrors[recordKey] = nextRowErrors
|
|
||||||
}
|
|
||||||
cellErrors.value = nextErrors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSaveDrafts = async () => {
|
|
||||||
if (Object.keys(draftEdits.value).length === 0) return
|
|
||||||
savingDrafts.value = true
|
|
||||||
const nextErrors: Record<string, Record<string, string>> = {}
|
|
||||||
const nextDrafts = { ...draftEdits.value }
|
|
||||||
const nextOriginals = { ...draftOriginals.value }
|
|
||||||
|
|
||||||
for (const [recordKey, changes] of Object.entries(draftEdits.value)) {
|
|
||||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
|
||||||
if (!record) {
|
|
||||||
delete nextDrafts[recordKey]
|
|
||||||
delete nextOriginals[recordKey]
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await updateRecord(record.id, changes)
|
|
||||||
delete nextDrafts[recordKey]
|
|
||||||
delete nextOriginals[recordKey]
|
|
||||||
} catch (e: any) {
|
|
||||||
const message = e.message || 'Failed to update record'
|
|
||||||
nextErrors[recordKey] = {}
|
|
||||||
for (const fieldName of Object.keys(changes)) {
|
|
||||||
nextErrors[recordKey][fieldName] = message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
draftEdits.value = nextDrafts
|
|
||||||
draftOriginals.value = nextOriginals
|
|
||||||
cellErrors.value = nextErrors
|
|
||||||
savingDrafts.value = false
|
|
||||||
if (Object.keys(nextErrors).length > 0) {
|
|
||||||
error.value = 'Some updates failed. Fix highlighted cells and try again.'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDiscardDrafts = () => {
|
|
||||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
|
||||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
|
||||||
if (!record) continue
|
|
||||||
for (const [fieldName, originalValue] of Object.entries(fields)) {
|
|
||||||
record[fieldName] = originalValue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
draftEdits.value = {}
|
|
||||||
draftOriginals.value = {}
|
|
||||||
cellErrors.value = {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Saved view handlers ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply a saved view: execute its stored filters directly without re-running AI.
|
|
||||||
*/
|
|
||||||
const handleApplyView = async (view: SavedView) => {
|
|
||||||
activeViewId.value = view.id
|
|
||||||
searchQuery.value = ''
|
|
||||||
searchSummary.value = view.description || ''
|
|
||||||
currentSearchPlan.value = {
|
|
||||||
strategy: view.strategy,
|
|
||||||
filters: view.filters,
|
|
||||||
sort: view.sort,
|
|
||||||
explanation: view.description || '',
|
|
||||||
}
|
|
||||||
searchLoading.value = true
|
|
||||||
try {
|
|
||||||
const response = await api.post(
|
|
||||||
`/runtime/objects/${objectApiName.value}/records/search`,
|
|
||||||
{
|
|
||||||
filters: view.filters,
|
|
||||||
sort: view.sort,
|
|
||||||
page: 1,
|
|
||||||
pageSize: listPageSize.value,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
const data = response?.data ?? []
|
|
||||||
records.value = data
|
|
||||||
totalCount.value = response?.totalCount ?? data.length
|
|
||||||
} catch (e: any) {
|
|
||||||
error.value = e.message || 'Failed to apply saved view'
|
|
||||||
} finally {
|
|
||||||
searchLoading.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Open the "Save view" dialog, pre-filling the name via AI suggestion.
|
|
||||||
*/
|
|
||||||
const handleSaveView = async () => {
|
|
||||||
if (!currentSearchPlan.value) return
|
|
||||||
saveViewName.value = ''
|
|
||||||
saveViewDialogOpen.value = true
|
|
||||||
// Async-suggest a name while dialog is open
|
|
||||||
const objectLabel = objectDefinition.value?.label || objectApiName.value
|
|
||||||
const suggested = await suggestViewName(
|
|
||||||
objectLabel,
|
|
||||||
currentSearchPlan.value.filters,
|
|
||||||
currentSearchPlan.value.explanation,
|
|
||||||
)
|
|
||||||
// Only auto-fill if user hasn't typed anything yet
|
|
||||||
if (!saveViewName.value) {
|
|
||||||
saveViewName.value = suggested
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Confirm the save: persist the view and close the dialog.
|
|
||||||
*/
|
|
||||||
const confirmSaveView = async () => {
|
|
||||||
const name = saveViewName.value.trim()
|
|
||||||
if (!name || !currentSearchPlan.value) return
|
|
||||||
savingView.value = true
|
|
||||||
try {
|
|
||||||
await createSavedView({
|
|
||||||
name,
|
|
||||||
objectApiName: objectApiName.value,
|
|
||||||
filters: currentSearchPlan.value.filters,
|
|
||||||
sort: currentSearchPlan.value.sort,
|
|
||||||
description: currentSearchPlan.value.explanation,
|
|
||||||
})
|
|
||||||
saveViewDialogOpen.value = false
|
|
||||||
saveViewName.value = ''
|
|
||||||
} catch (e: any) {
|
|
||||||
error.value = e.message || 'Failed to save view'
|
|
||||||
} finally {
|
|
||||||
savingView.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleOpenViewManager = () => {
|
|
||||||
viewPanelOpen.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleUpdateView = async (id: string, payload: any) => {
|
|
||||||
await updateSavedView(id, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDeleteView = async (view: SavedView) => {
|
|
||||||
await deleteSavedView(view.id)
|
|
||||||
if (activeViewId.value === view.id) {
|
|
||||||
activeViewId.value = null
|
|
||||||
currentSearchPlan.value = null
|
|
||||||
await initializeListRecords()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watch(
|
|
||||||
() => records.value.map(record => normalizeRecordId(record.id)),
|
|
||||||
(ids) => {
|
|
||||||
const idSet = new Set(ids)
|
|
||||||
const nextDrafts: Record<string, Record<string, any>> = {}
|
|
||||||
const nextOriginals: Record<string, Record<string, any>> = {}
|
|
||||||
const nextErrors: Record<string, Record<string, string>> = {}
|
|
||||||
|
|
||||||
for (const [recordKey, fields] of Object.entries(draftEdits.value)) {
|
|
||||||
if (idSet.has(recordKey)) nextDrafts[recordKey] = fields
|
|
||||||
}
|
|
||||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
|
||||||
if (idSet.has(recordKey)) nextOriginals[recordKey] = fields
|
|
||||||
}
|
|
||||||
for (const [recordKey, fields] of Object.entries(cellErrors.value)) {
|
|
||||||
if (idSet.has(recordKey)) nextErrors[recordKey] = fields
|
|
||||||
}
|
|
||||||
|
|
||||||
draftEdits.value = nextDrafts
|
|
||||||
draftOriginals.value = nextOriginals
|
|
||||||
cellErrors.value = nextErrors
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Watch for route changes
|
// Watch for route changes
|
||||||
watch(() => route.params, async (newParams, oldParams) => {
|
watch(() => route.params, async (newParams, oldParams) => {
|
||||||
// Reset current record when navigating to 'new'
|
// Reset current record when navigating to 'new'
|
||||||
@@ -683,8 +390,6 @@ onMounted(async () => {
|
|||||||
|
|
||||||
if (view.value === 'list') {
|
if (view.value === 'list') {
|
||||||
await initializeListRecords()
|
await initializeListRecords()
|
||||||
// Load saved views for this object
|
|
||||||
fetchSavedViews(objectApiName.value).catch(() => {})
|
|
||||||
} else if (recordId.value && recordId.value !== 'new') {
|
} else if (recordId.value && recordId.value !== 'new') {
|
||||||
await fetchRecord(recordId.value)
|
await fetchRecord(recordId.value)
|
||||||
}
|
}
|
||||||
@@ -733,13 +438,6 @@ onMounted(async () => {
|
|||||||
:total-count="totalCount"
|
:total-count="totalCount"
|
||||||
:search-summary="searchSummary"
|
:search-summary="searchSummary"
|
||||||
:base-url="`/runtime/objects`"
|
:base-url="`/runtime/objects`"
|
||||||
:draft-edits="draftEdits"
|
|
||||||
:cell-errors="cellErrors"
|
|
||||||
:saving-drafts="savingDrafts"
|
|
||||||
:saved-views="savedViews"
|
|
||||||
:active-view-id="activeViewId"
|
|
||||||
:current-search-plan="currentSearchPlan"
|
|
||||||
:saving-view="savingView"
|
|
||||||
selectable
|
selectable
|
||||||
@row-click="handleRowClick"
|
@row-click="handleRowClick"
|
||||||
@create="handleCreate"
|
@create="handleCreate"
|
||||||
@@ -748,13 +446,6 @@ onMounted(async () => {
|
|||||||
@search="handleSearch"
|
@search="handleSearch"
|
||||||
@page-change="handlePageChange"
|
@page-change="handlePageChange"
|
||||||
@load-more="handleLoadMore"
|
@load-more="handleLoadMore"
|
||||||
@view-change="handleViewChange"
|
|
||||||
@cell-edit="handleCellEdit"
|
|
||||||
@save-drafts="handleSaveDrafts"
|
|
||||||
@discard-drafts="handleDiscardDrafts"
|
|
||||||
@apply-view="handleApplyView"
|
|
||||||
@save-view="handleSaveView"
|
|
||||||
@open-view-manager="handleOpenViewManager"
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- Detail View -->
|
<!-- Detail View -->
|
||||||
@@ -826,46 +517,6 @@ onMounted(async () => {
|
|||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
<!-- Save view dialog -->
|
|
||||||
<Dialog v-model:open="saveViewDialogOpen">
|
|
||||||
<DialogContent class="sm:max-w-[420px]">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Save view</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Give this search a name so you can reuse it later.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<div class="space-y-2 py-2">
|
|
||||||
<Label for="view-name">View name</Label>
|
|
||||||
<Input
|
|
||||||
id="view-name"
|
|
||||||
v-model="saveViewName"
|
|
||||||
placeholder="e.g. Cocker Spaniels"
|
|
||||||
@keyup.enter="confirmSaveView"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button variant="outline" @click="saveViewDialogOpen = false" :disabled="savingView">
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button @click="confirmSaveView" :disabled="savingView || !saveViewName.trim()">
|
|
||||||
Save
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
<!-- Saved views slide-over panel -->
|
|
||||||
<SavedViewPanel
|
|
||||||
v-model:open="viewPanelOpen"
|
|
||||||
:views="savedViews"
|
|
||||||
:object-label="objectDefinition?.pluralLabel || objectDefinition?.label || objectApiName"
|
|
||||||
:active-view-id="activeViewId"
|
|
||||||
@apply-view="handleApplyView"
|
|
||||||
@update-view="handleUpdateView"
|
|
||||||
@delete-view="handleDeleteView"
|
|
||||||
/>
|
|
||||||
</NuxtLayout>
|
</NuxtLayout>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ const {
|
|||||||
fetchRecord,
|
fetchRecord,
|
||||||
deleteRecord,
|
deleteRecord,
|
||||||
deleteRecords,
|
deleteRecords,
|
||||||
updateRecord,
|
|
||||||
handleSave,
|
handleSave,
|
||||||
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
|
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
|
||||||
|
|
||||||
@@ -91,12 +90,6 @@ const editConfig = computed(() => {
|
|||||||
|
|
||||||
const listPageSize = computed(() => listConfig.value?.pageSize ?? 25)
|
const listPageSize = computed(() => listConfig.value?.pageSize ?? 25)
|
||||||
const maxFrontendRecords = computed(() => listConfig.value?.maxFrontendRecords ?? 500)
|
const maxFrontendRecords = computed(() => listConfig.value?.maxFrontendRecords ?? 500)
|
||||||
const normalizeRecordId = (id: any) => String(id)
|
|
||||||
|
|
||||||
const draftEdits = ref<Record<string, Record<string, any>>>({})
|
|
||||||
const draftOriginals = ref<Record<string, Record<string, any>>>({})
|
|
||||||
const cellErrors = ref<Record<string, Record<string, string>>>({})
|
|
||||||
const savingDrafts = ref(false)
|
|
||||||
|
|
||||||
// Fetch object definition
|
// Fetch object definition
|
||||||
const fetchObjectDefinition = async () => {
|
const fetchObjectDefinition = async () => {
|
||||||
@@ -219,156 +212,6 @@ const handleLoadMore = async (page: number, pageSize: number) => {
|
|||||||
await loadListRecords(page, { append: true, pageSize })
|
await loadListRecords(page, { append: true, pageSize })
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadAllListRecords = async () => {
|
|
||||||
if (!records.value.length) {
|
|
||||||
await loadListRecords(1)
|
|
||||||
}
|
|
||||||
const resolvedTotal = totalCount.value ?? records.value.length
|
|
||||||
if (resolvedTotal > records.value.length) {
|
|
||||||
await loadListRecords(1, { append: false, pageSize: resolvedTotal })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleViewChange = async (mode: 'list' | 'spreadsheet') => {
|
|
||||||
if (mode === 'spreadsheet') {
|
|
||||||
await loadAllListRecords()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleCellEdit = async (payload: { row: any; field: any; newValue: any; oldValue: any }) => {
|
|
||||||
if (!payload?.row?.id || payload.newValue === payload.oldValue) return
|
|
||||||
const recordKey = normalizeRecordId(payload.row.id)
|
|
||||||
const fieldName = payload.field.apiName
|
|
||||||
const originalRow = draftOriginals.value[recordKey]
|
|
||||||
const originalValue = originalRow && Object.prototype.hasOwnProperty.call(originalRow, fieldName)
|
|
||||||
? originalRow[fieldName]
|
|
||||||
: payload.oldValue
|
|
||||||
|
|
||||||
if (Object.is(payload.newValue, originalValue)) {
|
|
||||||
const nextDrafts = { ...draftEdits.value }
|
|
||||||
const nextRowDrafts = { ...(nextDrafts[recordKey] || {}) }
|
|
||||||
delete nextRowDrafts[fieldName]
|
|
||||||
if (Object.keys(nextRowDrafts).length === 0) {
|
|
||||||
delete nextDrafts[recordKey]
|
|
||||||
} else {
|
|
||||||
nextDrafts[recordKey] = nextRowDrafts
|
|
||||||
}
|
|
||||||
draftEdits.value = nextDrafts
|
|
||||||
|
|
||||||
const nextOriginals = { ...draftOriginals.value }
|
|
||||||
const nextRowOriginals = { ...(nextOriginals[recordKey] || {}) }
|
|
||||||
delete nextRowOriginals[fieldName]
|
|
||||||
if (Object.keys(nextRowOriginals).length === 0) {
|
|
||||||
delete nextOriginals[recordKey]
|
|
||||||
} else {
|
|
||||||
nextOriginals[recordKey] = nextRowOriginals
|
|
||||||
}
|
|
||||||
draftOriginals.value = nextOriginals
|
|
||||||
} else {
|
|
||||||
draftEdits.value = {
|
|
||||||
...draftEdits.value,
|
|
||||||
[recordKey]: {
|
|
||||||
...(draftEdits.value[recordKey] || {}),
|
|
||||||
[fieldName]: payload.newValue,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
if (!originalRow || !Object.prototype.hasOwnProperty.call(originalRow, fieldName)) {
|
|
||||||
draftOriginals.value = {
|
|
||||||
...draftOriginals.value,
|
|
||||||
[recordKey]: {
|
|
||||||
...(draftOriginals.value[recordKey] || {}),
|
|
||||||
[fieldName]: payload.oldValue,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cellErrors.value[recordKey]?.[fieldName]) {
|
|
||||||
const nextErrors = { ...cellErrors.value }
|
|
||||||
const nextRowErrors = { ...(nextErrors[recordKey] || {}) }
|
|
||||||
delete nextRowErrors[fieldName]
|
|
||||||
if (Object.keys(nextRowErrors).length === 0) {
|
|
||||||
delete nextErrors[recordKey]
|
|
||||||
} else {
|
|
||||||
nextErrors[recordKey] = nextRowErrors
|
|
||||||
}
|
|
||||||
cellErrors.value = nextErrors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSaveDrafts = async () => {
|
|
||||||
if (Object.keys(draftEdits.value).length === 0) return
|
|
||||||
savingDrafts.value = true
|
|
||||||
const nextErrors: Record<string, Record<string, string>> = {}
|
|
||||||
const nextDrafts = { ...draftEdits.value }
|
|
||||||
const nextOriginals = { ...draftOriginals.value }
|
|
||||||
|
|
||||||
for (const [recordKey, changes] of Object.entries(draftEdits.value)) {
|
|
||||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
|
||||||
if (!record) {
|
|
||||||
delete nextDrafts[recordKey]
|
|
||||||
delete nextOriginals[recordKey]
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await updateRecord(record.id, changes)
|
|
||||||
delete nextDrafts[recordKey]
|
|
||||||
delete nextOriginals[recordKey]
|
|
||||||
} catch (e: any) {
|
|
||||||
const message = e.message || 'Failed to update record'
|
|
||||||
nextErrors[recordKey] = {}
|
|
||||||
for (const fieldName of Object.keys(changes)) {
|
|
||||||
nextErrors[recordKey][fieldName] = message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
draftEdits.value = nextDrafts
|
|
||||||
draftOriginals.value = nextOriginals
|
|
||||||
cellErrors.value = nextErrors
|
|
||||||
savingDrafts.value = false
|
|
||||||
if (Object.keys(nextErrors).length > 0) {
|
|
||||||
error.value = 'Some updates failed. Fix highlighted cells and try again.'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDiscardDrafts = () => {
|
|
||||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
|
||||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
|
||||||
if (!record) continue
|
|
||||||
for (const [fieldName, originalValue] of Object.entries(fields)) {
|
|
||||||
record[fieldName] = originalValue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
draftEdits.value = {}
|
|
||||||
draftOriginals.value = {}
|
|
||||||
cellErrors.value = {}
|
|
||||||
}
|
|
||||||
|
|
||||||
watch(
|
|
||||||
() => records.value.map(record => normalizeRecordId(record.id)),
|
|
||||||
(ids) => {
|
|
||||||
const idSet = new Set(ids)
|
|
||||||
const nextDrafts: Record<string, Record<string, any>> = {}
|
|
||||||
const nextOriginals: Record<string, Record<string, any>> = {}
|
|
||||||
const nextErrors: Record<string, Record<string, string>> = {}
|
|
||||||
|
|
||||||
for (const [recordKey, fields] of Object.entries(draftEdits.value)) {
|
|
||||||
if (idSet.has(recordKey)) nextDrafts[recordKey] = fields
|
|
||||||
}
|
|
||||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
|
||||||
if (idSet.has(recordKey)) nextOriginals[recordKey] = fields
|
|
||||||
}
|
|
||||||
for (const [recordKey, fields] of Object.entries(cellErrors.value)) {
|
|
||||||
if (idSet.has(recordKey)) nextErrors[recordKey] = fields
|
|
||||||
}
|
|
||||||
|
|
||||||
draftEdits.value = nextDrafts
|
|
||||||
draftOriginals.value = nextOriginals
|
|
||||||
cellErrors.value = nextErrors
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Watch for route changes
|
// Watch for route changes
|
||||||
watch(() => route.params, async (newParams, oldParams) => {
|
watch(() => route.params, async (newParams, oldParams) => {
|
||||||
// Reset current record when navigating to 'new'
|
// Reset current record when navigating to 'new'
|
||||||
@@ -435,9 +278,6 @@ onMounted(async () => {
|
|||||||
:data="records"
|
:data="records"
|
||||||
:loading="dataLoading"
|
:loading="dataLoading"
|
||||||
:total-count="totalCount"
|
:total-count="totalCount"
|
||||||
:draft-edits="draftEdits"
|
|
||||||
:cell-errors="cellErrors"
|
|
||||||
:saving-drafts="savingDrafts"
|
|
||||||
selectable
|
selectable
|
||||||
@row-click="handleRowClick"
|
@row-click="handleRowClick"
|
||||||
@create="handleCreate"
|
@create="handleCreate"
|
||||||
@@ -445,10 +285,6 @@ onMounted(async () => {
|
|||||||
@delete="handleDelete"
|
@delete="handleDelete"
|
||||||
@page-change="handlePageChange"
|
@page-change="handlePageChange"
|
||||||
@load-more="handleLoadMore"
|
@load-more="handleLoadMore"
|
||||||
@view-change="handleViewChange"
|
|
||||||
@cell-edit="handleCellEdit"
|
|
||||||
@save-drafts="handleSaveDrafts"
|
|
||||||
@discard-drafts="handleDiscardDrafts"
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- Detail View -->
|
<!-- Detail View -->
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|
||||||
|
|||||||
@@ -33,10 +33,6 @@
|
|||||||
<Label class="text-muted-foreground">Email</Label>
|
<Label class="text-muted-foreground">Email</Label>
|
||||||
<p class="font-medium">{{ user?.email }}</p>
|
<p class="font-medium">{{ user?.email }}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<Label class="text-muted-foreground">Alias</Label>
|
|
||||||
<p class="font-medium">{{ user?.alias || 'N/A' }}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
<div>
|
||||||
<Label class="text-muted-foreground">First Name</Label>
|
<Label class="text-muted-foreground">First Name</Label>
|
||||||
<p class="font-medium">{{ user?.firstName || 'N/A' }}</p>
|
<p class="font-medium">{{ user?.firstName || 'N/A' }}</p>
|
||||||
@@ -214,9 +210,6 @@ const removeRole = async (roleId: string) => {
|
|||||||
|
|
||||||
const getUserName = (user: any) => {
|
const getUserName = (user: any) => {
|
||||||
if (!user) return 'User';
|
if (!user) return 'User';
|
||||||
if (user.alias) {
|
|
||||||
return user.alias;
|
|
||||||
}
|
|
||||||
if (user.firstName || user.lastName) {
|
if (user.firstName || user.lastName) {
|
||||||
return [user.firstName, user.lastName].filter(Boolean).join(' ');
|
return [user.firstName, user.lastName].filter(Boolean).join(' ');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -95,10 +95,6 @@
|
|||||||
<Label for="lastName">Last Name (Optional)</Label>
|
<Label for="lastName">Last Name (Optional)</Label>
|
||||||
<Input id="lastName" v-model="newUser.lastName" placeholder="Doe" />
|
<Input id="lastName" v-model="newUser.lastName" placeholder="Doe" />
|
||||||
</div>
|
</div>
|
||||||
<div class="space-y-2">
|
|
||||||
<Label for="alias">Alias (Optional)</Label>
|
|
||||||
<Input id="alias" v-model="newUser.alias" placeholder="Display name" />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" @click="showCreateDialog = false">Cancel</Button>
|
<Button variant="outline" @click="showCreateDialog = false">Cancel</Button>
|
||||||
@@ -135,10 +131,6 @@
|
|||||||
<Label for="edit-lastName">Last Name</Label>
|
<Label for="edit-lastName">Last Name</Label>
|
||||||
<Input id="edit-lastName" v-model="editUser.lastName" placeholder="Doe" />
|
<Input id="edit-lastName" v-model="editUser.lastName" placeholder="Doe" />
|
||||||
</div>
|
</div>
|
||||||
<div class="space-y-2">
|
|
||||||
<Label for="edit-alias">Alias</Label>
|
|
||||||
<Input id="edit-alias" v-model="editUser.alias" placeholder="Display name" />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" @click="showEditDialog = false">Cancel</Button>
|
<Button variant="outline" @click="showEditDialog = false">Cancel</Button>
|
||||||
@@ -195,7 +187,6 @@ const newUser = ref({
|
|||||||
password: '',
|
password: '',
|
||||||
firstName: '',
|
firstName: '',
|
||||||
lastName: '',
|
lastName: '',
|
||||||
alias: '',
|
|
||||||
});
|
});
|
||||||
const editUser = ref({
|
const editUser = ref({
|
||||||
id: '',
|
id: '',
|
||||||
@@ -203,7 +194,6 @@ const editUser = ref({
|
|||||||
password: '',
|
password: '',
|
||||||
firstName: '',
|
firstName: '',
|
||||||
lastName: '',
|
lastName: '',
|
||||||
alias: '',
|
|
||||||
});
|
});
|
||||||
const userToDelete = ref<any>(null);
|
const userToDelete = ref<any>(null);
|
||||||
|
|
||||||
@@ -225,7 +215,7 @@ const createUser = async () => {
|
|||||||
await api.post('/setup/users', newUser.value);
|
await api.post('/setup/users', newUser.value);
|
||||||
toast.success('User created successfully');
|
toast.success('User created successfully');
|
||||||
showCreateDialog.value = false;
|
showCreateDialog.value = false;
|
||||||
newUser.value = { email: '', password: '', firstName: '', lastName: '', alias: '' };
|
newUser.value = { email: '', password: '', firstName: '', lastName: '' };
|
||||||
await loadUsers();
|
await loadUsers();
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('Failed to create user:', error);
|
console.error('Failed to create user:', error);
|
||||||
@@ -240,7 +230,6 @@ const openEditDialog = (user: any) => {
|
|||||||
password: '',
|
password: '',
|
||||||
firstName: user.firstName || '',
|
firstName: user.firstName || '',
|
||||||
lastName: user.lastName || '',
|
lastName: user.lastName || '',
|
||||||
alias: user.alias || '',
|
|
||||||
};
|
};
|
||||||
showEditDialog.value = true;
|
showEditDialog.value = true;
|
||||||
};
|
};
|
||||||
@@ -251,7 +240,6 @@ const updateUser = async () => {
|
|||||||
email: editUser.value.email,
|
email: editUser.value.email,
|
||||||
firstName: editUser.value.firstName,
|
firstName: editUser.value.firstName,
|
||||||
lastName: editUser.value.lastName,
|
lastName: editUser.value.lastName,
|
||||||
alias: editUser.value.alias,
|
|
||||||
};
|
};
|
||||||
if (editUser.value.password) {
|
if (editUser.value.password) {
|
||||||
payload.password = editUser.value.password;
|
payload.password = editUser.value.password;
|
||||||
@@ -285,9 +273,6 @@ const deleteUser = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getUserName = (user: any) => {
|
const getUserName = (user: any) => {
|
||||||
if (user.alias) {
|
|
||||||
return user.alias;
|
|
||||||
}
|
|
||||||
if (user.firstName || user.lastName) {
|
if (user.firstName || user.lastName) {
|
||||||
return [user.firstName, user.lastName].filter(Boolean).join(' ');
|
return [user.firstName, user.lastName].filter(Boolean).join(' ');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -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',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -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',
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -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',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -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,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -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: '/',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user