Compare commits

...

24 Commits

Author SHA1 Message Date
Francisco Gaona
12a82372f4 WIP - Semantic linking working asynchronously 2026-04-12 11:24:03 +02:00
Francisco Gaona
efa57c4ba8 WIP - semantic linking seems to be working fine 2026-04-12 11:09:43 +02:00
Francisco Gaona
3f9be316ce WIP - semantinc linking working with other fields 2026-04-12 10:48:37 +02:00
Francisco Gaona
385a842ab8 WIP - semantic linking working with just name 2026-04-12 09:26:23 +02:00
Francisco Gaona
320f8c4266 WIP - some progress with semantic linking but still needs a lot of work 2026-04-11 23:30:25 +02:00
Francisco Gaona
12b0a0881e WIP - initial UI for comments and semantic links 2026-04-11 22:14:24 +02:00
Francisco Gaona
dc18b08a3a WIP - enable embedings 2026-04-11 21:14:34 +02:00
phyroslam
df183230d8 Add phased knowledge layer: comments and semantic linking pipeline 2026-04-11 11:40:01 -07:00
Francisco Gaona
baf3997fb6 WIP - fix displaying name for owner field 2026-04-10 22:19:11 +02:00
Francisco Gaona
a2d48f6a03 WIP - Fix options for picklist field, some progress on multi picklist. 2026-04-10 21:41:13 +02:00
Francisco Gaona
fb2533fa4c WIP - sharing list views 2026-04-10 10:57:20 +02:00
Francisco Gaona
12304d5890 WIP - saving list views 2026-04-10 10:37:11 +02:00
Francisco Gaona
a0bdb09c03 WIP - resolving related look ups for search filtering 2026-04-10 09:07:06 +02:00
Francisco Gaona
c89dc04d4c WIP - improve list filtering explanation 2026-04-09 21:46:29 +02:00
Francisco Gaona
7a175923b0 Merge branch 'codex/fix-ai-search-result-explanation' into integrate-query-explain-fix 2026-04-09 19:06:37 +02:00
phyroslam
ed48623f27 Use LLM refinement for query explanation text 2026-04-09 08:58:09 -07:00
Francisco Gaona
228c3fb704 WIP - fixes to spreadsheet view 2026-04-09 09:28:25 +02:00
Francisco Gaona
5f14a4050a WIP - added spredsheet view using ag-grid 2026-02-06 22:01:59 +01:00
Francisco Gaona
eb1619c56c WIP - fix AI suggestions during call progress 2026-02-05 03:02:02 +01:00
Francisco Gaona
9226442525 WIP - fix twilio functionality now that we use BFF 2026-02-05 02:41:54 +01:00
Francisco Gaona
49a571215d WIP - fix browser refresh not holding user authentication 2026-02-04 08:55:08 +01:00
Francisco Gaona
0e2f3dddbc WIP - BFF 2026-02-04 00:21:06 +01:00
Francisco Gaona
f68321c802 Use AI assistant to create records in the system, added configurable list views 2026-01-31 03:24:46 +01:00
Francisco Gaona
20fc90a3fb Add Contact standard object, related lists, meilisearch, pagination, search, AI assistant 2026-01-16 18:01:26 +01:00
127 changed files with 15047 additions and 773 deletions

View File

@@ -5,6 +5,11 @@ DATABASE_URL="mysql://platform:platform@db:3306/platform"
CENTRAL_DATABASE_URL="mysql://root:asjdnfqTash37faggT@db:3306/central_platform" CENTRAL_DATABASE_URL="mysql://root:asjdnfqTash37faggT@db:3306/central_platform"
REDIS_URL="redis://redis:6379" REDIS_URL="redis://redis:6379"
# Meilisearch (optional)
MEILI_HOST="http://meilisearch:7700"
MEILI_API_KEY="dev-meili-master-key"
MEILI_INDEX_PREFIX="tenant_"
# JWT, multi-tenant hints, etc. # JWT, multi-tenant hints, etc.
JWT_SECRET="devsecret" JWT_SECRET="devsecret"
TENANCY_STRATEGY="single-db" TENANCY_STRATEGY="single-db"

View File

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

View File

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

View File

@@ -0,0 +1,207 @@
exports.up = async function (knex) {
await knex.schema.createTable('contacts', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
table.string('firstName', 100).notNullable();
table.string('lastName', 100).notNullable();
table.uuid('accountId').notNullable();
table.timestamps(true, true);
table
.foreign('accountId')
.references('id')
.inTable('accounts')
.onDelete('CASCADE');
table.index(['accountId']);
table.index(['lastName', 'firstName']);
});
await knex.schema.createTable('contact_details', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
table.string('relatedObjectType', 100).notNullable();
table.uuid('relatedObjectId').notNullable();
table.string('detailType', 50).notNullable();
table.string('label', 100);
table.text('value').notNullable();
table.boolean('isPrimary').defaultTo(false);
table.timestamps(true, true);
table.index(['relatedObjectType', 'relatedObjectId']);
table.index(['detailType']);
});
const [contactObjectId] = await knex('object_definitions').insert({
id: knex.raw('(UUID())'),
apiName: 'Contact',
label: 'Contact',
pluralLabel: 'Contacts',
description: 'Standard Contact object',
isSystem: true,
isCustom: false,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
});
const contactObjectDefId =
contactObjectId ||
(await knex('object_definitions').where('apiName', 'Contact').first()).id;
await knex('field_definitions').insert([
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactObjectDefId,
apiName: 'firstName',
label: 'First Name',
type: 'String',
length: 100,
isRequired: true,
isSystem: true,
isCustom: false,
displayOrder: 1,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactObjectDefId,
apiName: 'lastName',
label: 'Last Name',
type: 'String',
length: 100,
isRequired: true,
isSystem: true,
isCustom: false,
displayOrder: 2,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactObjectDefId,
apiName: 'accountId',
label: 'Account',
type: 'Reference',
referenceObject: 'Account',
isRequired: true,
isSystem: true,
isCustom: false,
displayOrder: 3,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
]);
const [contactDetailObjectId] = await knex('object_definitions').insert({
id: knex.raw('(UUID())'),
apiName: 'ContactDetail',
label: 'Contact Detail',
pluralLabel: 'Contact Details',
description: 'Polymorphic contact detail object',
isSystem: true,
isCustom: false,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
});
const contactDetailObjectDefId =
contactDetailObjectId ||
(await knex('object_definitions').where('apiName', 'ContactDetail').first())
.id;
const contactDetailRelationObjects = ['Account', 'Contact']
await knex('field_definitions').insert([
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactDetailObjectDefId,
apiName: 'relatedObjectType',
label: 'Related Object Type',
type: 'PICKLIST',
length: 100,
isRequired: true,
isSystem: false,
isCustom: false,
displayOrder: 1,
ui_metadata: JSON.stringify({
options: contactDetailRelationObjects.map((value) => ({ label: value, value })),
}),
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactDetailObjectDefId,
apiName: 'relatedObjectId',
label: 'Related Object ID',
type: 'LOOKUP',
length: 36,
isRequired: true,
isSystem: false,
isCustom: false,
displayOrder: 2,
ui_metadata: JSON.stringify({
relationObjects: contactDetailRelationObjects,
relationTypeField: 'relatedObjectType',
relationDisplayField: 'name',
}),
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactDetailObjectDefId,
apiName: 'detailType',
label: 'Detail Type',
type: 'String',
length: 50,
isRequired: true,
isSystem: false,
isCustom: false,
displayOrder: 3,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactDetailObjectDefId,
apiName: 'label',
label: 'Label',
type: 'String',
length: 100,
isSystem: false,
isCustom: false,
displayOrder: 4,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactDetailObjectDefId,
apiName: 'value',
label: 'Value',
type: 'Text',
isRequired: true,
isSystem: false,
isCustom: false,
displayOrder: 5,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
{
id: knex.raw('(UUID())'),
objectDefinitionId: contactDetailObjectDefId,
apiName: 'isPrimary',
label: 'Primary',
type: 'Boolean',
isSystem: false,
isCustom: false,
displayOrder: 6,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
},
]);
};
exports.down = async function (knex) {
await knex.schema.dropTableIfExists('contact_details');
await knex.schema.dropTableIfExists('contacts');
};

View File

@@ -0,0 +1,101 @@
exports.up = async function (knex) {
const contactDetailObject = await knex('object_definitions')
.where({ apiName: 'ContactDetail' })
.first();
if (!contactDetailObject) return;
const relationObjects = ['Account', 'Contact'];
await knex('field_definitions')
.where({
objectDefinitionId: contactDetailObject.id,
apiName: 'relatedObjectType',
})
.update({
type: 'PICKLIST',
length: 100,
isSystem: false,
ui_metadata: JSON.stringify({
options: relationObjects.map((value) => ({ label: value, value })),
}),
updated_at: knex.fn.now(),
});
await knex('field_definitions')
.where({
objectDefinitionId: contactDetailObject.id,
apiName: 'relatedObjectId',
})
.update({
type: 'LOOKUP',
length: 36,
isSystem: false,
ui_metadata: JSON.stringify({
relationObjects,
relationTypeField: 'relatedObjectType',
relationDisplayField: 'name',
}),
updated_at: knex.fn.now(),
});
await knex('field_definitions')
.whereIn('apiName', [
'detailType',
'label',
'value',
'isPrimary',
])
.andWhere({ objectDefinitionId: contactDetailObject.id })
.update({
isSystem: false,
updated_at: knex.fn.now(),
});
};
exports.down = async function (knex) {
const contactDetailObject = await knex('object_definitions')
.where({ apiName: 'ContactDetail' })
.first();
if (!contactDetailObject) return;
await knex('field_definitions')
.where({
objectDefinitionId: contactDetailObject.id,
apiName: 'relatedObjectType',
})
.update({
type: 'String',
length: 100,
isSystem: true,
ui_metadata: null,
updated_at: knex.fn.now(),
});
await knex('field_definitions')
.where({
objectDefinitionId: contactDetailObject.id,
apiName: 'relatedObjectId',
})
.update({
type: 'String',
length: 36,
isSystem: true,
ui_metadata: null,
updated_at: knex.fn.now(),
});
await knex('field_definitions')
.whereIn('apiName', [
'detailType',
'label',
'value',
'isPrimary',
])
.andWhere({ objectDefinitionId: contactDetailObject.id })
.update({
isSystem: true,
updated_at: knex.fn.now(),
});
};

View File

@@ -0,0 +1,45 @@
exports.up = async function (knex) {
const contactDetailObject = await knex('object_definitions')
.where({ apiName: 'ContactDetail' })
.first();
if (!contactDetailObject) return;
await knex('field_definitions')
.where({ objectDefinitionId: contactDetailObject.id })
.whereIn('apiName', [
'relatedObjectType',
'relatedObjectId',
'detailType',
'label',
'value',
'isPrimary',
])
.update({
isSystem: false,
updated_at: knex.fn.now(),
});
};
exports.down = async function (knex) {
const contactDetailObject = await knex('object_definitions')
.where({ apiName: 'ContactDetail' })
.first();
if (!contactDetailObject) return;
await knex('field_definitions')
.where({ objectDefinitionId: contactDetailObject.id })
.whereIn('apiName', [
'relatedObjectType',
'relatedObjectId',
'detailType',
'label',
'value',
'isPrimary',
])
.update({
isSystem: true,
updated_at: knex.fn.now(),
});
};

View File

@@ -0,0 +1,62 @@
exports.up = async function (knex) {
// Add ownerId column to contacts
await knex.schema.alterTable('contacts', (table) => {
table.uuid('ownerId');
table
.foreign('ownerId')
.references('id')
.inTable('users')
.onDelete('SET NULL');
table.index(['ownerId']);
});
// Add ownerId field definition metadata for Contact object
const contactObject = await knex('object_definitions')
.where('apiName', 'Contact')
.first();
if (contactObject) {
const existingField = await knex('field_definitions')
.where({
objectDefinitionId: contactObject.id,
apiName: 'ownerId',
})
.first();
if (!existingField) {
await knex('field_definitions').insert({
id: knex.raw('(UUID())'),
objectDefinitionId: contactObject.id,
apiName: 'ownerId',
label: 'Owner',
type: 'Reference',
referenceObject: 'User',
isSystem: true,
isCustom: false,
displayOrder: 4,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
});
}
}
};
exports.down = async function (knex) {
const contactObject = await knex('object_definitions')
.where('apiName', 'Contact')
.first();
if (contactObject) {
await knex('field_definitions')
.where({
objectDefinitionId: contactObject.id,
apiName: 'ownerId',
})
.delete();
}
await knex.schema.alterTable('contacts', (table) => {
table.dropForeign(['ownerId']);
table.dropColumn('ownerId');
});
};

View File

@@ -0,0 +1,55 @@
/**
* 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');
};

View File

@@ -0,0 +1,35 @@
/**
* 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();
};

View File

@@ -0,0 +1,30 @@
/**
* 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');
});
};

View File

@@ -0,0 +1,93 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = async function (knex) {
await knex.schema.createTable('comments', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
table.string('parent_object_api_name').notNullable();
table.uuid('parent_record_id').notNullable();
table.uuid('author_user_id').notNullable();
table.text('content').notNullable();
table.timestamps(true, true);
table.foreign('author_user_id').references('id').inTable('users').onDelete('CASCADE');
table.index(['parent_object_api_name', 'parent_record_id'], 'comments_parent_idx');
table.index(['author_user_id'], 'comments_author_idx');
});
await knex.schema.createTable('semantic_documents', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
table.string('entity_type').notNullable();
table.uuid('entity_id').notNullable();
table.string('title').nullable();
table.text('narrative').nullable();
table.json('metadata').nullable();
table.json('source_summary').nullable();
table.timestamps(true, true);
table.unique(['entity_type', 'entity_id'], {
indexName: 'semantic_documents_entity_unique',
});
table.index(['entity_type'], 'semantic_documents_type_idx');
});
await knex.schema.createTable('semantic_chunks', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
table.uuid('semantic_document_id').notNullable();
table.integer('chunk_index').notNullable();
table.string('source_kind').notNullable().defaultTo('base_record');
table.uuid('source_ref_id').nullable();
table.text('text').notNullable();
table.json('metadata').nullable();
table.timestamps(true, true);
table.foreign('semantic_document_id').references('id').inTable('semantic_documents').onDelete('CASCADE');
table.unique(['semantic_document_id', 'chunk_index'], {
indexName: 'semantic_chunks_doc_index_unique',
});
table.index(['semantic_document_id'], 'semantic_chunks_document_idx');
table.index(['source_kind'], 'semantic_chunks_source_kind_idx');
});
await knex.schema.createTable('semantic_links', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
table.string('source_entity_type', 100).notNullable();
table.uuid('source_entity_id').notNullable();
table.string('target_entity_type', 100).notNullable();
table.uuid('target_entity_id').notNullable();
table.string('link_type', 100).notNullable().defaultTo('related_to');
table.string('status').notNullable().defaultTo('suggested');
table.string('origin').notNullable().defaultTo('semantic');
table.decimal('confidence', 5, 4).notNullable().defaultTo(0);
table.text('reason').nullable();
table.json('evidence').nullable();
table.uuid('suggested_by_user_id').nullable();
table.uuid('reviewed_by_user_id').nullable();
table.timestamp('reviewed_at').nullable();
table.timestamps(true, true);
table.foreign('suggested_by_user_id').references('id').inTable('users').onDelete('SET NULL');
table.foreign('reviewed_by_user_id').references('id').inTable('users').onDelete('SET NULL');
table.unique(
['source_entity_type', 'source_entity_id', 'target_entity_type', 'target_entity_id', 'link_type'],
{ indexName: 'semantic_links_unique_pair_type' },
);
table.index(['source_entity_type', 'source_entity_id'], 'semantic_links_source_idx');
table.index(['target_entity_type', 'target_entity_id'], 'semantic_links_target_idx');
table.index(['status'], 'semantic_links_status_idx');
});
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = async function (knex) {
await knex.schema.dropTableIfExists('semantic_links');
await knex.schema.dropTableIfExists('semantic_chunks');
await knex.schema.dropTableIfExists('semantic_documents');
await knex.schema.dropTableIfExists('comments');
};

View File

@@ -11,6 +11,9 @@
"dependencies": { "dependencies": {
"@casl/ability": "^6.7.5", "@casl/ability": "^6.7.5",
"@fastify/websocket": "^10.0.1", "@fastify/websocket": "^10.0.1",
"@langchain/core": "^1.1.15",
"@langchain/langgraph": "^1.0.15",
"@langchain/openai": "^1.2.1",
"@nestjs/bullmq": "^10.1.0", "@nestjs/bullmq": "^10.1.0",
"@nestjs/common": "^10.3.0", "@nestjs/common": "^10.3.0",
"@nestjs/config": "^3.1.1", "@nestjs/config": "^3.1.1",
@@ -26,8 +29,10 @@
"bullmq": "^5.1.0", "bullmq": "^5.1.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.1", "class-validator": "^0.14.1",
"deepagents": "^1.5.0",
"ioredis": "^5.3.2", "ioredis": "^5.3.2",
"knex": "^3.1.0", "knex": "^3.1.0",
"langchain": "^1.2.10",
"mysql2": "^3.15.3", "mysql2": "^3.15.3",
"objection": "^3.1.5", "objection": "^3.1.5",
"openai": "^6.15.0", "openai": "^6.15.0",
@@ -224,6 +229,26 @@
"tslib": "^2.1.0" "tslib": "^2.1.0"
} }
}, },
"node_modules/@anthropic-ai/sdk": {
"version": "0.71.2",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.71.2.tgz",
"integrity": "sha512-TGNDEUuEstk/DKu0/TflXAEt+p+p/WhTlFzEnoosvbaDU2LTjm42igSdlL0VijrKpWejtOKxX0b8A7uc+XiSAQ==",
"license": "MIT",
"dependencies": {
"json-schema-to-ts": "^3.1.1"
},
"bin": {
"anthropic-ai-sdk": "bin/cli"
},
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
},
"peerDependenciesMeta": {
"zod": {
"optional": true
}
}
},
"node_modules/@babel/code-frame": { "node_modules/@babel/code-frame": {
"version": "7.27.1", "version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
@@ -685,6 +710,15 @@
"@babel/core": "^7.0.0-0" "@babel/core": "^7.0.0-0"
} }
}, },
"node_modules/@babel/runtime": {
"version": "7.28.6",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz",
"integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": { "node_modules/@babel/template": {
"version": "7.27.2", "version": "7.27.2",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",
@@ -762,6 +796,12 @@
"url": "https://github.com/stalniy/casl/blob/master/BACKERS.md" "url": "https://github.com/stalniy/casl/blob/master/BACKERS.md"
} }
}, },
"node_modules/@cfworker/json-schema": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz",
"integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==",
"license": "MIT"
},
"node_modules/@colors/colors": { "node_modules/@colors/colors": {
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
@@ -1679,6 +1719,236 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@langchain/anthropic": {
"version": "1.3.10",
"resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-1.3.10.tgz",
"integrity": "sha512-VXq5fsEJ4FB5XGrnoG+bfm0I7OlmYLI4jZ6cX9RasyqhGo9wcDyKw1+uEQ1H7Og7jWrTa1bfXCun76wttewJnw==",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.71.0",
"zod": "^3.25.76 || ^4"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@langchain/core": "1.1.15"
}
},
"node_modules/@langchain/core": {
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.1.15.tgz",
"integrity": "sha512-b8RN5DkWAmDAlMu/UpTZEluYwCLpm63PPWniRKlE8ie3KkkE7IuMQ38pf4kV1iaiI+d99BEQa2vafQHfCujsRA==",
"license": "MIT",
"dependencies": {
"@cfworker/json-schema": "^4.0.2",
"ansi-styles": "^5.0.0",
"camelcase": "6",
"decamelize": "1.2.0",
"js-tiktoken": "^1.0.12",
"langsmith": ">=0.4.0 <1.0.0",
"mustache": "^4.2.0",
"p-queue": "^6.6.2",
"uuid": "^10.0.0",
"zod": "^3.25.76 || ^4"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@langchain/core/node_modules/ansi-styles": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/@langchain/core/node_modules/camelcase": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
"integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@langchain/core/node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/@langchain/langgraph": {
"version": "1.0.15",
"resolved": "https://registry.npmjs.org/@langchain/langgraph/-/langgraph-1.0.15.tgz",
"integrity": "sha512-l7/f255sPilanhyY+lbX+VDXQSnytFwJ4FVoEl4OBpjDoCHuDyHUL5yrb568apBSHgQA7aKsYac0mBEqIR5Bjg==",
"license": "MIT",
"dependencies": {
"@langchain/langgraph-checkpoint": "^1.0.0",
"@langchain/langgraph-sdk": "~1.5.0",
"uuid": "^10.0.0"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@langchain/core": "^1.0.1",
"zod": "^3.25.32 || ^4.1.0",
"zod-to-json-schema": "^3.x"
},
"peerDependenciesMeta": {
"zod-to-json-schema": {
"optional": true
}
}
},
"node_modules/@langchain/langgraph-checkpoint": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@langchain/langgraph-checkpoint/-/langgraph-checkpoint-1.0.0.tgz",
"integrity": "sha512-xrclBGvNCXDmi0Nz28t3vjpxSH6UYx6w5XAXSiiB1WEdc2xD2iY/a913I3x3a31XpInUW/GGfXXfePfaghV54A==",
"license": "MIT",
"dependencies": {
"uuid": "^10.0.0"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@langchain/core": "^1.0.1"
}
},
"node_modules/@langchain/langgraph-checkpoint/node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/@langchain/langgraph-sdk": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.5.2.tgz",
"integrity": "sha512-ArRnYIqJEUKnS+HFZoTtsIy2Uxy158l5ZTPWNhJkws6FuDEA3q/h6bhvHpZIf5z0JseDHCCoIbx6yOc2RpMpgg==",
"license": "MIT",
"dependencies": {
"p-queue": "^9.0.1",
"p-retry": "^7.1.1",
"uuid": "^13.0.0"
},
"peerDependencies": {
"@langchain/core": "^1.0.1",
"react": "^18 || ^19",
"react-dom": "^18 || ^19"
},
"peerDependenciesMeta": {
"@langchain/core": {
"optional": true
},
"react": {
"optional": true
},
"react-dom": {
"optional": true
}
}
},
"node_modules/@langchain/langgraph-sdk/node_modules/eventemitter3": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz",
"integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==",
"license": "MIT"
},
"node_modules/@langchain/langgraph-sdk/node_modules/p-queue": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.1.0.tgz",
"integrity": "sha512-O/ZPaXuQV29uSLbxWBGGZO1mCQXV2BLIwUr59JUU9SoH76mnYvtms7aafH/isNSNGwuEfP6W/4xD0/TJXxrizw==",
"license": "MIT",
"dependencies": {
"eventemitter3": "^5.0.1",
"p-timeout": "^7.0.0"
},
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@langchain/langgraph-sdk/node_modules/p-timeout": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz",
"integrity": "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==",
"license": "MIT",
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@langchain/langgraph-sdk/node_modules/uuid": {
"version": "13.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",
"integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist-node/bin/uuid"
}
},
"node_modules/@langchain/langgraph/node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/@langchain/openai": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@langchain/openai/-/openai-1.2.1.tgz",
"integrity": "sha512-eZYPhvXIwz0/8iCjj2LWqeaznQ7DZ6tBdvF+Ebv4sQW2UqJWZqRC8QIdKZgTbs8ffMWPHkSSOidYqu4XfWCNYg==",
"license": "MIT",
"dependencies": {
"js-tiktoken": "^1.0.12",
"openai": "^6.10.0",
"zod": "^3.25.76 || ^4"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@langchain/core": "^1.0.0"
}
},
"node_modules/@ljharb/through": { "node_modules/@ljharb/through": {
"version": "2.3.14", "version": "2.3.14",
"resolved": "https://registry.npmjs.org/@ljharb/through/-/through-2.3.14.tgz", "resolved": "https://registry.npmjs.org/@ljharb/through/-/through-2.3.14.tgz",
@@ -2263,7 +2533,6 @@
"version": "2.1.5", "version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@nodelib/fs.stat": "2.0.5", "@nodelib/fs.stat": "2.0.5",
@@ -2277,7 +2546,6 @@
"version": "2.0.5", "version": "2.0.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 8" "node": ">= 8"
@@ -2287,7 +2555,6 @@
"version": "1.2.8", "version": "1.2.8",
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@nodelib/fs.scandir": "2.1.5", "@nodelib/fs.scandir": "2.1.5",
@@ -2818,6 +3085,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
"license": "MIT"
},
"node_modules/@types/validator": { "node_modules/@types/validator": {
"version": "13.15.10", "version": "13.15.10",
"resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.10.tgz", "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.10.tgz",
@@ -3711,7 +3984,6 @@
"version": "1.5.1", "version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -3800,7 +4072,6 @@
"version": "3.0.3", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"fill-range": "^7.1.1" "fill-range": "^7.1.1"
@@ -4337,6 +4608,15 @@
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/console-table-printer": {
"version": "2.15.0",
"resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.15.0.tgz",
"integrity": "sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw==",
"license": "MIT",
"dependencies": {
"simple-wcswidth": "^1.1.2"
}
},
"node_modules/convert-source-map": { "node_modules/convert-source-map": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -4485,6 +4765,15 @@
} }
} }
}, },
"node_modules/decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/dedent": { "node_modules/dedent": {
"version": "1.7.0", "version": "1.7.0",
"resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.0.tgz", "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.0.tgz",
@@ -4507,6 +4796,22 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/deepagents": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/deepagents/-/deepagents-1.5.0.tgz",
"integrity": "sha512-tjZLOISPMpqfk+k/iE1uIZavXW9j4NrhopUmH5ARqzmk95EEtGDyN++tgnY+tdVOOZTjE2LHjOVV7or58dtx8A==",
"license": "MIT",
"dependencies": {
"@langchain/anthropic": "^1.3.7",
"@langchain/core": "^1.1.12",
"@langchain/langgraph": "^1.0.14",
"fast-glob": "^3.3.3",
"langchain": "^1.2.7",
"micromatch": "^4.0.8",
"yaml": "^2.8.2",
"zod": "^4.3.5"
}
},
"node_modules/deepmerge": { "node_modules/deepmerge": {
"version": "4.3.1", "version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
@@ -5150,6 +5455,12 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/eventemitter3": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
"license": "MIT"
},
"node_modules/events": { "node_modules/events": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
@@ -5261,7 +5572,6 @@
"version": "3.3.3", "version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.stat": "^2.0.2",
@@ -5487,7 +5797,6 @@
"version": "7.1.1", "version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"to-regex-range": "^5.0.1" "to-regex-range": "^5.0.1"
@@ -5892,7 +6201,6 @@
"version": "5.1.2", "version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"is-glob": "^4.0.1" "is-glob": "^4.0.1"
@@ -6341,7 +6649,6 @@
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
@@ -6370,7 +6677,6 @@
"version": "4.0.3", "version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"is-extglob": "^2.1.1" "is-extglob": "^2.1.1"
@@ -6389,11 +6695,22 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/is-network-error": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.0.tgz",
"integrity": "sha512-6oIwpsgRfnDiyEDLMay/GqCl3HoAtH5+RUKW29gYkL0QA+ipzpDLA16yQs7/RHCSu+BwgbJaOUqa4A99qNVQVw==",
"license": "MIT",
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-number": { "node_modules/is-number": {
"version": "7.0.0", "version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=0.12.0" "node": ">=0.12.0"
@@ -7279,6 +7596,15 @@
"url": "https://github.com/chalk/supports-color?sponsor=1" "url": "https://github.com/chalk/supports-color?sponsor=1"
} }
}, },
"node_modules/js-tiktoken": {
"version": "1.0.21",
"resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz",
"integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.5.1"
}
},
"node_modules/js-tokens": { "node_modules/js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -7335,6 +7661,19 @@
"fast-deep-equal": "^3.1.3" "fast-deep-equal": "^3.1.3"
} }
}, },
"node_modules/json-schema-to-ts": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.18.3",
"ts-algebra": "^2.0.0"
},
"engines": {
"node": ">=16"
}
},
"node_modules/json-schema-traverse": { "node_modules/json-schema-traverse": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -7536,6 +7875,85 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/langchain": {
"version": "1.2.10",
"resolved": "https://registry.npmjs.org/langchain/-/langchain-1.2.10.tgz",
"integrity": "sha512-9uVxOJE/RTECvNutQfOLwH7f6R9mcq0G/IMHwA2eptDA86R/Yz2zWMz4vARVFPxPrdSJ9nJFDPAqRQlRFwdHBw==",
"license": "MIT",
"dependencies": {
"@langchain/langgraph": "^1.0.0",
"@langchain/langgraph-checkpoint": "^1.0.0",
"langsmith": ">=0.4.0 <1.0.0",
"uuid": "^10.0.0",
"zod": "^3.25.76 || ^4"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@langchain/core": "1.1.15"
}
},
"node_modules/langchain/node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/langsmith": {
"version": "0.4.5",
"resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.4.5.tgz",
"integrity": "sha512-9N4JSQLz6fWiZwVXaiy0erlvNHlC68EtGJZG2OX+1y9mqj7KvKSL+xJnbCFc+ky3JN8s1d6sCfyyDdi4uDdLnQ==",
"license": "MIT",
"dependencies": {
"@types/uuid": "^10.0.0",
"chalk": "^4.1.2",
"console-table-printer": "^2.12.1",
"p-queue": "^6.6.2",
"semver": "^7.6.3",
"uuid": "^10.0.0"
},
"peerDependencies": {
"@opentelemetry/api": "*",
"@opentelemetry/exporter-trace-otlp-proto": "*",
"@opentelemetry/sdk-trace-base": "*",
"openai": "*"
},
"peerDependenciesMeta": {
"@opentelemetry/api": {
"optional": true
},
"@opentelemetry/exporter-trace-otlp-proto": {
"optional": true
},
"@opentelemetry/sdk-trace-base": {
"optional": true
},
"openai": {
"optional": true
}
}
},
"node_modules/langsmith/node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/leven": { "node_modules/leven": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@@ -7848,7 +8266,6 @@
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 8" "node": ">= 8"
@@ -7858,7 +8275,6 @@
"version": "4.0.8", "version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"braces": "^3.0.3", "braces": "^3.0.3",
@@ -7872,7 +8288,6 @@
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=8.6" "node": ">=8.6"
@@ -8037,6 +8452,15 @@
"@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3"
} }
}, },
"node_modules/mustache": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",
"integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",
"license": "MIT",
"bin": {
"mustache": "bin/mustache"
}
},
"node_modules/mute-stream": { "node_modules/mute-stream": {
"version": "0.0.8", "version": "0.0.8",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz",
@@ -8438,6 +8862,15 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/p-finally": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
"integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/p-limit": { "node_modules/p-limit": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
@@ -8470,6 +8903,49 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/p-queue": {
"version": "6.6.2",
"resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",
"integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",
"license": "MIT",
"dependencies": {
"eventemitter3": "^4.0.4",
"p-timeout": "^3.2.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/p-retry": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/p-retry/-/p-retry-7.1.1.tgz",
"integrity": "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w==",
"license": "MIT",
"dependencies": {
"is-network-error": "^1.1.0"
},
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/p-timeout": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",
"integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",
"license": "MIT",
"dependencies": {
"p-finally": "^1.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/p-try": { "node_modules/p-try": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
@@ -8974,7 +9450,6 @@
"version": "1.2.3", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -9313,7 +9788,6 @@
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -9617,6 +10091,12 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/simple-wcswidth": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz",
"integrity": "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==",
"license": "MIT"
},
"node_modules/sisteransi": { "node_modules/sisteransi": {
"version": "1.0.5", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
@@ -10237,7 +10717,6 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"is-number": "^7.0.0" "is-number": "^7.0.0"
@@ -10289,6 +10768,12 @@
"tree-kill": "cli.js" "tree-kill": "cli.js"
} }
}, },
"node_modules/ts-algebra": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
"license": "MIT"
},
"node_modules/ts-api-utils": { "node_modules/ts-api-utils": {
"version": "1.4.3", "version": "1.4.3",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
@@ -11035,6 +11520,21 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/yaml": {
"version": "2.8.2",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",
"integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
},
"node_modules/yargs": { "node_modules/yargs": {
"version": "17.7.2", "version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
@@ -11086,6 +11586,15 @@
"funding": { "funding": {
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
},
"node_modules/zod": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.5.tgz",
"integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
} }
} }
} }

View File

@@ -28,6 +28,9 @@
"dependencies": { "dependencies": {
"@casl/ability": "^6.7.5", "@casl/ability": "^6.7.5",
"@fastify/websocket": "^10.0.1", "@fastify/websocket": "^10.0.1",
"@langchain/core": "^1.1.15",
"@langchain/langgraph": "^1.0.15",
"@langchain/openai": "^1.2.1",
"@nestjs/bullmq": "^10.1.0", "@nestjs/bullmq": "^10.1.0",
"@nestjs/common": "^10.3.0", "@nestjs/common": "^10.3.0",
"@nestjs/config": "^3.1.1", "@nestjs/config": "^3.1.1",
@@ -43,8 +46,10 @@
"bullmq": "^5.1.0", "bullmq": "^5.1.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.1", "class-validator": "^0.14.1",
"deepagents": "^1.5.0",
"ioredis": "^5.3.2", "ioredis": "^5.3.2",
"knex": "^3.1.0", "knex": "^3.1.0",
"langchain": "^1.2.10",
"mysql2": "^3.15.3", "mysql2": "^3.15.3",
"objection": "^3.1.5", "objection": "^3.1.5",
"openai": "^6.15.0", "openai": "^6.15.0",

View File

@@ -20,6 +20,8 @@ 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
@@ -145,12 +147,42 @@ model Account {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
owner User @relation(fields: [ownerId], references: [id]) owner User @relation(fields: [ownerId], references: [id])
contacts Contact[]
@@index([ownerId]) @@index([ownerId])
@@map("accounts") @@map("accounts")
} }
model Contact {
id String @id @default(uuid())
firstName String
lastName String
accountId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId])
@@map("contacts")
}
model ContactDetail {
id String @id @default(uuid())
relatedObjectType String
relatedObjectId String
detailType String
label String?
value String
isPrimary Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([relatedObjectType, relatedObjectId])
@@map("contact_details")
}
// Application Builder // Application Builder
model App { model App {
id String @id @default(uuid()) id String @id @default(uuid())

View File

@@ -0,0 +1,49 @@
import { Body, Controller, Post, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { TenantId } from '../tenant/tenant.decorator';
import { AiAssistantService } from './ai-assistant.service';
import { AiChatRequestDto } from './dto/ai-chat.dto';
import { AiSearchRequestDto } from './dto/ai-search.dto';
@Controller('ai')
@UseGuards(JwtAuthGuard)
export class AiAssistantController {
constructor(private readonly aiAssistantService: AiAssistantService) {}
@Post('chat')
async chat(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Body() payload: AiChatRequestDto,
) {
return this.aiAssistantService.handleChat(
tenantId,
user.userId,
payload.message,
payload.history,
payload.context,
);
}
@Post('search')
async search(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Body() payload: AiSearchRequestDto,
) {
return this.aiAssistantService.searchRecords(
tenantId,
user.userId,
payload,
);
}
@Post('suggest-view-name')
async suggestViewName(
@TenantId() tenantId: string,
@Body() payload: { objectLabel: string; filters: any[]; explanation?: string },
) {
return this.aiAssistantService.suggestViewName(tenantId, payload);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { AiAssistantController } from './ai-assistant.controller';
import { AiAssistantService } from './ai-assistant.service';
import { ObjectModule } from '../object/object.module';
import { PageLayoutModule } from '../page-layout/page-layout.module';
import { TenantModule } from '../tenant/tenant.module';
import { MeilisearchModule } from '../search/meilisearch.module';
@Module({
imports: [ObjectModule, PageLayoutModule, TenantModule, MeilisearchModule],
controllers: [AiAssistantController],
providers: [AiAssistantService],
})
export class AiAssistantModule {}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,111 @@
export interface AiChatMessage {
role: 'user' | 'assistant';
text: string;
}
export interface AiChatContext {
objectApiName?: string;
view?: string;
recordId?: string;
route?: string;
}
export interface AiAssistantReply {
reply: string;
action?: 'create_record' | 'collect_fields' | 'clarify' | 'plan_complete' | 'plan_pending';
missingFields?: string[];
record?: any;
records?: any[]; // Multiple records when plan execution completes
plan?: RecordCreationPlan;
}
// ============================================
// Entity Discovery Types
// ============================================
export interface EntityFieldInfo {
apiName: string;
label: string;
type: string;
isRequired: boolean;
isSystem: boolean;
referenceObject?: string; // For LOOKUP fields, the target entity
description?: string;
}
export interface EntityRelationship {
fieldApiName: string;
fieldLabel: string;
targetEntity: string;
relationshipType: 'lookup' | 'master-detail' | 'polymorphic';
}
export interface EntityInfo {
apiName: string;
label: string;
pluralLabel?: string;
description?: string;
fields: EntityFieldInfo[];
requiredFields: string[]; // Field apiNames that are required
relationships: EntityRelationship[];
}
export interface SystemEntities {
entities: EntityInfo[];
entityByApiName: Record<string, EntityInfo>; // Changed from Map for state serialization
loadedAt: number;
}
// ============================================
// Planning Types
// ============================================
export interface PlannedRecord {
id: string; // Temporary ID for planning (e.g., "temp_account_1")
entityApiName: string;
entityLabel: string;
fields: Record<string, any>;
resolvedFields?: Record<string, any>; // Fields after dependency resolution
missingRequiredFields: string[];
dependsOn: string[]; // IDs of other planned records this depends on
status: 'pending' | 'ready' | 'created' | 'failed';
createdRecordId?: string; // Actual ID after creation
wasExisting?: boolean; // True if record already existed in database
error?: string;
}
export interface RecordCreationPlan {
id: string;
records: PlannedRecord[];
executionOrder: string[]; // Ordered list of planned record IDs
status: 'building' | 'incomplete' | 'ready' | 'executing' | 'completed' | 'failed';
createdRecords: any[];
errors: string[];
}
// ============================================
// State Types
// ============================================
export interface AiAssistantState {
message: string;
messages?: any[]; // BaseMessage[] from langchain - used when invoked by Deep Agent
history?: AiChatMessage[];
context: AiChatContext;
// Entity discovery
systemEntities?: SystemEntities;
// Planning
plan?: RecordCreationPlan;
// Legacy fields (kept for compatibility during transition)
objectDefinition?: any;
pageLayout?: any;
extractedFields?: Record<string, any>;
requiredFields?: string[];
missingFields?: string[];
action?: AiAssistantReply['action'];
record?: any;
reply?: string;
}

View File

@@ -0,0 +1,36 @@
import { Type } from 'class-transformer';
import { IsNotEmpty, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator';
import { AiChatMessageDto } from './ai-chat.message.dto';
export class AiChatContextDto {
@IsOptional()
@IsString()
objectApiName?: string;
@IsOptional()
@IsString()
view?: string;
@IsOptional()
@IsString()
recordId?: string;
@IsOptional()
@IsString()
route?: string;
}
export class AiChatRequestDto {
@IsString()
@IsNotEmpty()
message: string;
@IsOptional()
@IsObject()
context?: AiChatContextDto;
@IsOptional()
@ValidateNested({ each: true })
@Type(() => AiChatMessageDto)
history?: AiChatMessageDto[];
}

View File

@@ -0,0 +1,10 @@
import { IsIn, IsNotEmpty, IsString } from 'class-validator';
export class AiChatMessageDto {
@IsIn(['user', 'assistant'])
role: 'user' | 'assistant';
@IsString()
@IsNotEmpty()
text: string;
}

View File

@@ -0,0 +1,22 @@
import { Type } from 'class-transformer';
import { IsNotEmpty, IsOptional, IsString, IsNumber } from 'class-validator';
export class AiSearchRequestDto {
@IsString()
@IsNotEmpty()
objectApiName: string;
@IsString()
@IsNotEmpty()
query: string;
@IsOptional()
@Type(() => Number)
@IsNumber()
page?: number;
@IsOptional()
@Type(() => Number)
@IsNumber()
pageSize?: number;
}

View File

@@ -10,14 +10,14 @@ export class AppBuilderService {
// Runtime endpoints // Runtime endpoints
async getApps(tenantId: string, userId: string) { async getApps(tenantId: string, userId: string) {
const knex = await this.tenantDbService.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const app = await this.getAppForSetup(tenantId, appSlug); const app = await this.getAppForSetup(tenantId, appSlug);
const page = await AppPage.query(knex).findOne({ const page = await AppPage.query(knex).findOne({

View File

@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { BullModule } from '@nestjs/bullmq';
import { PrismaModule } from './prisma/prisma.module'; import { PrismaModule } from './prisma/prisma.module';
import { TenantModule } from './tenant/tenant.module'; import { TenantModule } from './tenant/tenant.module';
import { AuthModule } from './auth/auth.module'; import { AuthModule } from './auth/auth.module';
@@ -8,12 +9,21 @@ import { ObjectModule } from './object/object.module';
import { AppBuilderModule } from './app-builder/app-builder.module'; 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 { SavedListViewModule } from './saved-list-view/saved-list-view.module';
import { KnowledgeModule } from './knowledge/knowledge.module';
@Module({ @Module({
imports: [ imports: [
ConfigModule.forRoot({ ConfigModule.forRoot({
isGlobal: true, isGlobal: true,
}), }),
BullModule.forRoot({
connection: {
host: process.env.REDIS_HOST || 'platform-redis',
port: parseInt(process.env.REDIS_PORT || '6379', 10),
},
}),
PrismaModule, PrismaModule,
TenantModule, TenantModule,
AuthModule, AuthModule,
@@ -22,6 +32,9 @@ import { VoiceModule } from './voice/voice.module';
AppBuilderModule, AppBuilderModule,
PageLayoutModule, PageLayoutModule,
VoiceModule, VoiceModule,
AiAssistantModule,
SavedListViewModule,
KnowledgeModule,
], ],
}) })
export class AppModule {} export class AppModule {}

View File

@@ -1,15 +1,19 @@
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()
@@ -111,4 +115,15 @@ export class AuthController {
// This endpoint exists for consistency and potential future enhancements // This endpoint exists for consistency and potential future enhancements
return { message: 'Logged out successfully' }; return { message: 'Logged out successfully' };
} }
@UseGuards(JwtAuthGuard)
@Get('me')
async me(@CurrentUser() user: any, @TenantId() tenantId: string) {
// Return the current authenticated user info
return {
id: user.userId,
email: user.email,
tenantId: tenantId || user.tenantId,
};
}
} }

View File

@@ -29,8 +29,8 @@ export class AuthService {
} }
// Otherwise, validate as tenant user // Otherwise, validate as tenant user
const tenantDb = await this.tenantDbService.getTenantKnex(tenantId); const tenantDb = await this.tenantDbService.getTenantKnexById(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.getTenantKnex(tenantId); const tenantDb = await this.tenantDbService.getTenantKnexById(tenantId);
const hashedPassword = await bcrypt.hash(password, 10); const hashedPassword = await bcrypt.hash(password, 10);

View File

@@ -0,0 +1,89 @@
export type SemanticProjectionInput = {
objectApiName: string;
record: Record<string, any>;
objectDefinition?: any;
comments: Array<{ id: string; content: string; author_user_id: string; created_at?: string }>;
};
export type SemanticProjection = {
entityType: string;
entityId: string;
title: string;
narrative: string;
/** Plain text used for embedding — no 'key: value' labels, no comments (chunker handles those separately). */
embeddingNarrative: string;
metadata: Record<string, any>;
sourceSummary: {
includedFieldCount: number;
includedCommentCount: number;
includesComments: boolean;
};
};
export interface SemanticProjectionAdapter {
supports(objectApiName: string): boolean;
buildProjection(input: SemanticProjectionInput): SemanticProjection;
}
const EXCLUDED_FIELDS = new Set([
'id',
'created_at',
'updated_at',
'ownerId',
'owner_id',
'tenantId',
'tenant_id',
]);
export class DefaultSemanticProjectionAdapter implements SemanticProjectionAdapter {
supports(): boolean {
return true;
}
buildProjection(input: SemanticProjectionInput): SemanticProjection {
const fieldEntries = Object.entries(input.record || {}).filter(([key, value]) => {
if (EXCLUDED_FIELDS.has(key)) return false;
if (value === null || value === undefined || value === '') return false;
return ['string', 'number', 'boolean'].includes(typeof value);
});
const title =
input.record?.name ||
input.record?.title ||
input.record?.subject ||
`${input.objectApiName} ${input.record?.id || ''}`.trim();
const fieldNarrative = fieldEntries
.map(([key, value]) => `${key}: ${String(value)}`)
.join('\n');
const commentNarrative = (input.comments || [])
.map((comment, index) => `Comment ${index + 1}: ${comment.content}`)
.join('\n');
const narrative = [fieldNarrative, commentNarrative].filter(Boolean).join('\n\n');
// Plain values only — no 'key:' prefixes. Comments are handled separately by the chunker.
const embeddingNarrative = fieldEntries
.map(([, value]) => String(value))
.join('\n');
return {
entityType: input.objectApiName,
entityId: input.record.id,
title,
narrative,
embeddingNarrative,
metadata: {
objectApiName: input.objectApiName,
hasComments: (input.comments || []).length > 0,
},
sourceSummary: {
includedFieldCount: fieldEntries.length,
includedCommentCount: (input.comments || []).length,
includesComments: (input.comments || []).length > 0,
},
};
}
}

View File

@@ -0,0 +1,24 @@
import { IsNotEmpty, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
export class CreateCommentDto {
@IsString()
@IsNotEmpty()
parentObjectApiName: string;
@IsString()
@IsNotEmpty()
parentRecordId: string;
@IsString()
@MinLength(1)
@MaxLength(10000)
content: string;
}
export class UpdateCommentDto {
@IsOptional()
@IsString()
@MinLength(1)
@MaxLength(10000)
content?: string;
}

View File

@@ -0,0 +1,52 @@
import { IsIn, IsNumber, IsObject, IsOptional, IsString, Max, Min } from 'class-validator';
export const SEMANTIC_LINK_STATUSES = ['suggested', 'approved', 'rejected', 'dismissed'] as const;
export const SEMANTIC_LINK_ORIGINS = ['manual', 'semantic', 'llm', 'hybrid', 'rule_based'] as const;
export class ReviewSemanticLinkDto {
@IsString()
@IsIn(SEMANTIC_LINK_STATUSES)
status: (typeof SEMANTIC_LINK_STATUSES)[number];
}
export class UpsertSemanticLinkDto {
@IsString()
sourceEntityType: string;
@IsString()
sourceEntityId: string;
@IsString()
targetEntityType: string;
@IsString()
targetEntityId: string;
@IsOptional()
@IsString()
linkType?: string;
@IsOptional()
@IsString()
@IsIn(SEMANTIC_LINK_STATUSES)
status?: (typeof SEMANTIC_LINK_STATUSES)[number];
@IsOptional()
@IsString()
@IsIn(SEMANTIC_LINK_ORIGINS)
origin?: (typeof SEMANTIC_LINK_ORIGINS)[number];
@IsOptional()
@IsNumber()
@Min(0)
@Max(1)
confidence?: number;
@IsOptional()
@IsString()
reason?: string;
@IsOptional()
@IsObject()
evidence?: Record<string, any>;
}

View File

@@ -0,0 +1,124 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { TenantId } from '../tenant/tenant.decorator';
import { CreateCommentDto, UpdateCommentDto } from './dto/comment.dto';
import { ReviewSemanticLinkDto } from './dto/semantic-link.dto';
import { CommentService } from './services/comment.service';
import { SemanticOrchestratorService } from './services/semantic-orchestrator.service';
import { SemanticLinkService } from './services/semantic-link.service';
import { TenantDatabaseService } from '../tenant/tenant-database.service';
@Controller('knowledge')
@UseGuards(JwtAuthGuard)
export class KnowledgeController {
constructor(
private readonly commentService: CommentService,
private readonly semanticOrchestratorService: SemanticOrchestratorService,
private readonly semanticLinkService: SemanticLinkService,
private readonly tenantDbService: TenantDatabaseService,
) {}
@Get('comments/:objectApiName/:recordId')
async getComments(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@Param('recordId') recordId: string,
) {
return this.commentService.listComments(tenantId, objectApiName, recordId);
}
@Post('comments')
async createComment(
@TenantId() tenantId: string,
@Body() dto: CreateCommentDto,
@CurrentUser() user: any,
) {
return this.commentService.createComment(tenantId, dto, user.userId);
}
@Patch('comments/:id')
async updateComment(
@TenantId() tenantId: string,
@Param('id') id: string,
@Body() dto: UpdateCommentDto,
@CurrentUser() user: any,
) {
return this.commentService.updateComment(tenantId, id, dto, user.userId);
}
@Delete('comments/:id')
async deleteComment(
@TenantId() tenantId: string,
@Param('id') id: string,
@CurrentUser() user: any,
) {
return this.commentService.deleteComment(tenantId, id, user.userId);
}
@Post('semantic/refresh/:objectApiName/:recordId')
async refreshSemantic(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@Param('recordId') recordId: string,
@CurrentUser() user: any,
) {
return this.semanticOrchestratorService.refreshRecord(
tenantId,
objectApiName,
recordId,
user.userId,
'manual_refresh',
);
}
@Post('semantic/reindex/:objectApiName')
async reindexObject(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@CurrentUser() user: any,
@Query('limit') limit?: string,
) {
const parsedLimit = Number.isFinite(Number(limit)) ? Number(limit) : 250;
return this.semanticOrchestratorService.reindexObject(
tenantId,
objectApiName,
user.userId,
parsedLimit,
);
}
@Get('semantic/links/:objectApiName/:recordId')
async listLinks(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@Param('recordId') recordId: string,
@Query('status') status?: string,
) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
return this.semanticLinkService.listForRecord(knex, objectApiName, recordId, status);
}
@Patch('semantic/links/:id/review')
async reviewLink(
@TenantId() tenantId: string,
@Param('id') id: string,
@Body() dto: ReviewSemanticLinkDto,
@CurrentUser() user: any,
) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
return this.semanticLinkService.reviewLink(knex, id, dto.status, user.userId);
}
}

View File

@@ -0,0 +1,31 @@
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { KnowledgeController } from './knowledge.controller';
import { CommentService } from './services/comment.service';
import { SemanticOrchestratorService } from './services/semantic-orchestrator.service';
import { SemanticChunkerService } from './services/semantic-chunker.service';
import { SemanticLinkService } from './services/semantic-link.service';
import { SemanticRefreshQueueService } from './services/semantic-refresh-queue.service';
import { SemanticRefreshProcessor } from './semantic-refresh.processor';
import { TenantModule } from '../tenant/tenant.module';
import { MeilisearchModule } from '../search/meilisearch.module';
import { SEMANTIC_REFRESH_QUEUE } from './semantic-refresh.constants';
@Module({
imports: [
TenantModule,
MeilisearchModule,
BullModule.registerQueue({ name: SEMANTIC_REFRESH_QUEUE }),
],
controllers: [KnowledgeController],
providers: [
CommentService,
SemanticOrchestratorService,
SemanticChunkerService,
SemanticLinkService,
SemanticRefreshQueueService,
SemanticRefreshProcessor,
],
exports: [SemanticOrchestratorService, SemanticRefreshQueueService],
})
export class KnowledgeModule {}

View File

@@ -0,0 +1,3 @@
export const SEMANTIC_REFRESH_QUEUE = 'semantic-refresh';
export const SEMANTIC_REFRESH_JOB = 'refresh-record';

View File

@@ -0,0 +1,45 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { SemanticOrchestratorService } from './services/semantic-orchestrator.service';
import { SEMANTIC_REFRESH_QUEUE } from './semantic-refresh.constants';
export type SemanticRefreshJobData = {
tenantId: string;
objectApiName: string;
recordId: string;
userId?: string;
trigger: string;
};
@Processor(SEMANTIC_REFRESH_QUEUE)
export class SemanticRefreshProcessor extends WorkerHost {
private readonly logger = new Logger(SemanticRefreshProcessor.name);
constructor(
private readonly semanticOrchestratorService: SemanticOrchestratorService,
) {
super();
}
async process(job: Job<SemanticRefreshJobData>): Promise<void> {
const { tenantId, objectApiName, recordId, userId, trigger } = job.data;
this.logger.log(
`Processing semantic refresh: ${objectApiName}:${recordId} trigger=${trigger}`,
);
try {
await this.semanticOrchestratorService.refreshRecord(
tenantId,
objectApiName,
recordId,
userId,
trigger,
);
} catch (error) {
this.logger.error(
`Semantic refresh failed: ${objectApiName}:${recordId} trigger=${trigger} error=${error.message}`,
);
throw error; // Let BullMQ handle retries
}
}
}

View File

@@ -0,0 +1,115 @@
import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { TenantDatabaseService } from '../../tenant/tenant-database.service';
import { CreateCommentDto, UpdateCommentDto } from '../dto/comment.dto';
import { SemanticRefreshQueueService } from './semantic-refresh-queue.service';
@Injectable()
export class CommentService {
constructor(
private readonly tenantDbService: TenantDatabaseService,
private readonly semanticRefreshQueue: SemanticRefreshQueueService,
) {}
async listComments(tenantId: string, parentObjectApiName: string, parentRecordId: string) {
const knex = await this.getKnex(tenantId);
return knex('comments')
.where({
parent_object_api_name: parentObjectApiName,
parent_record_id: parentRecordId,
})
.orderBy('created_at', 'desc');
}
async createComment(tenantId: string, dto: CreateCommentDto, userId: string) {
const knex = await this.getKnex(tenantId);
const [created] = await knex('comments')
.insert({
parent_object_api_name: dto.parentObjectApiName,
parent_record_id: dto.parentRecordId,
author_user_id: userId,
content: dto.content,
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
})
.returning('*');
console.log(
`[Knowledge] Comment created: ${dto.parentObjectApiName}:${dto.parentRecordId} by ${userId}`,
);
await this.semanticRefreshQueue.enqueue(
tenantId,
dto.parentObjectApiName,
dto.parentRecordId,
userId,
'comment_created',
);
return created;
}
async updateComment(tenantId: string, commentId: string, dto: UpdateCommentDto, userId: string) {
const knex = await this.getKnex(tenantId);
const existing = await knex('comments').where({ id: commentId }).first();
if (!existing) {
throw new NotFoundException('Comment not found');
}
if (existing.author_user_id !== userId) {
throw new ForbiddenException('Only the author can edit this comment');
}
await knex('comments')
.where({ id: commentId })
.update({
...(dto.content ? { content: dto.content } : {}),
updated_at: knex.fn.now(),
});
console.log(
`[Knowledge] Comment updated: ${existing.parent_object_api_name}:${existing.parent_record_id} by ${userId}`,
);
await this.semanticRefreshQueue.enqueue(
tenantId,
existing.parent_object_api_name,
existing.parent_record_id,
userId,
'comment_updated',
);
return knex('comments').where({ id: commentId }).first();
}
async deleteComment(tenantId: string, commentId: string, userId: string) {
const knex = await this.getKnex(tenantId);
const existing = await knex('comments').where({ id: commentId }).first();
if (!existing) {
throw new NotFoundException('Comment not found');
}
if (existing.author_user_id !== userId) {
throw new ForbiddenException('Only the author can delete this comment');
}
await knex('comments').where({ id: commentId }).delete();
console.log(
`[Knowledge] Comment deleted: ${existing.parent_object_api_name}:${existing.parent_record_id} by ${userId}`,
);
await this.semanticRefreshQueue.enqueue(
tenantId,
existing.parent_object_api_name,
existing.parent_record_id,
userId,
'comment_deleted',
);
return { success: true };
}
private async getKnex(tenantId: string) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
return this.tenantDbService.getTenantKnexById(resolvedTenantId);
}
}

View File

@@ -0,0 +1,20 @@
import { SemanticChunkerService } from './semantic-chunker.service';
describe('SemanticChunkerService', () => {
let service: SemanticChunkerService;
beforeEach(() => {
service = new SemanticChunkerService();
});
it('creates chunks from base narrative and comments', () => {
const chunks = service.chunkText('Intro paragraph\n\nSecond paragraph', [
{ id: 'c-1', content: 'Comment body' },
]);
expect(chunks).toHaveLength(3);
expect(chunks[0].sourceKind).toBe('base_record');
expect(chunks[2].sourceKind).toBe('comment');
expect(chunks[2].sourceRefId).toBe('c-1');
});
});

View File

@@ -0,0 +1,71 @@
import { Injectable } from '@nestjs/common';
export type SemanticChunk = {
chunkIndex: number;
sourceKind: 'base_record' | 'comment' | 'mixed';
sourceRefId: string | null;
text: string;
metadata: Record<string, any>;
};
@Injectable()
export class SemanticChunkerService {
chunkText(
baseNarrative: string,
comments: Array<{ id: string; content: string }>,
): SemanticChunk[] {
const chunks: SemanticChunk[] = [];
const baseParts = this.splitText(baseNarrative);
for (const [index, text] of baseParts.entries()) {
chunks.push({
chunkIndex: chunks.length,
sourceKind: 'base_record',
sourceRefId: null,
text,
metadata: { section: 'base', localIndex: index },
});
}
for (const comment of comments || []) {
const commentParts = this.splitText(comment.content);
for (const [index, text] of commentParts.entries()) {
chunks.push({
chunkIndex: chunks.length,
sourceKind: 'comment',
sourceRefId: comment.id,
text,
metadata: { section: 'comment', localIndex: index, commentId: comment.id },
});
}
}
return chunks;
}
private splitText(text: string): string[] {
const normalized = (text || '').trim();
if (!normalized) return [];
const paragraphs = normalized
.split(/\n{2,}/)
.map((part) => part.trim())
.filter(Boolean);
const chunks: string[] = [];
for (const paragraph of paragraphs) {
if (paragraph.length <= 500) {
chunks.push(paragraph);
continue;
}
let cursor = 0;
while (cursor < paragraph.length) {
chunks.push(paragraph.slice(cursor, cursor + 500).trim());
cursor += 500;
}
}
return chunks.filter(Boolean);
}
}

View File

@@ -0,0 +1,20 @@
import { SemanticLinkService } from './semantic-link.service';
describe('SemanticLinkService', () => {
let service: SemanticLinkService;
beforeEach(() => {
service = new SemanticLinkService();
});
it('normalizes undirected pairs in deterministic order', () => {
const normalized = service.normalizeUndirectedPair('Contact', 'b-id', 'Account', 'a-id');
expect(normalized).toEqual({
sourceEntityType: 'Account',
sourceEntityId: 'a-id',
targetEntityType: 'Contact',
targetEntityId: 'b-id',
});
});
});

View File

@@ -0,0 +1,120 @@
import { Injectable, NotFoundException } from '@nestjs/common';
export type SemanticLinkUpsertInput = {
sourceEntityType: string;
sourceEntityId: string;
targetEntityType: string;
targetEntityId: string;
linkType?: string;
status?: string;
origin?: string;
confidence?: number;
reason?: string;
evidence?: Record<string, any>;
suggestedByUserId?: string | null;
};
@Injectable()
export class SemanticLinkService {
normalizeUndirectedPair(
sourceEntityType: string,
sourceEntityId: string,
targetEntityType: string,
targetEntityId: string,
) {
const sourceKey = `${sourceEntityType}:${sourceEntityId}`;
const targetKey = `${targetEntityType}:${targetEntityId}`;
if (sourceKey <= targetKey) {
return {
sourceEntityType,
sourceEntityId,
targetEntityType,
targetEntityId,
};
}
return {
sourceEntityType: targetEntityType,
sourceEntityId: targetEntityId,
targetEntityType: sourceEntityType,
targetEntityId: sourceEntityId,
};
}
async upsertSuggestedLink(knex: any, input: SemanticLinkUpsertInput) {
const normalized = this.normalizeUndirectedPair(
input.sourceEntityType,
input.sourceEntityId,
input.targetEntityType,
input.targetEntityId,
);
const payload = {
source_entity_type: normalized.sourceEntityType,
source_entity_id: normalized.sourceEntityId,
target_entity_type: normalized.targetEntityType,
target_entity_id: normalized.targetEntityId,
link_type: input.linkType || 'related_to',
status: input.status || 'suggested',
origin: input.origin || 'semantic',
confidence: input.confidence ?? 0,
reason: input.reason || null,
evidence: input.evidence ? JSON.stringify(input.evidence) : null,
suggested_by_user_id: input.suggestedByUserId || null,
updated_at: knex.fn.now(),
created_at: knex.fn.now(),
};
await knex('semantic_links')
.insert(payload)
.onConflict([
'source_entity_type',
'source_entity_id',
'target_entity_type',
'target_entity_id',
'link_type',
])
.merge({
status: knex.raw("IF(status = 'approved', status, VALUES(status))"),
origin: payload.origin,
confidence: knex.raw('GREATEST(confidence, VALUES(confidence))'),
reason: payload.reason,
evidence: payload.evidence,
updated_at: knex.fn.now(),
});
}
async listForRecord(knex: any, entityType: string, entityId: string, status?: string) {
const query = knex('semantic_links')
.where((builder: any) => {
builder
.where({ source_entity_type: entityType, source_entity_id: entityId })
.orWhere({ target_entity_type: entityType, target_entity_id: entityId });
})
.orderBy('updated_at', 'desc');
if (status) {
query.andWhere({ status });
}
return query;
}
async reviewLink(knex: any, linkId: string, status: string, reviewerUserId: string) {
const updated = await knex('semantic_links')
.where({ id: linkId })
.update({
status,
reviewed_by_user_id: reviewerUserId,
reviewed_at: knex.fn.now(),
updated_at: knex.fn.now(),
});
if (!updated) {
throw new NotFoundException('Semantic link not found');
}
return knex('semantic_links').where({ id: linkId }).first();
}
}

View File

@@ -0,0 +1,364 @@
import { Injectable, Logger } from '@nestjs/common';
import { TenantDatabaseService } from '../../tenant/tenant-database.service';
import { MeilisearchService } from '../../search/meilisearch.service';
import { getCentralPrisma } from '../../prisma/central-prisma.service';
import { OpenAIConfig } from '../../voice/interfaces/integration-config.interface';
import { randomUUID } from 'crypto';
import {
DefaultSemanticProjectionAdapter,
SemanticProjectionAdapter,
} from '../adapters/semantic-projection.adapter';
import { SemanticChunkerService } from './semantic-chunker.service';
import { SemanticLinkService } from './semantic-link.service';
@Injectable()
export class SemanticOrchestratorService {
private readonly logger = new Logger(SemanticOrchestratorService.name);
private readonly adapters: SemanticProjectionAdapter[] = [new DefaultSemanticProjectionAdapter()];
private readonly defaultEmbeddingModel =
process.env.OPENAI_EMBEDDING_MODEL || 'text-embedding-3-small';
private readonly semanticEmbedderName = 'default';
private readonly MIN_CONFIDENCE_BASE = 0.7;
private readonly MIN_CONFIDENCE_COMMENT = 0.52;
constructor(
private readonly tenantDbService: TenantDatabaseService,
private readonly meilisearchService: MeilisearchService,
private readonly chunkerService: SemanticChunkerService,
private readonly semanticLinkService: SemanticLinkService,
) {}
async refreshRecord(
tenantId: string,
objectApiName: string,
recordId: string,
userId?: string,
trigger: string = 'manual',
) {
this.logger.log(
`Semantic refresh start: ${objectApiName}:${recordId} (trigger=${trigger})`,
);
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const objectDefinition = await knex('object_definitions').where({ apiName: objectApiName }).first();
if (!objectDefinition) {
this.logger.warn(`Object definition ${objectApiName} not found. Skipping semantic refresh.`);
return { skipped: true };
}
const tableName = this.getTableName(objectDefinition);
const record = await knex(tableName).where({ id: recordId }).first();
if (!record) {
this.logger.warn(`Record not found for semantic refresh: ${objectApiName}:${recordId}`);
return { skipped: true };
}
const comments = await knex('comments')
.where({
parent_object_api_name: objectApiName,
parent_record_id: recordId,
})
.orderBy('created_at', 'asc');
this.logger.log(
`Semantic refresh source: ${objectApiName}:${recordId} comments=${comments.length}`,
);
const adapter = this.adapters.find((candidate) => candidate.supports(objectApiName))!;
const projection = adapter.buildProjection({
objectApiName,
record,
objectDefinition,
comments,
});
const documentId = await this.upsertSemanticDocument(knex, projection);
const chunks = this.chunkerService.chunkText(projection.embeddingNarrative, comments);
this.logger.log(
`Semantic refresh chunking: ${objectApiName}:${recordId} chunks=${chunks.length}`,
);
await this.replaceChunks(knex, documentId, chunks);
const openAiConfig = await this.getOpenAiConfig(resolvedTenantId);
const embedderReady = await this.indexChunks(resolvedTenantId, projection, chunks, openAiConfig);
await this.generateSuggestions(
resolvedTenantId,
projection,
chunks,
openAiConfig,
embedderReady,
userId,
trigger,
);
this.logger.log(
`Semantic refresh complete: ${objectApiName}:${recordId} document=${documentId}`,
);
return { documentId, chunkCount: chunks.length };
}
async reindexObject(tenantId: string, objectApiName: string, userId?: string, limit = 250) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const objectDefinition = await knex('object_definitions').where({ apiName: objectApiName }).first();
if (!objectDefinition) {
return { total: 0, processed: 0 };
}
const tableName = this.getTableName(objectDefinition);
const records = await knex(tableName).select('id').limit(limit);
let processed = 0;
for (const record of records) {
await this.refreshRecord(resolvedTenantId, objectApiName, record.id, userId, 'batch_reindex');
processed += 1;
}
return { total: records.length, processed };
}
private async upsertSemanticDocument(knex: any, projection: any): Promise<string> {
const existing = await knex('semantic_documents')
.where({ entity_type: projection.entityType, entity_id: projection.entityId })
.first();
if (existing) {
await knex('semantic_documents')
.where({ id: existing.id })
.update({
title: projection.title,
narrative: projection.narrative,
metadata: JSON.stringify(projection.metadata || {}),
source_summary: JSON.stringify(projection.sourceSummary || {}),
updated_at: knex.fn.now(),
});
return existing.id;
}
const newId = randomUUID();
const [created] = await knex('semantic_documents')
.insert({
id: newId,
entity_type: projection.entityType,
entity_id: projection.entityId,
title: projection.title,
narrative: projection.narrative,
metadata: JSON.stringify(projection.metadata || {}),
source_summary: JSON.stringify(projection.sourceSummary || {}),
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
})
.returning('id');
if (created && typeof created === 'object' && created.id) {
return created.id;
}
// MySQL may return a numeric insert id (often 0 for UUID PKs). Always trust the generated UUID.
return newId;
}
private async replaceChunks(knex: any, documentId: string, chunks: any[]) {
if (!documentId) {
this.logger.warn('Skipping chunk replace: missing semantic document id.');
return;
}
await knex('semantic_chunks').where({ semantic_document_id: documentId }).delete();
if (!chunks.length) return;
await knex('semantic_chunks').insert(
chunks.map((chunk) => ({
semantic_document_id: documentId,
chunk_index: chunk.chunkIndex,
source_kind: chunk.sourceKind,
source_ref_id: chunk.sourceRefId,
text: chunk.text,
metadata: JSON.stringify(chunk.metadata || {}),
created_at: knex.fn.now(),
updated_at: knex.fn.now(),
})),
);
}
private async indexChunks(
tenantId: string,
projection: any,
chunks: any[],
openAiConfig: OpenAIConfig | null,
) {
if (!this.meilisearchService.isEnabled()) {
this.logger.warn('Meilisearch disabled; skipping semantic chunk indexing.');
return false;
}
const indexName = this.meilisearchService.buildSemanticChunkIndexName(tenantId);
let embedderReady = false;
if (openAiConfig?.apiKey) {
embedderReady = await this.meilisearchService.ensureOpenAiEmbedder(indexName, {
embedderName: this.semanticEmbedderName,
apiKey: openAiConfig.apiKey,
model: openAiConfig.embeddingModel || this.defaultEmbeddingModel,
documentTemplate: '{{doc.title}}\n{{doc.text}}',
});
this.logger.log(
`Meilisearch embedder ensured: index=${indexName} model=${openAiConfig.embeddingModel || this.defaultEmbeddingModel}`,
);
} else {
this.logger.warn('OpenAI embedder not configured; semantic search will be lexical only.');
}
this.logger.log(`Indexing semantic chunks: index=${indexName} count=${chunks.length}`);
await this.meilisearchService.upsertDocuments(indexName, chunks.map((chunk) => ({
id: `${projection.entityType}_${projection.entityId}_${chunk.chunkIndex}`,
entityType: projection.entityType,
entityId: projection.entityId,
title: projection.title,
sourceKind: chunk.sourceKind,
sourceRefId: chunk.sourceRefId,
text: chunk.text,
})));
return embedderReady;
}
private async generateSuggestions(
tenantId: string,
projection: any,
chunks: any[],
openAiConfig: OpenAIConfig | null,
embedderReady: boolean,
userId?: string,
trigger: string = 'semantic_refresh',
) {
if (!this.meilisearchService.isEnabled() || !chunks.length) {
this.logger.warn(
`Skipping suggestion generation: meili=${this.meilisearchService.isEnabled()} chunks=${chunks.length}`,
);
return;
}
const indexName = this.meilisearchService.buildSemanticChunkIndexName(tenantId);
// Build query from all chunks (base record + comments), prioritising comments
// since they carry the most distinctive semantic signal.
const commentChunks = chunks.filter((c) => c.sourceKind === 'comment');
const baseChunks = chunks.filter((c) => c.sourceKind !== 'comment');
const orderedChunks = [...commentChunks, ...baseChunks];
const queryText = orderedChunks.map((chunk) => chunk.text).join(' ').slice(0, 1200);
this.logger.log(
`Generating suggestions: index=${indexName} queryLen=${queryText.length} hybrid=${embedderReady}`,
);
const search = await this.meilisearchService.searchIndex(
indexName,
queryText,
20,
// semanticRatio:1.0 = pure vector search, no lexical component that would
// match on shared tokens like 'name:' or 'Comment 1:' across all records.
embedderReady ? { embedder: this.semanticEmbedderName, semanticRatio: 1.0 } : undefined,
);
this.logger.log(
`Meilisearch results: index=${indexName} hits=${search.hits?.length || 0} total=${search.total}`,
);
const candidates = new Map<string, { hit: any; confidence: number }>();
for (const hit of search.hits || []) {
// Skip self
if (hit.entityId === projection.entityId) continue;
const confidence = hit._semanticScore ?? hit._rankingScore ?? 0;
// Use a lower threshold for comment chunks (short, conversational text
// naturally produces lower cosine similarity than structured field values).
const isComment = hit.sourceKind === 'comment';
const threshold = isComment ? this.MIN_CONFIDENCE_COMMENT : this.MIN_CONFIDENCE_BASE;
this.logger.log(
`Suggestion candidate: ${hit.entityType}:${hit.entityId} confidence=${confidence.toFixed(4)} kind=${hit.sourceKind || 'base'} threshold=${threshold} text="${String(hit.text || '').substring(0, 60)}"`,
);
if (confidence < threshold) {
this.logger.log(
`Skipping low-confidence match: ${hit.entityType}:${hit.entityId} confidence=${confidence.toFixed(4)} < ${threshold} (${isComment ? 'comment' : 'base'})`,
);
continue;
}
const key = `${hit.entityType}:${hit.entityId}`;
const existing = candidates.get(key);
if (!existing || confidence > existing.confidence) {
candidates.set(key, { hit, confidence });
}
}
this.logger.log(`Filtered suggestions: ${candidates.size} passed thresholds (base=${this.MIN_CONFIDENCE_BASE}, comment=${this.MIN_CONFIDENCE_COMMENT})`);
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
for (const [key, { hit, confidence }] of candidates.entries()) {
const [targetType, targetId] = key.split(':');
await this.semanticLinkService.upsertSuggestedLink(knex, {
sourceEntityType: projection.entityType,
sourceEntityId: projection.entityId,
targetEntityType: targetType,
targetEntityId: targetId,
linkType: 'related_to',
status: 'suggested',
origin: 'semantic',
confidence,
reason: `Suggested from semantic similarity (${trigger})`,
evidence: {
trigger,
sourceSignals: chunks.slice(0, 2).map((chunk) => ({
sourceKind: chunk.sourceKind,
text: chunk.text.slice(0, 180),
})),
matchedChunks: [{
sourceKind: hit.sourceKind,
text: String(hit.text || '').slice(0, 180),
score: confidence,
}],
},
suggestedByUserId: userId || null,
});
}
}
private getTableName(objectDefinition: any): string {
if (objectDefinition.tableName) return objectDefinition.tableName;
if (objectDefinition.pluralLabel) {
return objectDefinition.pluralLabel.toLowerCase().replace(/[^a-z0-9]+/g, '_');
}
return `${objectDefinition.apiName.toLowerCase()}s`;
}
private async getOpenAiConfig(tenantId: string): Promise<OpenAIConfig | null> {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const centralPrisma = getCentralPrisma();
const tenant = await centralPrisma.tenant.findUnique({
where: { id: resolvedTenantId },
select: { integrationsConfig: true },
});
let config = tenant?.integrationsConfig
? typeof tenant.integrationsConfig === 'string'
? this.tenantDbService.decryptIntegrationsConfig(tenant.integrationsConfig)
: tenant.integrationsConfig
: null;
if (!config?.openai && process.env.OPENAI_API_KEY) {
config = {
...(config || {}),
openai: {
apiKey: process.env.OPENAI_API_KEY,
embeddingModel: this.defaultEmbeddingModel,
},
};
}
if (config?.openai?.apiKey) {
return {
apiKey: config.openai.apiKey,
embeddingModel: config.openai.embeddingModel || this.defaultEmbeddingModel,
};
}
return null;
}
}

View File

@@ -0,0 +1,42 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import {
SEMANTIC_REFRESH_QUEUE,
SEMANTIC_REFRESH_JOB,
} from '../semantic-refresh.constants';
import { SemanticRefreshJobData } from '../semantic-refresh.processor';
@Injectable()
export class SemanticRefreshQueueService {
private readonly logger = new Logger(SemanticRefreshQueueService.name);
constructor(
@InjectQueue(SEMANTIC_REFRESH_QUEUE) private readonly queue: Queue,
) {}
async enqueue(
tenantId: string,
objectApiName: string,
recordId: string,
userId?: string,
trigger: string = 'manual',
): Promise<void> {
const data: SemanticRefreshJobData = {
tenantId,
objectApiName,
recordId,
userId,
trigger,
};
await this.queue.add(SEMANTIC_REFRESH_JOB, data, {
attempts: 3,
backoff: { type: 'exponential', delay: 2000 },
removeOnComplete: 100,
removeOnFail: 50,
});
this.logger.debug(
`Enqueued semantic refresh: ${objectApiName}:${recordId} trigger=${trigger}`,
);
}
}

View File

@@ -1,7 +1,38 @@
import { Model, ModelOptions, QueryContext, snakeCaseMappers } from 'objection'; import { Model, ModelOptions, QueryContext } from 'objection';
export class BaseModel extends Model { export class BaseModel extends Model {
static columnNameMappers = snakeCaseMappers(); /**
* Use a minimal column mapper: keep property names as-is, but handle
* timestamp fields that are stored as created_at/updated_at in the DB.
*/
static columnNameMappers = {
parse(dbRow: Record<string, any>) {
const mapped: Record<string, any> = {};
for (const [key, value] of Object.entries(dbRow || {})) {
if (key === 'created_at') {
mapped.createdAt = value;
} else if (key === 'updated_at') {
mapped.updatedAt = value;
} else {
mapped[key] = value;
}
}
return mapped;
},
format(model: Record<string, any>) {
const mapped: Record<string, any> = {};
for (const [key, value] of Object.entries(model || {})) {
if (key === 'createdAt') {
mapped.created_at = value;
} else if (key === 'updatedAt') {
mapped.updated_at = value;
} else {
mapped[key] = value;
}
}
return mapped;
},
};
id: string; id: string;
createdAt: Date; createdAt: Date;

View File

@@ -0,0 +1,33 @@
import { BaseModel } from './base.model';
export class ContactDetail extends BaseModel {
static tableName = 'contact_details';
id!: string;
relatedObjectType!: 'Account' | 'Contact';
relatedObjectId!: string;
detailType!: string;
label?: string;
value!: string;
isPrimary!: boolean;
// Provide optional relations for each supported parent type.
static relationMappings = {
account: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'account.model',
join: {
from: 'contact_details.relatedObjectId',
to: 'accounts.id',
},
},
contact: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'contact.model',
join: {
from: 'contact_details.relatedObjectId',
to: 'contacts.id',
},
},
};
}

View File

@@ -0,0 +1,30 @@
import { BaseModel } from './base.model';
export class Contact extends BaseModel {
static tableName = 'contacts';
id!: string;
firstName!: string;
lastName!: string;
accountId!: string;
ownerId?: string;
static relationMappings = {
account: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'account.model',
join: {
from: 'contacts.accountId',
to: 'accounts.id',
},
},
owner: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'user.model',
join: {
from: 'contacts.ownerId',
to: 'users.id',
},
},
};
}

View File

@@ -30,6 +30,8 @@ export interface UIMetadata {
step?: number; // For number step?: number; // For number
accept?: string; // For file/image accept?: string; // For file/image
relationDisplayField?: string; // Which field to display for relations relationDisplayField?: string; // Which field to display for relations
relationObjects?: string[]; // For polymorphic relations
relationTypeField?: string; // Field API name storing the selected relation type
// Formatting // Formatting
format?: string; // Date format, number format, etc. format?: string; // Date format, number format, etc.

View File

@@ -1,4 +1,5 @@
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';
@@ -8,6 +9,8 @@ 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;
@@ -22,11 +25,37 @@ 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');

View File

@@ -22,7 +22,9 @@ export interface FieldConfigDTO {
step?: number; step?: number;
accept?: string; accept?: string;
relationObject?: string; relationObject?: string;
relationObjects?: string[];
relationDisplayField?: string; relationDisplayField?: string;
relationTypeField?: string;
format?: string; format?: string;
prefix?: string; prefix?: string;
suffix?: string; suffix?: string;
@@ -43,6 +45,14 @@ export interface ObjectDefinitionDTO {
description?: string; description?: string;
isSystem: boolean; isSystem: boolean;
fields: FieldConfigDTO[]; fields: FieldConfigDTO[];
relatedLists?: Array<{
title: string;
relationName: string;
objectApiName: string;
fields: FieldConfigDTO[];
canCreate?: boolean;
createRoute?: string;
}>;
} }
@Injectable() @Injectable()
@@ -69,6 +79,10 @@ export class FieldMapperService {
const frontendType = this.mapFieldType(field.type); const frontendType = this.mapFieldType(field.type);
const isLookupField = frontendType === 'belongsTo' || field.type.toLowerCase().includes('lookup'); const isLookupField = frontendType === 'belongsTo' || field.type.toLowerCase().includes('lookup');
// Hide 'id' field from list view by default
const isIdField = field.apiName === 'id';
const defaultShowOnList = isIdField ? false : true;
return { return {
id: field.id, id: field.id,
apiName: field.apiName, apiName: field.apiName,
@@ -85,7 +99,7 @@ export class FieldMapperService {
isReadOnly: field.isSystem || uiMetadata.isReadOnly || false, isReadOnly: field.isSystem || uiMetadata.isReadOnly || false,
// View visibility // View visibility
showOnList: uiMetadata.showOnList !== false, showOnList: uiMetadata.showOnList !== undefined ? uiMetadata.showOnList : defaultShowOnList,
showOnDetail: uiMetadata.showOnDetail !== false, showOnDetail: uiMetadata.showOnDetail !== false,
showOnEdit: uiMetadata.showOnEdit !== false && !field.isSystem, showOnEdit: uiMetadata.showOnEdit !== false && !field.isSystem,
sortable: uiMetadata.sortable !== false, sortable: uiMetadata.sortable !== false,
@@ -98,10 +112,12 @@ export class FieldMapperService {
step: uiMetadata.step, step: uiMetadata.step,
accept: uiMetadata.accept, accept: uiMetadata.accept,
relationObject: field.referenceObject, relationObject: field.referenceObject,
relationObjects: uiMetadata.relationObjects,
// For lookup fields, provide default display field if not specified // For lookup fields, provide default display field if not specified
relationDisplayField: isLookupField relationDisplayField: isLookupField
? (uiMetadata.relationDisplayField || 'name') ? (uiMetadata.relationDisplayField || 'name')
: uiMetadata.relationDisplayField, : uiMetadata.relationDisplayField,
relationTypeField: uiMetadata.relationTypeField,
// Formatting // Formatting
format: uiMetadata.format, format: uiMetadata.format,
@@ -129,12 +145,14 @@ export class FieldMapperService {
'boolean': 'boolean', 'boolean': 'boolean',
'date': 'date', 'date': 'date',
'datetime': 'datetime', 'datetime': 'datetime',
'date_time': 'datetime',
'time': 'time', 'time': 'time',
'email': 'email', 'email': 'email',
'url': 'url', 'url': 'url',
'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',
@@ -206,6 +224,17 @@ export class FieldMapperService {
.filter((f: any) => f.isActive !== false) .filter((f: any) => f.isActive !== false)
.sort((a: any, b: any) => (a.displayOrder || 0) - (b.displayOrder || 0)) .sort((a: any, b: any) => (a.displayOrder || 0) - (b.displayOrder || 0))
.map((f: any) => this.mapFieldToDTO(f)), .map((f: any) => this.mapFieldToDTO(f)),
relatedLists: (objectDef.relatedLists || []).map((list: any) => ({
title: list.title,
relationName: list.relationName,
objectApiName: list.objectApiName,
fields: (list.fields || [])
.filter((f: any) => f.isActive !== false)
.map((f: any) => this.mapFieldToDTO(f))
.filter((f: any) => f.showOnList !== false),
canCreate: list.canCreate,
createRoute: list.createRoute,
})),
}; };
} }

View File

@@ -119,6 +119,47 @@ export class DynamicModelFactory {
}; };
} }
// Add additional relation mappings (e.g., hasMany)
for (const relation of relations) {
if (mappings[relation.name]) {
continue;
}
let modelClass: any = relation.targetObjectApiName;
if (getModel) {
const resolvedModel = getModel(relation.targetObjectApiName);
if (resolvedModel) {
modelClass = resolvedModel;
} else {
continue;
}
}
const targetTable = DynamicModelFactory.getTableName(relation.targetObjectApiName);
if (relation.type === 'belongsTo') {
mappings[relation.name] = {
relation: Model.BelongsToOneRelation,
modelClass,
join: {
from: `${tableName}.${relation.fromColumn}`,
to: `${targetTable}.${relation.toColumn}`,
},
};
}
if (relation.type === 'hasMany') {
mappings[relation.name] = {
relation: Model.HasManyRelation,
modelClass,
join: {
from: `${tableName}.${relation.fromColumn}`,
to: `${targetTable}.${relation.toColumn}`,
},
};
}
}
return mappings; return mappings;
} }
@@ -138,7 +179,8 @@ export class DynamicModelFactory {
* Convert a field definition to JSON schema property * Convert a field definition to JSON schema property
*/ */
private static fieldToJsonSchema(field: FieldDefinition): Record<string, any> { private static fieldToJsonSchema(field: FieldDefinition): Record<string, any> {
switch (field.type.toUpperCase()) { const baseSchema = () => {
switch (field.type.toUpperCase()) {
case 'TEXT': case 'TEXT':
case 'STRING': case 'STRING':
case 'EMAIL': case 'EMAIL':
@@ -146,45 +188,57 @@ export class DynamicModelFactory {
case 'PHONE': case 'PHONE':
case 'PICKLIST': case 'PICKLIST':
case 'MULTI_PICKLIST': case 'MULTI_PICKLIST':
return { return {
type: 'string', type: 'string',
...(field.isUnique && { uniqueItems: true }), ...(field.isUnique && { uniqueItems: true }),
}; };
case 'LONG_TEXT': case 'LONG_TEXT':
return { type: 'string' }; return { type: 'string' };
case 'NUMBER': case 'NUMBER':
case 'DECIMAL': case 'DECIMAL':
case 'CURRENCY': case 'CURRENCY':
case 'PERCENT': case 'PERCENT':
return { return {
type: 'number', type: 'number',
...(field.isUnique && { uniqueItems: true }), ...(field.isUnique && { uniqueItems: true }),
}; };
case 'INTEGER': case 'INTEGER':
return { return {
type: 'integer', type: 'integer',
...(field.isUnique && { uniqueItems: true }), ...(field.isUnique && { uniqueItems: true }),
}; };
case 'BOOLEAN': case 'BOOLEAN':
return { type: 'boolean', default: false }; return { type: 'boolean', default: false };
case 'DATE': case 'DATE':
return { type: 'string', format: 'date' }; return { type: 'string', format: 'date' };
case 'DATE_TIME': case 'DATE_TIME':
return { type: 'string', format: 'date-time' }; return { type: 'string', format: 'date-time' };
case 'LOOKUP': case 'LOOKUP':
case 'BELONGS_TO': case 'BELONGS_TO':
return { type: 'string' }; return { type: 'string' };
default: default:
return { type: 'string' }; return { type: 'string' };
}
};
const schema = baseSchema();
// Allow null for non-required fields so optional strings/numbers don't fail validation
if (!field.isRequired) {
return {
anyOf: [schema, { type: 'null' }],
};
} }
return schema;
} }
/** /**
@@ -196,6 +250,9 @@ export class DynamicModelFactory {
.replace(/([A-Z])/g, '_$1') .replace(/([A-Z])/g, '_$1')
.toLowerCase() .toLowerCase()
.replace(/^_/, ''); .replace(/^_/, '');
if (snakeCase.endsWith('y')) {
return `${snakeCase.slice(0, -1)}ies`;
}
return snakeCase.endsWith('s') ? snakeCase : `${snakeCase}s`; return snakeCase.endsWith('s') ? snakeCase : `${snakeCase}s`;
} }
} }

View File

@@ -16,13 +16,17 @@ export class ModelRegistry {
*/ */
registerModel(apiName: string, modelClass: ModelClass<BaseModel>): void { registerModel(apiName: string, modelClass: ModelClass<BaseModel>): void {
this.registry.set(apiName, modelClass); this.registry.set(apiName, modelClass);
const lowerKey = apiName.toLowerCase();
if (lowerKey !== apiName && !this.registry.has(lowerKey)) {
this.registry.set(lowerKey, modelClass);
}
} }
/** /**
* Get a model from the registry * Get a model from the registry
*/ */
getModel(apiName: string): ModelClass<BaseModel> { getModel(apiName: string): ModelClass<BaseModel> {
const model = this.registry.get(apiName); const model = this.registry.get(apiName) || this.registry.get(apiName.toLowerCase());
if (!model) { if (!model) {
throw new Error(`Model for ${apiName} not found in registry`); throw new Error(`Model for ${apiName} not found in registry`);
} }
@@ -33,7 +37,7 @@ export class ModelRegistry {
* Check if a model exists in the registry * Check if a model exists in the registry
*/ */
hasModel(apiName: string): boolean { hasModel(apiName: string): boolean {
return this.registry.has(apiName); return this.registry.has(apiName) || this.registry.has(apiName.toLowerCase());
} }
/** /**
@@ -46,7 +50,8 @@ export class ModelRegistry {
// Returns undefined if model not found (for models not yet registered) // Returns undefined if model not found (for models not yet registered)
const model = DynamicModelFactory.createModel( const model = DynamicModelFactory.createModel(
metadata, metadata,
(apiName: string) => this.registry.get(apiName), (apiName: string) =>
this.registry.get(apiName) || this.registry.get(apiName.toLowerCase()),
); );
this.registerModel(metadata.apiName, model); this.registerModel(metadata.apiName, model);
return model; return model;

View File

@@ -171,6 +171,25 @@ export class ModelService {
} }
} }
if (objectMetadata.relations) {
for (const relation of objectMetadata.relations) {
if (relation.targetObjectApiName) {
try {
await this.ensureModelWithDependencies(
tenantId,
relation.targetObjectApiName,
fetchMetadata,
visited,
);
} catch (error) {
this.logger.debug(
`Skipping registration of related model ${relation.targetObjectApiName}: ${error.message}`
);
}
}
}
}
// Now create and register this model (all dependencies are ready) // Now create and register this model (all dependencies are ready)
await this.createModelForObject(tenantId, objectMetadata); await this.createModelForObject(tenantId, objectMetadata);
this.logger.log(`Registered model for ${objectApiName} in tenant ${tenantId}`); this.logger.log(`Registered model for ${objectApiName} in tenant ${tenantId}`);

View File

@@ -9,9 +9,11 @@ import { MigrationModule } from '../migration/migration.module';
import { RbacModule } from '../rbac/rbac.module'; import { RbacModule } from '../rbac/rbac.module';
import { ModelRegistry } from './models/model.registry'; import { ModelRegistry } from './models/model.registry';
import { ModelService } from './models/model.service'; import { ModelService } from './models/model.service';
import { MeilisearchModule } from '../search/meilisearch.module';
import { KnowledgeModule } from '../knowledge/knowledge.module';
@Module({ @Module({
imports: [TenantModule, MigrationModule, RbacModule], imports: [TenantModule, MigrationModule, RbacModule, MeilisearchModule, KnowledgeModule],
providers: [ providers: [
ObjectService, ObjectService,
SchemaManagementService, SchemaManagementService,

File diff suppressed because it is too large Load Diff

View File

@@ -95,4 +95,49 @@ export class RuntimeObjectController {
user.userId, user.userId,
); );
} }
@Post(':objectApiName/records/bulk-delete')
async deleteRecords(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@Body() body: { recordIds?: string[]; ids?: string[] },
@CurrentUser() user: any,
) {
const recordIds: string[] = body?.recordIds || body?.ids || [];
return this.objectService.deleteRecords(
tenantId,
objectApiName,
recordIds,
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,
);
}
} }

View File

@@ -15,7 +15,11 @@ export class SchemaManagementService {
objectDefinition: ObjectDefinition, objectDefinition: ObjectDefinition,
fields: FieldDefinition[], fields: FieldDefinition[],
) { ) {
const tableName = this.getTableName(objectDefinition.apiName); const tableName = this.getTableName(
objectDefinition.apiName,
objectDefinition.label,
objectDefinition.pluralLabel,
);
// Check if table already exists // Check if table already exists
const exists = await knex.schema.hasTable(tableName); const exists = await knex.schema.hasTable(tableName);
@@ -44,8 +48,10 @@ export class SchemaManagementService {
knex: Knex, knex: Knex,
objectApiName: string, objectApiName: string,
field: FieldDefinition, field: FieldDefinition,
objectLabel?: string,
pluralLabel?: string,
) { ) {
const tableName = this.getTableName(objectApiName); const tableName = this.getTableName(objectApiName, objectLabel, pluralLabel);
await knex.schema.alterTable(tableName, (table) => { await knex.schema.alterTable(tableName, (table) => {
this.addFieldColumn(table, field); this.addFieldColumn(table, field);
@@ -61,8 +67,10 @@ export class SchemaManagementService {
knex: Knex, knex: Knex,
objectApiName: string, objectApiName: string,
fieldApiName: string, fieldApiName: string,
objectLabel?: string,
pluralLabel?: string,
) { ) {
const tableName = this.getTableName(objectApiName); const tableName = this.getTableName(objectApiName, objectLabel, pluralLabel);
await knex.schema.alterTable(tableName, (table) => { await knex.schema.alterTable(tableName, (table) => {
table.dropColumn(fieldApiName); table.dropColumn(fieldApiName);
@@ -71,11 +79,44 @@ export class SchemaManagementService {
this.logger.log(`Removed field ${fieldApiName} from table ${tableName}`); this.logger.log(`Removed field ${fieldApiName} from table ${tableName}`);
} }
/**
* Alter a field in an existing object table
* Handles safe updates like changing NOT NULL or constraints
* Warns about potentially destructive operations
*/
async alterFieldInTable(
knex: Knex,
objectApiName: string,
fieldApiName: string,
field: FieldDefinition,
objectLabel?: string,
pluralLabel?: string,
options?: {
skipTypeChange?: boolean; // Skip if type change would lose data
},
) {
const tableName = this.getTableName(objectApiName, objectLabel, pluralLabel);
const skipTypeChange = options?.skipTypeChange ?? true;
await knex.schema.alterTable(tableName, (table) => {
// Drop the existing column and recreate with new definition
// Note: This approach works for metadata changes, but type changes may need data migration
table.dropColumn(fieldApiName);
});
// Recreate the column with new definition
await knex.schema.alterTable(tableName, (table) => {
this.addFieldColumn(table, field);
});
this.logger.log(`Altered field ${fieldApiName} in table ${tableName}`);
}
/** /**
* Drop an object table * Drop an object table
*/ */
async dropObjectTable(knex: Knex, objectApiName: string) { async dropObjectTable(knex: Knex, objectApiName: string, objectLabel?: string, pluralLabel?: string) {
const tableName = this.getTableName(objectApiName); const tableName = this.getTableName(objectApiName, objectLabel, pluralLabel);
await knex.schema.dropTableIfExists(tableName); await knex.schema.dropTableIfExists(tableName);
@@ -94,15 +135,30 @@ export class SchemaManagementService {
let column: Knex.ColumnBuilder; let column: Knex.ColumnBuilder;
switch (field.type) { switch (field.type) {
// Text types
case 'String': case 'String':
case 'TEXT':
case 'EMAIL':
case 'PHONE':
case 'URL':
column = table.string(columnName, field.length || 255); column = table.string(columnName, field.length || 255);
break; break;
case 'Text': case 'Text':
case 'LONG_TEXT':
column = table.text(columnName); column = table.text(columnName);
break; break;
case 'PICKLIST':
case 'MULTI_PICKLIST':
column = table.string(columnName, 255);
break;
// Numeric types
case 'Number': case 'Number':
case 'NUMBER':
case 'CURRENCY':
case 'PERCENT':
if (field.scale && field.scale > 0) { if (field.scale && field.scale > 0) {
column = table.decimal( column = table.decimal(
columnName, columnName,
@@ -115,18 +171,28 @@ export class SchemaManagementService {
break; break;
case 'Boolean': case 'Boolean':
case 'BOOLEAN':
column = table.boolean(columnName).defaultTo(false); column = table.boolean(columnName).defaultTo(false);
break; break;
// Date types
case 'Date': case 'Date':
case 'DATE':
column = table.date(columnName); column = table.date(columnName);
break; break;
case 'DateTime': case 'DateTime':
case 'DATE_TIME':
column = table.datetime(columnName); column = table.datetime(columnName);
break; break;
case 'TIME':
column = table.time(columnName);
break;
// Relationship types
case 'Reference': case 'Reference':
case 'LOOKUP':
column = table.uuid(columnName); column = table.uuid(columnName);
if (field.referenceObject) { if (field.referenceObject) {
const refTableName = this.getTableName(field.referenceObject); const refTableName = this.getTableName(field.referenceObject);
@@ -134,19 +200,30 @@ export class SchemaManagementService {
} }
break; break;
// Email (legacy)
case 'Email': case 'Email':
column = table.string(columnName, 255); column = table.string(columnName, 255);
break; break;
// Phone (legacy)
case 'Phone': case 'Phone':
column = table.string(columnName, 50); column = table.string(columnName, 50);
break; break;
// Url (legacy)
case 'Url': case 'Url':
column = table.string(columnName, 255); column = table.string(columnName, 255);
break; break;
// File types
case 'FILE':
case 'IMAGE':
column = table.text(columnName); // Store file path or URL
break;
// JSON
case 'Json': case 'Json':
case 'JSON':
column = table.json(columnName); column = table.json(columnName);
break; break;
@@ -174,16 +251,35 @@ export class SchemaManagementService {
/** /**
* Convert object API name to table name (convert to snake_case, pluralize) * Convert object API name to table name (convert to snake_case, pluralize)
*/ */
private getTableName(apiName: string): string { private getTableName(apiName: string, objectLabel?: string, pluralLabel?: string): string {
// Convert PascalCase to snake_case const toSnakePlural = (source: string): string => {
const snakeCase = apiName const cleaned = source.replace(/[\s-]+/g, '_');
.replace(/([A-Z])/g, '_$1') const snake = cleaned
.toLowerCase() .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
.replace(/^_/, ''); .replace(/__+/g, '_')
.toLowerCase()
.replace(/^_/, '');
// Simple pluralization (append 's' if not already plural) if (snake.endsWith('y')) return `${snake.slice(0, -1)}ies`;
// In production, use a proper pluralization library if (snake.endsWith('s')) return snake;
return snakeCase.endsWith('s') ? snakeCase : `${snakeCase}s`; return `${snake}s`;
};
const fromApi = toSnakePlural(apiName);
const fromLabel = objectLabel ? toSnakePlural(objectLabel) : null;
const fromPlural = pluralLabel ? toSnakePlural(pluralLabel) : null;
if (fromLabel && fromLabel.includes('_') && !fromApi.includes('_')) {
return fromLabel;
}
if (fromPlural && fromPlural.includes('_') && !fromApi.includes('_')) {
return fromPlural;
}
if (fromLabel && fromLabel !== fromApi) return fromLabel;
if (fromPlural && fromPlural !== fromApi) return fromPlural;
return fromApi;
} }
/** /**

View File

@@ -4,6 +4,7 @@ import {
Post, Post,
Patch, Patch,
Put, Put,
Delete,
Param, Param,
Body, Body,
UseGuards, UseGuards,
@@ -72,6 +73,35 @@ export class SetupObjectController {
return this.fieldMapperService.mapFieldToDTO(field); return this.fieldMapperService.mapFieldToDTO(field);
} }
@Put(':objectApiName/fields/:fieldApiName')
async updateFieldDefinition(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@Param('fieldApiName') fieldApiName: string,
@Body() data: any,
) {
const field = await this.objectService.updateFieldDefinition(
tenantId,
objectApiName,
fieldApiName,
data,
);
return this.fieldMapperService.mapFieldToDTO(field);
}
@Delete(':objectApiName/fields/:fieldApiName')
async deleteFieldDefinition(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@Param('fieldApiName') fieldApiName: string,
) {
return this.objectService.deleteFieldDefinition(
tenantId,
objectApiName,
fieldApiName,
);
}
@Patch(':objectApiName') @Patch(':objectApiName')
async updateObjectDefinition( async updateObjectDefinition(
@TenantId() tenantId: string, @TenantId() tenantId: string,

View File

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

View File

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

View File

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

View File

@@ -180,8 +180,9 @@ export class AbilityFactory {
} }
} }
// Field permissions exist but this field is not explicitly granted → deny // No explicit rule for this field but other field permissions exist.
return false; // Default to allow so new fields don't get silently stripped and fail validation.
return true;
} }
/** /**

View File

@@ -45,7 +45,11 @@ export class RecordSharingController {
} }
// Get the record to check ownership // Get the record to check ownership
const tableName = this.getTableName(objectDef.apiName); const tableName = this.getTableName(
objectDef.apiName,
objectDef.label,
objectDef.pluralLabel,
);
const record = await knex(tableName) const record = await knex(tableName)
.where({ id: recordId }) .where({ id: recordId })
.first(); .first();
@@ -109,7 +113,11 @@ export class RecordSharingController {
} }
// Get the record to check ownership // Get the record to check ownership
const tableName = this.getTableName(objectDef.apiName); const tableName = this.getTableName(
objectDef.apiName,
objectDef.label,
objectDef.pluralLabel,
);
const record = await knex(tableName) const record = await knex(tableName)
.where({ id: recordId }) .where({ id: recordId })
.first(); .first();
@@ -207,7 +215,11 @@ export class RecordSharingController {
} }
// Get the record to check ownership // Get the record to check ownership
const tableName = this.getTableName(objectDef.apiName); const tableName = this.getTableName(
objectDef.apiName,
objectDef.label,
objectDef.pluralLabel,
);
const record = await knex(tableName) const record = await knex(tableName)
.where({ id: recordId }) .where({ id: recordId })
.first(); .first();
@@ -305,20 +317,34 @@ export class RecordSharingController {
return false; return false;
} }
private getTableName(apiName: string): string { private getTableName(apiName: string, objectLabel?: string, pluralLabel?: string): string {
// Convert CamelCase to snake_case and pluralize const toSnakePlural = (source: string): string => {
const snakeCase = apiName const cleaned = source.replace(/[\s-]+/g, '_');
.replace(/([A-Z])/g, '_$1') const snake = cleaned
.toLowerCase() .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
.replace(/^_/, ''); .replace(/__+/g, '_')
.toLowerCase()
// Simple pluralization .replace(/^_/, '');
if (snakeCase.endsWith('y')) {
return snakeCase.slice(0, -1) + 'ies'; if (snake.endsWith('y')) return `${snake.slice(0, -1)}ies`;
} else if (snakeCase.endsWith('s')) { if (snake.endsWith('s')) return snake;
return snakeCase + 'es'; return `${snake}s`;
} else { };
return snakeCase + 's';
const fromApi = toSnakePlural(apiName);
const fromLabel = objectLabel ? toSnakePlural(objectLabel) : null;
const fromPlural = pluralLabel ? toSnakePlural(pluralLabel) : null;
if (fromLabel && fromLabel.includes('_') && !fromApi.includes('_')) {
return fromLabel;
} }
if (fromPlural && fromPlural.includes('_') && !fromApi.includes('_')) {
return fromPlural;
}
if (fromLabel && fromLabel !== fromApi) return fromLabel;
if (fromPlural && fromPlural !== fromApi) return fromPlural;
return fromApi;
} }
} }

View File

@@ -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 }, @Body() data: { email: string; password: string; firstName?: string; lastName?: string; alias?: 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,6 +52,7 @@ 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,
}); });
@@ -62,7 +63,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 }, @Body() data: { email?: string; password?: string; firstName?: string; lastName?: string; alias?: 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);
@@ -72,6 +73,7 @@ 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) {

View File

@@ -0,0 +1,53 @@
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;
}

View File

@@ -0,0 +1,92 @@
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);
}
}

View File

@@ -0,0 +1,12 @@
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 {}

View File

@@ -0,0 +1,264 @@
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,
};
}
}

View File

@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { MeilisearchService } from './meilisearch.service';
@Module({
providers: [MeilisearchService],
exports: [MeilisearchService],
})
export class MeilisearchModule {}

View File

@@ -0,0 +1,483 @@
import { Injectable, Logger } from '@nestjs/common';
import * as http from 'http';
import * as https from 'https';
type MeiliConfig = {
host: string;
apiKey?: string;
indexPrefix: string;
};
type HybridSearchOptions = {
embedder: string;
semanticRatio?: number;
};
type OpenAiEmbedderConfig = {
embedderName: string;
apiKey: string;
model: string;
documentTemplate: string;
};
@Injectable()
export class MeilisearchService {
private readonly logger = new Logger(MeilisearchService.name);
private readonly embedderCache = new Map<string, string>();
private vectorStoreEnabled = false;
isEnabled(): boolean {
return Boolean(this.getConfig());
}
async searchRecord(
tenantId: string,
objectApiName: string,
query: string,
displayField?: string,
): Promise<{ id: string; hit: any } | null> {
const config = this.getConfig();
if (!config) return null;
const indexName = this.buildIndexName(config, tenantId, objectApiName);
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/search`;
console.log('querying Meilisearch index:', { indexName, query, displayField });
try {
const response = await this.requestJson('POST', url, {
q: query,
limit: 5,
}, this.buildHeaders(config));
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(
`Meilisearch query failed for index ${indexName}: ${response.status}`,
);
return null;
}
const hits = Array.isArray(response.body?.hits) ? response.body.hits : [];
if (hits.length === 0) return null;
if (displayField) {
const loweredQuery = query.toLowerCase();
const exactMatch = hits.find((hit: any) => {
const value = hit?.[displayField];
return value && String(value).toLowerCase() === loweredQuery;
});
if (exactMatch?.id) {
return { id: exactMatch.id, hit: exactMatch };
}
}
const match = hits[0];
if (match?.id) {
return { id: match.id, hit: match };
}
} catch (error) {
this.logger.warn(`Meilisearch lookup failed: ${error.message}`);
}
return null;
}
async searchRecords(
tenantId: string,
objectApiName: string,
query: string,
options?: { limit?: number; offset?: number },
): Promise<{ hits: any[]; total: number }> {
const config = this.getConfig();
if (!config) return { hits: [], total: 0 };
const indexName = this.buildIndexName(config, tenantId, objectApiName);
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/search`;
const limit = Number.isFinite(Number(options?.limit)) ? Number(options?.limit) : 20;
const offset = Number.isFinite(Number(options?.offset)) ? Number(options?.offset) : 0;
try {
const response = await this.requestJson('POST', url, {
q: query,
limit,
offset,
}, this.buildHeaders(config));
console.log('Meilisearch response body:', response.body);
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(
`Meilisearch query failed for index ${indexName}: ${response.status}`,
);
return { hits: [], total: 0 };
}
const hits = Array.isArray(response.body?.hits) ? response.body.hits : [];
const total =
response.body?.estimatedTotalHits ??
response.body?.nbHits ??
hits.length;
return { hits, total };
} catch (error) {
this.logger.warn(`Meilisearch query failed: ${error.message}`);
return { hits: [], total: 0 };
}
}
async upsertRecord(
tenantId: string,
objectApiName: string,
record: Record<string, any>,
fieldsToIndex: string[],
): Promise<void> {
const config = this.getConfig();
if (!config || !record?.id) return;
const indexName = this.buildIndexName(config, tenantId, objectApiName);
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/documents?primaryKey=id`;
const document = this.pickRecordFields(record, fieldsToIndex);
try {
const response = await this.requestJson('POST', url, [document], this.buildHeaders(config));
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(
`Meilisearch upsert failed for index ${indexName}: ${response.status}`,
);
}
} catch (error) {
this.logger.warn(`Meilisearch upsert failed: ${error.message}`);
}
}
async deleteRecord(
tenantId: string,
objectApiName: string,
recordId: string,
): Promise<void> {
const config = this.getConfig();
if (!config || !recordId) return;
const indexName = this.buildIndexName(config, tenantId, objectApiName);
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/documents/${encodeURIComponent(recordId)}`;
try {
const response = await this.requestJson('DELETE', url, undefined, this.buildHeaders(config));
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(
`Meilisearch delete failed for index ${indexName}: ${response.status}`,
);
}
} catch (error) {
this.logger.warn(`Meilisearch delete failed: ${error.message}`);
}
}
buildSemanticChunkIndexName(tenantId: string): string {
const config = this.getConfig();
const prefix = config?.indexPrefix || 'tenant_';
return `${prefix}${tenantId}_semantic_chunks`.toLowerCase();
}
async upsertDocuments(indexName: string, documents: Record<string, any>[]): Promise<void> {
const config = this.getConfig();
if (!config || !Array.isArray(documents) || documents.length === 0) return;
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/documents?primaryKey=id`;
try {
const response = await this.requestJson('POST', url, documents, this.buildHeaders(config));
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(`Meilisearch document upsert failed for index ${indexName}: ${response.status}`);
return;
}
// Meilisearch indexes (and embeds) documents asynchronously. Wait for the task
// to complete so callers can immediately search and see the new documents.
const taskUid = response.body?.taskUid ?? response.body?.uid;
if (Number.isFinite(Number(taskUid))) {
const succeeded = await this.waitForTask(config, Number(taskUid), 30000);
if (!succeeded) {
this.logger.warn(`Meilisearch indexing task did not succeed within timeout: taskUid=${taskUid} index=${indexName}`);
}
}
} catch (error) {
this.logger.warn(`Meilisearch document upsert failed: ${error.message}`);
}
}
async searchIndex(
indexName: string,
query: string,
limit = 20,
hybrid?: HybridSearchOptions,
): Promise<{ hits: any[]; total: number }> {
const config = this.getConfig();
if (!config) return { hits: [], total: 0 };
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/search`;
try {
const response = await this.requestJson(
'POST',
url,
{
q: query,
limit,
showRankingScore: true,
...(hybrid ? { hybrid, showRankingScoreDetails: true } : {}),
},
this.buildHeaders(config),
);
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(
`Meilisearch search failed for index ${indexName}: ${response.status}`,
);
this.logger.warn(
`Meilisearch search payload: ${JSON.stringify({ q: query, limit, hybrid })}`,
);
this.logger.warn(
`Meilisearch search error body: ${JSON.stringify(response.body)}`,
);
// If hybrid is invalid (embedder missing), retry once without hybrid
if (hybrid && response.body?.code === 'invalid_embedder') {
const fallback = await this.requestJson(
'POST',
url,
{ q: query, limit },
this.buildHeaders(config),
);
if (this.isSuccessStatus(fallback.status)) {
const hits = Array.isArray(fallback.body?.hits) ? fallback.body.hits : [];
const total =
fallback.body?.estimatedTotalHits ?? fallback.body?.nbHits ?? hits.length;
this.logger.warn(
`Meilisearch hybrid failed; fell back to lexical search for index ${indexName}.`,
);
return { hits, total };
}
}
return { hits: [], total: 0 };
}
const hits = Array.isArray(response.body?.hits) ? response.body.hits : [];
const total = response.body?.estimatedTotalHits ?? response.body?.nbHits ?? hits.length;
return { hits, total };
} catch (error) {
this.logger.warn(`Meilisearch search failed: ${error.message}`);
return { hits: [], total: 0 };
}
}
private getConfig(): MeiliConfig | null {
const host = process.env.MEILI_HOST || process.env.MEILISEARCH_HOST;
if (!host) return null;
const trimmedHost = host.replace(/\/+$/, '');
const apiKey = process.env.MEILI_API_KEY || process.env.MEILISEARCH_API_KEY;
const indexPrefix = process.env.MEILI_INDEX_PREFIX || 'tenant_';
return { host: trimmedHost, apiKey, indexPrefix };
}
private buildIndexName(config: MeiliConfig, tenantId: string, objectApiName: string): string {
return `${config.indexPrefix}${tenantId}_${objectApiName}`.toLowerCase();
}
private buildHeaders(config: MeiliConfig): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (config.apiKey) {
headers['X-Meili-API-Key'] = config.apiKey;
headers.Authorization = `Bearer ${config.apiKey}`;
}
return headers;
}
private pickRecordFields(record: Record<string, any>, fields: string[]): Record<string, any> {
const document: Record<string, any> = { id: record.id };
for (const field of fields) {
if (record[field] !== undefined) {
document[field] = record[field];
}
}
return document;
}
private isSuccessStatus(status: number): boolean {
return status >= 200 && status < 300;
}
private requestJson(
method: 'POST' | 'DELETE' | 'PATCH' | 'GET',
url: string,
payload: any,
headers: Record<string, string>,
): Promise<{ status: number; body: any }> {
return new Promise((resolve, reject) => {
const parsedUrl = new URL(url);
const client = parsedUrl.protocol === 'https:' ? https : http;
const request = client.request(
{
method,
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: `${parsedUrl.pathname}${parsedUrl.search}`,
headers,
},
(response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
if (!data) {
resolve({ status: response.statusCode || 0, body: null });
return;
}
try {
const body = JSON.parse(data);
resolve({ status: response.statusCode || 0, body });
} catch (error) {
reject(error);
}
});
},
);
request.on('error', reject);
if (payload !== undefined && method !== 'GET') {
request.write(JSON.stringify(payload));
}
request.end();
});
}
private async enableVectorStore(): Promise<void> {
// Temporarily disabled to avoid the overhead of checking on every save.
// Re-enable by removing the early return below.
return;
if (this.vectorStoreEnabled) return; // eslint-disable-line no-unreachable
const meiliConfig = this.getConfig();
if (!meiliConfig) return;
const url = `${meiliConfig.host}/experimental-features`;
try {
const response = await this.requestJson(
'PATCH',
url,
{ vectorStore: true },
this.buildHeaders(meiliConfig),
);
if (this.isSuccessStatus(response.status)) {
this.vectorStoreEnabled = true;
this.logger.log('Meilisearch vector store experimental feature enabled');
} else {
this.logger.warn(
`Failed to enable Meilisearch vector store: ${response.status} ${JSON.stringify(response.body)}`,
);
}
} catch (error) {
this.logger.warn(`Failed to enable Meilisearch vector store: ${error.message}`);
}
}
async ensureOpenAiEmbedder(
indexName: string,
config: OpenAiEmbedderConfig,
): Promise<boolean> {
const meiliConfig = this.getConfig();
if (!meiliConfig || !config?.apiKey) return false;
await this.enableVectorStore();
const signature = JSON.stringify({
embedderName: config.embedderName,
model: config.model,
documentTemplate: config.documentTemplate,
apiKey: config.apiKey,
});
const cacheKey = `${indexName}:${config.embedderName}`;
if (this.embedderCache.get(cacheKey) === signature) {
return true;
}
const url = `${meiliConfig.host}/indexes/${encodeURIComponent(indexName)}/settings/embedders`;
try {
const response = await this.requestJson(
'PATCH',
url,
{
[config.embedderName]: {
source: 'openAi',
model: config.model,
apiKey: config.apiKey,
documentTemplate: config.documentTemplate,
},
},
this.buildHeaders(meiliConfig),
);
if (!this.isSuccessStatus(response.status)) {
this.logger.warn(
`Meilisearch embedder update failed for index ${indexName}: ${response.status}`,
);
this.logger.warn(
`Meilisearch embedder error body: ${JSON.stringify(response.body)}`,
);
return false;
}
const taskUid = response.body?.taskUid ?? response.body?.uid;
if (Number.isFinite(Number(taskUid))) {
const succeeded = await this.waitForTask(meiliConfig, Number(taskUid), 8000);
if (!succeeded) {
this.logger.warn(`Meilisearch embedder task did not succeed: ${taskUid}`);
return false;
}
}
const hasEmbedder = await this.hasEmbedder(meiliConfig, indexName, config.embedderName);
if (!hasEmbedder) {
this.logger.warn(`Meilisearch embedder missing after update: ${config.embedderName}`);
return false;
}
this.embedderCache.set(cacheKey, signature);
return true;
} catch (error) {
this.logger.warn(`Meilisearch embedder update failed: ${error.message}`);
return false;
}
}
private async waitForTask(
config: MeiliConfig,
taskUid: number,
timeoutMs = 8000,
): Promise<boolean> {
const url = `${config.host}/tasks/${taskUid}`;
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const response = await this.requestJson('GET', url, undefined, this.buildHeaders(config));
if (!this.isSuccessStatus(response.status)) {
return false;
}
const status = response.body?.status;
if (status === 'succeeded') return true;
if (status === 'failed' || status === 'canceled') {
this.logger.warn(`Meilisearch task ${taskUid} failed: ${JSON.stringify(response.body?.error)}`);
return false;
}
await new Promise((resolve) => setTimeout(resolve, 300));
}
return false;
}
private async hasEmbedder(
config: MeiliConfig,
indexName: string,
embedderName: string,
): Promise<boolean> {
const url = `${config.host}/indexes/${encodeURIComponent(indexName)}/settings/embedders`;
const response = await this.requestJson('GET', url, undefined, this.buildHeaders(config));
if (!this.isSuccessStatus(response.status)) {
return false;
}
const embedders = response.body || {};
return Boolean(embedders && embedders[embedderName]);
}
}

View File

@@ -16,26 +16,45 @@ 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() domain: string) { async getIntegrationsConfig(@TenantId() tenantIdentifier: string) {
const centralPrisma = getCentralPrisma(); const tenant = await this.findTenant(tenantIdentifier);
// Look up tenant by domain
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
if (!domainRecord?.tenant || !domainRecord.tenant.integrationsConfig) { if (!tenant || !tenant.integrationsConfig) {
return { data: null }; return { data: null };
} }
// Decrypt the config // Decrypt the config
const config = this.tenantDbService.decryptIntegrationsConfig( const config = this.tenantDbService.decryptIntegrationsConfig(
domainRecord.tenant.integrationsConfig as any, tenant.integrationsConfig as any,
); );
// Return config with sensitive fields masked // Return config with sensitive fields masked
@@ -49,31 +68,26 @@ export class TenantController {
*/ */
@Put('integrations') @Put('integrations')
async updateIntegrationsConfig( async updateIntegrationsConfig(
@TenantId() domain: string, @TenantId() tenantIdentifier: string,
@Body() body: { integrationsConfig: any }, @Body() body: { integrationsConfig: any },
) { ) {
const { integrationsConfig } = body; const { integrationsConfig } = body;
if (!domain) { if (!tenantIdentifier) {
throw new Error('Domain is missing from request'); throw new Error('Tenant identifier is missing from request');
} }
// Look up tenant by domain const tenant = await this.findTenant(tenantIdentifier);
const centralPrisma = getCentralPrisma();
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
if (!domainRecord?.tenant) { if (!tenant) {
throw new Error(`Tenant with domain ${domain} not found`); throw new Error(`Tenant with identifier ${tenantIdentifier} 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 (domainRecord.tenant.integrationsConfig) { if (tenant.integrationsConfig) {
const existingConfig = this.tenantDbService.decryptIntegrationsConfig( const existingConfig = this.tenantDbService.decryptIntegrationsConfig(
domainRecord.tenant.integrationsConfig as any, tenant.integrationsConfig as any,
); );
// Replace masked values with actual values from existing config // Replace masked values with actual values from existing config
@@ -86,8 +100,9 @@ export class TenantController {
); );
// Update in database // Update in database
const centralPrisma = getCentralPrisma();
await centralPrisma.tenant.update({ await centralPrisma.tenant.update({
where: { id: domainRecord.tenant.id }, where: { id: tenant.id },
data: { data: {
integrationsConfig: encryptedConfig as any, integrationsConfig: encryptedConfig as any,
}, },

View File

@@ -14,61 +14,61 @@ export class TenantMiddleware implements NestMiddleware {
next: () => void, next: () => void,
) { ) {
try { try {
// Extract subdomain from hostname // Priority 1: Check x-tenant-subdomain header from Nitro BFF proxy
const host = req.headers.host || ''; // This is the primary method when using the BFF architecture
const hostname = host.split(':')[0]; // Remove port if present let subdomain = req.headers['x-tenant-subdomain'] as string | null;
// 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;
this.logger.log(`Host header: ${host}, hostname: ${hostname}, parts: ${JSON.stringify(parts)}, x-tenant-id: ${tenantId}`); if (subdomain) {
this.logger.log(`Using x-tenant-subdomain header: ${subdomain}`);
}
// Try to extract subdomain from Origin header first (for API calls from frontend) // Priority 2: Fall back to extracting subdomain from Origin/Host headers
if (origin) { // This supports direct backend access for development/testing
try { if (!subdomain && !tenantId) {
const originUrl = new URL(origin); const host = req.headers.host || '';
const originHost = originUrl.hostname; const hostname = host.split(':')[0];
parts = originHost.split('.'); const origin = req.headers.origin as string;
this.logger.log(`Using Origin header hostname: ${originHost}, parts: ${JSON.stringify(parts)}`); const referer = req.headers.referer as string;
} catch (error) {
this.logger.warn(`Failed to parse origin: ${origin}`); let parts = hostname.split('.');
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) {
// Fallback to Referer if no Origin // Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co")
try { if (parts.length >= 3) {
const refererUrl = new URL(referer); subdomain = parts[0];
const refererHost = refererUrl.hostname; if (subdomain === 'www') {
parts = refererHost.split('.'); subdomain = null;
this.logger.log(`Using Referer header hostname: ${refererHost}, parts: ${JSON.stringify(parts)}`); }
} catch (error) { } else if (parts.length === 2 && parts[1] === 'localhost') {
this.logger.warn(`Failed to parse referer: ${referer}`); subdomain = parts[0];
} }
} }
// Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co") this.logger.log(`Extracted subdomain: ${subdomain}, x-tenant-id: ${tenantId}`);
// 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: ${hostname}`); this.logger.warn(`No tenant identified from host: ${subdomain}`);
} }
next(); next();

View File

@@ -11,6 +11,7 @@ export interface OpenAIConfig {
apiKey: string; apiKey: string;
assistantId?: string; assistantId?: string;
model?: string; model?: string;
embeddingModel?: string;
voice?: string; voice?: string;
} }

View File

@@ -98,37 +98,75 @@ 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) {
const body = req.body as any; // Parse body - Twilio sends URL-encoded form data
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; const from = body.From; // Format: "client:tenantId:userId"
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}, Body From: ${from}, Body To: ${to}`); this.logger.log(`CallSid: ${callSid}, From: ${from}, To: ${to}`);
this.logger.log(`Full body: ${JSON.stringify(body)}`);
try { try {
// Extract tenant domain from Host header // Extract tenant ID from the client identity
const host = req.headers.host || ''; // Format: "client:tenantId:userId"
const tenantDomain = host.split('.')[0]; // e.g., "tenant1" from "tenant1.routebox.co" let tenantId: string | null = null;
if (from && from.startsWith('client:')) {
this.logger.log(`Extracted tenant domain: ${tenantDomain}`); const parts = from.replace('client:', '').split(':');
if (parts.length >= 2) {
tenantId = parts[0]; // First part is tenantId
this.logger.log(`Extracted tenantId from client identity: ${tenantId}`);
}
}
if (!tenantId) {
this.logger.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 = to; // Fallback (will cause error if not found) let callerId: string | undefined;
try { try {
// Get Twilio config to find the phone number const { config } = await this.voiceService['getTwilioClient'](tenantId);
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;
} }
const dialNumber = to; if (!callerId) {
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}`);
@@ -145,10 +183,9 @@ 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.</Say> <Say>An error occurred while processing your call. ${error.message}</Say>
</Response>`; </Response>`;
res.type('text/xml').send(errorTwiml); res.type('text/xml').send(errorTwiml);
} }
@@ -156,13 +193,33 @@ 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) {
const body = req.body as any; // Parse body - Twilio sends URL-encoded form data
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; const toNumber = body.To; // This is the Twilio phone number that was called
this.logger.log(`\n\n╔════════════════════════════════════════╗`); this.logger.log(`\n\n╔════════════════════════════════════════╗`);
this.logger.log(`║ === INBOUND CALL RECEIVED ===`); this.logger.log(`║ === INBOUND CALL RECEIVED ===`);
@@ -170,19 +227,28 @@ 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 {
// Extract tenant domain from Host header // Look up tenant by the Twilio phone number that was called
const host = req.headers.host || ''; const tenantInfo = await this.voiceService.findTenantByPhoneNumber(toNumber);
const tenantDomain = host.split('.')[0]; // e.g., "tenant1" from "tenant1.routebox.co"
this.logger.log(`Extracted tenant domain: ${tenantDomain}`); if (!tenantInfo) {
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(tenantDomain); const connectedUsers = this.voiceGateway.getConnectedUsers(tenantId);
this.logger.log(`Connected users for tenant ${tenantDomain}: ${connectedUsers.length}`); this.logger.log(`Connected users for tenant ${tenantId}: ${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(', ')}`);
} }
@@ -198,20 +264,22 @@ export class VoiceController {
return res.type('text/xml').send(twiml); return res.type('text/xml').send(twiml);
} }
// Build TwiML to dial all connected clients with Media Streams for AI // Build TwiML to dial all connected clients
const clientElements = connectedUsers.map(userId => ` <Client>${userId}</Client>`).join('\n'); // Client identity format is now: tenantId:userId
const clientElements = connectedUsers.map(userId => ` <Client>${tenantId}:${userId}</Client>`).join('\n');
// Use wss:// for secure WebSocket (Traefik handles HTTPS) // Log the client identities being dialed
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 => {
@@ -219,7 +287,7 @@ export class VoiceController {
callSid, callSid,
fromNumber, fromNumber,
toNumber, toNumber,
tenantDomain, tenantId,
}); });
}); });
@@ -227,7 +295,7 @@ export class VoiceController {
<Response> <Response>
<Start> <Start>
<Stream url="${streamUrl}"> <Stream url="${streamUrl}">
<Parameter name="tenantId" value="${tenantDomain}"/> <Parameter name="tenantId" value="${tenantId}"/>
<Parameter name="userId" value="${connectedUsers[0]}"/> <Parameter name="userId" value="${connectedUsers[0]}"/>
</Stream> </Stream>
</Start> </Start>
@@ -236,7 +304,7 @@ ${clientElements}
</Dial> </Dial>
</Response>`; </Response>`;
this.logger.log(`✓ Returning inbound TwiML with Media Streams - dialing ${connectedUsers.length} client(s)`); this.logger.log(`✓ Returning inbound TwiML - dialing ${connectedUsers.length} client(s)`);
this.logger.log(`Generated TwiML:\n${twiml}\n`); this.logger.log(`Generated TwiML:\n${twiml}\n`);
res.type('text/xml').send(twiml); res.type('text/xml').send(twiml);
} catch (error: any) { } catch (error: any) {

View File

@@ -61,33 +61,41 @@ 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 domain = 'localhost'; let subdomain = 'localhost';
if (origin) { if (origin) {
try { try {
const url = new URL(origin); const url = new URL(origin);
const hostname = url.hostname; // e.g., tenant1.routebox.co or localhost const hostname = url.hostname;
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}`);
} }
} }
client.tenantId = domain; // Store the subdomain as tenantId // Resolve the actual tenantId (UUID) from the subdomain
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 = domain; // Same as subdomain client.tenantSlug = 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}, Domain: ${domain})`, `✓ Client connected: ${client.id} (User: ${client.userId}, TenantId: ${client.tenantId}, Subdomain: ${subdomain})`,
); );
this.logger.log(`Total connected users in ${domain}: ${this.getConnectedUsers(domain).length}`); this.logger.log(`Total connected users in tenant ${client.tenantId}: ${this.getConnectedUsers(client.tenantId).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);
@@ -303,13 +311,14 @@ export class VoiceGateway
/** /**
* Get connected users for a tenant * Get connected users for a tenant
* @param tenantId - The tenant UUID to filter by
*/ */
getConnectedUsers(tenantDomain?: string): string[] { getConnectedUsers(tenantId?: 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 tenantDomain specified, filter by tenant // If tenantId specified, filter by tenant
if (!tenantDomain || socket.tenantSlug === tenantDomain) { if (!tenantId || socket.tenantId === tenantId) {
userIds.push(userId); userIds.push(userId);
} }
} }

View File

@@ -31,46 +31,46 @@ export class VoiceService {
/** /**
* Get Twilio client for a tenant * Get Twilio client for a tenant
*/ */
private async getTwilioClient(tenantIdOrDomain: string): Promise<{ client: Twilio.Twilio; config: TwilioConfig; tenantId: string }> { private async getTwilioClient(tenantId: string): Promise<{ client: Twilio.Twilio; config: TwilioConfig; tenantId: string }> {
// Check cache first // Check cache first
if (this.twilioClients.has(tenantIdOrDomain)) { if (this.twilioClients.has(tenantId)) {
const centralPrisma = getCentralPrisma(); const centralPrisma = getCentralPrisma();
// Look up tenant by domain // Look up tenant by ID
const domainRecord = await centralPrisma.domain.findUnique({ const tenant = await centralPrisma.tenant.findUnique({
where: { domain: tenantIdOrDomain }, where: { id: tenantId },
include: { tenant: { select: { id: true, integrationsConfig: true } } }, select: { id: true, integrationsConfig: true },
}); });
const config = this.getIntegrationConfig(domainRecord?.tenant?.integrationsConfig as any); const config = this.getIntegrationConfig(tenant?.integrationsConfig as any);
return { return {
client: this.twilioClients.get(tenantIdOrDomain), client: this.twilioClients.get(tenantId),
config: config.twilio, config: config.twilio,
tenantId: domainRecord.tenant.id tenantId: tenant.id
}; };
} }
// Fetch tenant integrations config // Fetch tenant integrations config
const centralPrisma = getCentralPrisma(); const centralPrisma = getCentralPrisma();
this.logger.log(`Looking up domain: ${tenantIdOrDomain}`); this.logger.log(`Looking up tenant: ${tenantId}`);
const domainRecord = await centralPrisma.domain.findUnique({ const tenant = await centralPrisma.tenant.findUnique({
where: { domain: tenantIdOrDomain }, where: { id: tenantId },
include: { tenant: { select: { id: true, integrationsConfig: true } } }, select: { id: true, integrationsConfig: true },
}); });
this.logger.log(`Domain record found: ${!!domainRecord}, Tenant: ${!!domainRecord?.tenant}, Config: ${!!domainRecord?.tenant?.integrationsConfig}`); this.logger.log(`Tenant found: ${!!tenant}, Config: ${!!tenant?.integrationsConfig}`);
if (!domainRecord?.tenant) { if (!tenant) {
throw new Error(`Domain ${tenantIdOrDomain} not found`); throw new Error(`Tenant ${tenantId} not found`);
} }
if (!domainRecord.tenant.integrationsConfig) { if (!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(domainRecord.tenant.integrationsConfig as any); const config = this.getIntegrationConfig(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(tenantIdOrDomain, client); this.twilioClients.set(tenantId, client);
return { client, config: config.twilio, tenantId: domainRecord.tenant.id }; return { client, config: config.twilio, tenantId: tenant.id };
} }
/** /**
@@ -105,22 +105,64 @@ 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(tenantDomain: string, userId: string): Promise<string> { async generateAccessToken(tenantId: string, userId: string): Promise<string> {
const { config, tenantId } = await this.getTwilioClient(tenantDomain); const { config, tenantId: resolvedTenantId } = await this.getTwilioClient(tenantId);
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: userId, ttl: 3600 } // 1 hour expiry { identity, ttl: 3600 } // 1 hour expiry
); );
// Create a Voice grant // Create a Voice grant
@@ -436,20 +478,28 @@ export class VoiceService {
const { callSid, tenantId, userId } = params; const { callSid, tenantId, userId } = params;
try { try {
// Get OpenAI config - tenantId might be a domain, so look it up // Get OpenAI config - tenantId might be a domain or a tenant ID (UUID or CUID)
const centralPrisma = getCentralPrisma(); const centralPrisma = getCentralPrisma();
// Try to find tenant by domain first (if tenantId is like "tenant1") // Detect if tenantId looks like an ID (UUID or CUID) or a domain name
// 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 (!tenantId.match(/^[0-9a-f]{8}-[0-9a-f]{4}-/i)) { if (!isId) {
// Looks like a domain, not a UUID // Looks like a domain, not an ID
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 a UUID // It's an ID (UUID or CUID)
this.logger.log(`Looking up tenant by ID: ${tenantId}`);
tenant = await centralPrisma.tenant.findUnique({ tenant = await centralPrisma.tenant.findUnique({
where: { id: tenantId }, where: { id: tenantId },
select: { id: true, integrationsConfig: true }, select: { id: true, integrationsConfig: true },

View File

@@ -8,26 +8,101 @@ import {
} from '@/components/ui/input-group' } from '@/components/ui/input-group'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
import { ArrowUp } from 'lucide-vue-next' import { ArrowUp } from 'lucide-vue-next'
import { useRoute } from 'vue-router'
import { useApi } from '@/composables/useApi'
const chatInput = ref('') const chatInput = ref('')
const messages = ref<{ role: 'user' | 'assistant'; text: string }[]>([])
const sending = ref(false)
const route = useRoute()
const { api } = useApi()
const handleSend = () => { const buildContext = () => {
const recordId = route.params.recordId ? String(route.params.recordId) : undefined
const viewParam = route.params.view ? String(route.params.view) : undefined
const view = viewParam || (recordId ? (recordId === 'new' ? 'edit' : 'detail') : 'list')
const objectApiName = route.params.objectName
? String(route.params.objectName)
: undefined
return {
objectApiName,
view,
recordId,
route: route.fullPath,
}
}
const handleSend = async () => {
if (!chatInput.value.trim()) return if (!chatInput.value.trim()) return
// TODO: Implement AI chat send functionality const message = chatInput.value.trim()
console.log('Sending message:', chatInput.value) messages.value.push({ role: 'user', text: message })
chatInput.value = '' chatInput.value = ''
sending.value = true
try {
const history = messages.value.slice(0, -1).slice(-6)
const response = await api.post('/ai/chat', {
message,
history,
context: buildContext(),
})
messages.value.push({
role: 'assistant',
text: response.reply || 'Let me know what else you need.',
})
if (response.action === 'create_record') {
window.dispatchEvent(
new CustomEvent('ai-record-created', {
detail: {
objectApiName: buildContext().objectApiName,
record: response.record,
},
}),
)
}
} catch (error: any) {
console.error('Failed to send AI chat message:', error)
messages.value.push({
role: 'assistant',
text: error.message || 'Sorry, I ran into an error. Please try again.',
})
} finally {
sending.value = false
}
} }
</script> </script>
<template> <template>
<div class="ai-chat-area sticky bottom-0 z-20 bg-background border-t border-border p-4 bg-neutral-50"> <div class="ai-chat-area w-full border-t border-border p-4 bg-neutral-50">
<div class="ai-chat-messages mb-4 space-y-3">
<div
v-for="(message, index) in messages"
:key="`${message.role}-${index}`"
class="flex"
:class="message.role === 'user' ? 'justify-end' : 'justify-start'"
>
<div
class="max-w-[80%] rounded-lg px-3 py-2 text-sm"
:class="message.role === 'user' ? 'bg-primary text-primary-foreground' : 'bg-white border border-border text-foreground'"
>
{{ message.text }}
</div>
</div>
<p v-if="messages.length === 0" class="text-sm text-muted-foreground">
Ask the assistant to add records, filter lists, or summarize the page.
</p>
</div>
<InputGroup> <InputGroup>
<InputGroupTextarea <InputGroupTextarea
v-model="chatInput" v-model="chatInput"
placeholder="Ask, Search or Chat..." placeholder="Ask, Search or Chat..."
class="min-h-[60px] rounded-lg" class="min-h-[60px] rounded-lg"
@keydown.enter.exact.prevent="handleSend" @keydown.enter.exact.prevent="handleSend"
:disabled="sending"
/> />
<InputGroupAddon> <InputGroupAddon>
<InputGroupText class="ml-auto"> <InputGroupText class="ml-auto">
@@ -37,7 +112,7 @@ const handleSend = () => {
<InputGroupButton <InputGroupButton
variant="default" variant="default"
class="rounded-full" class="rounded-full"
:disabled="!chatInput.trim()" :disabled="!chatInput.trim() || sending"
@click="handleSend" @click="handleSend"
> >
<ArrowUp class="size-4" /> <ArrowUp class="size-4" />
@@ -50,8 +125,6 @@ const handleSend = () => {
<style scoped> <style scoped>
.ai-chat-area { .ai-chat-area {
height: calc(100vh / 6); min-height: 190px;
min-height: 140px;
max-height: 200px;
} }
</style> </style>

View File

@@ -22,12 +22,19 @@ import { useSoftphone } from '~/composables/useSoftphone'
const { logout } = useAuth() const { logout } = useAuth()
const { api } = useApi() const { api } = useApi()
const isDrawerOpen = useState<boolean>('bottomDrawerOpen', () => false)
const drawerTab = useState<string>('bottomDrawerTab', () => 'softphone')
const softphone = useSoftphone() const softphone = useSoftphone()
const handleLogout = async () => { const handleLogout = async () => {
await logout() await logout()
} }
const openSoftphoneDrawer = () => {
drawerTab.value = 'softphone'
isDrawerOpen.value = true
}
// Check if user is central admin (by checking if we're on a central subdomain) // Check if user is central admin (by checking if we're on a central subdomain)
// Use ref instead of computed to avoid hydration mismatch // Use ref instead of computed to avoid hydration mismatch
const isCentralAdmin = ref(false) const isCentralAdmin = ref(false)
@@ -335,13 +342,6 @@ const centralAdminMenuItems: Array<{
</SidebarContent> </SidebarContent>
<SidebarFooter> <SidebarFooter>
<SidebarMenu> <SidebarMenu>
<SidebarMenuItem v-if="!isCentralAdmin">
<SidebarMenuButton @click="softphone.open" class="cursor-pointer hover:bg-accent">
<Phone class="h-4 w-4" />
<span>Softphone</span>
<span v-if="softphone.hasIncomingCall.value" class="ml-auto h-2 w-2 rounded-full bg-red-500 animate-pulse"></span>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem> <SidebarMenuItem>
<SidebarMenuButton @click="handleLogout" class="cursor-pointer hover:bg-accent"> <SidebarMenuButton @click="handleLogout" class="cursor-pointer hover:bg-accent">
<LogOut class="h-4 w-4" /> <LogOut class="h-4 w-4" />

View File

@@ -0,0 +1,454 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import AIChatBar from '@/components/AIChatBar.vue'
import { Phone, Sparkles, X, ChevronUp, Hash, Mic, MicOff, PhoneIncoming, PhoneOff } from 'lucide-vue-next'
import { toast } from 'vue-sonner'
import { useSoftphone } from '~/composables/useSoftphone'
const isDrawerOpen = useState<boolean>('bottomDrawerOpen', () => false)
const activeTab = useState<string>('bottomDrawerTab', () => 'softphone')
const drawerHeight = useState<number>('bottomDrawerHeight', () => 240)
const props = defineProps<{
bounds?: { left: number; width: number }
}>()
const softphone = useSoftphone()
const minHeight = 200
const collapsedHeight = 72
const maxHeight = ref(480)
const isResizing = ref(false)
const resizeStartY = ref(0)
const resizeStartHeight = ref(0)
const phoneNumber = ref('')
const showDialpad = ref(false)
const statusLabel = computed(() => (softphone.isConnected.value ? 'Connected' : 'Offline'))
const clampHeight = (height: number) => Math.min(Math.max(height, minHeight), maxHeight.value)
const updateMaxHeight = () => {
if (!process.client) return
maxHeight.value = Math.round(window.innerHeight * 0.6)
drawerHeight.value = clampHeight(drawerHeight.value)
}
const openDrawer = (tab?: string) => {
if (tab) {
activeTab.value = tab
}
isDrawerOpen.value = true
if (activeTab.value === 'softphone') {
softphone.open()
}
}
const minimizeDrawer = () => {
isDrawerOpen.value = false
}
const startResize = (event: MouseEvent | TouchEvent) => {
if (!isDrawerOpen.value) {
isDrawerOpen.value = true
}
isResizing.value = true
resizeStartY.value = 'touches' in event ? event.touches[0].clientY : event.clientY
resizeStartHeight.value = drawerHeight.value
}
const handleResize = (event: MouseEvent | TouchEvent) => {
if (!isResizing.value) return
const clientY = 'touches' in event ? event.touches[0].clientY : event.clientY
const delta = resizeStartY.value - clientY
drawerHeight.value = clampHeight(resizeStartHeight.value + delta)
}
const stopResize = () => {
isResizing.value = false
}
watch(
() => softphone.incomingCall.value,
(incoming) => {
if (incoming) {
activeTab.value = 'softphone'
isDrawerOpen.value = true
}
}
)
watch(
() => activeTab.value,
(tab) => {
if (tab === 'softphone' && isDrawerOpen.value) {
softphone.open()
}
}
)
watch(
() => isDrawerOpen.value,
(open) => {
if (open && activeTab.value === 'softphone') {
softphone.open()
}
}
)
const handleCall = async () => {
if (!phoneNumber.value) {
toast.error('Please enter a phone number')
return
}
try {
await softphone.initiateCall(phoneNumber.value)
phoneNumber.value = ''
toast.success('Call initiated')
} catch (error: any) {
toast.error(error.message || 'Failed to initiate call')
}
}
const handleAccept = async () => {
if (!softphone.incomingCall.value) return
try {
await softphone.acceptCall(softphone.incomingCall.value.callSid)
} catch (error: any) {
toast.error(error.message || 'Failed to accept call')
}
}
const handleReject = async () => {
if (!softphone.incomingCall.value) return
try {
await softphone.rejectCall(softphone.incomingCall.value.callSid)
} catch (error: any) {
toast.error(error.message || 'Failed to reject call')
}
}
const handleEndCall = async () => {
if (!softphone.currentCall.value) return
try {
await softphone.endCall(softphone.currentCall.value.callSid)
} catch (error: any) {
toast.error(error.message || 'Failed to end call')
}
}
const handleDtmf = async (digit: string) => {
if (!softphone.currentCall.value) return
try {
await softphone.sendDtmf(softphone.currentCall.value.callSid, digit)
} catch (error: any) {
console.error('Failed to send DTMF:', error)
}
}
const formatPhoneNumber = (number: string): string => {
if (!number) return ''
const cleaned = number.replace(/\D/g, '')
if (cleaned.length === 11 && cleaned[0] === '1') {
return `+1 (${cleaned.slice(1, 4)}) ${cleaned.slice(4, 7)}-${cleaned.slice(7)}`
} else if (cleaned.length === 10) {
return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6)}`
}
return number
}
const formatDuration = (seconds?: number): string => {
if (!seconds) return '--:--'
const mins = Math.floor(seconds / 60)
const secs = seconds % 60
return `${mins}:${secs.toString().padStart(2, '0')}`
}
onMounted(() => {
console.log('BottomDrawer mounted');
updateMaxHeight()
window.addEventListener('mousemove', handleResize)
window.addEventListener('mouseup', stopResize)
window.addEventListener('touchmove', handleResize, { passive: true })
window.addEventListener('touchend', stopResize)
window.addEventListener('resize', updateMaxHeight)
})
onBeforeUnmount(() => {
console.log('BottomDrawer unmounted');
window.removeEventListener('mousemove', handleResize)
window.removeEventListener('mouseup', stopResize)
window.removeEventListener('touchmove', handleResize)
window.removeEventListener('touchend', stopResize)
window.removeEventListener('resize', updateMaxHeight)
})
</script>
<template>
<div
class="pointer-events-none fixed bottom-0 z-30 flex justify-center px-2"
:style="{
left: props.bounds?.left ? `${props.bounds.left}px` : '0',
width: props.bounds?.width ? `${props.bounds.width}px` : '100vw',
right: props.bounds?.width ? 'auto' : '0',
}"
>
<div
class="pointer-events-auto w-full border border-border bg-background transition-all duration-200"
:class="{ 'shadow-2xl': isDrawerOpen }"
:style="{ height: `${isDrawerOpen ? drawerHeight : collapsedHeight}px` }"
>
<div class="grid grid-cols-3 items-center justify-between border-border px-2 py-2">
<div class="flex">
<Tabs v-if="!isDrawerOpen" v-model="activeTab" class="flex h-full flex-col">
<TabsList class="mx-2 mt-2 grid w-fit grid-cols-2">
<TabsTrigger value="softphone" class="flex items-center gap-2" @click="openDrawer('softphone')">
<Phone class="h-4 w-4" />
Softphone
<span
class="inline-flex h-2 w-2 rounded-full"
:class="softphone.isConnected.value ? 'bg-emerald-500' : 'bg-muted-foreground/40'"
/>
</TabsTrigger>
<TabsTrigger value="ai" class="flex items-center gap-2" @click="openDrawer('ai')">
<Sparkles class="h-4 w-4" />
AI Agent
</TabsTrigger>
</TabsList>
</Tabs>
</div>
<div
class="flex h-6 flex-1 cursor-row-resize items-center justify-center"
@mousedown="startResize"
@touchstart.prevent="startResize"
>
<span class="h-1.5 w-12 rounded-full bg-muted" />
</div>
<div class="flex col-start-3 justify-end">
<Button variant="ghost" size="icon" class="ml-3" @click="isDrawerOpen ? minimizeDrawer() : openDrawer()">
<X v-if="isDrawerOpen" class="h-4 w-4" />
<ChevronUp v-else class="h-4 w-4" />
<span class="sr-only">{{ isDrawerOpen ? 'Minimize drawer' : 'Expand drawer' }}</span>
</Button>
</div>
</div>
<Tabs v-if="isDrawerOpen" v-model="activeTab" class="flex h-full flex-col border-t">
<TabsList class="mx-4 mt-2 grid w-fit grid-cols-2">
<TabsTrigger value="softphone" class="flex items-center gap-2" @click="openDrawer('softphone')">
<Phone class="h-4 w-4" />
Softphone
<span
class="inline-flex h-2 w-2 rounded-full"
:class="softphone.isConnected.value ? 'bg-emerald-500' : 'bg-muted-foreground/40'"
/>
</TabsTrigger>
<TabsTrigger value="ai" class="flex items-center gap-2" @click="openDrawer('ai')">
<Sparkles class="h-4 w-4" />
AI Agent
</TabsTrigger>
</TabsList>
<div v-show="isDrawerOpen" class="flex-1 overflow-hidden">
<TabsContent value="softphone" class="h-full">
<div class="flex h-full flex-col gap-4 px-6 pb-6 pt-4">
<div
class="flex items-center justify-between rounded-lg border px-4 py-3"
:class="softphone.isConnected.value ? 'border-emerald-200 bg-emerald-50/40' : 'border-border bg-muted/30'"
>
<div>
<p class="text-sm font-medium">Softphone</p>
<p class="text-xs text-muted-foreground">
{{ softphone.isConnected.value ? 'Ready to place and receive calls.' : 'Connect to start placing calls.' }}
</p>
</div>
<div class="flex items-center gap-2 text-xs">
<span
class="inline-flex h-2.5 w-2.5 rounded-full"
:class="softphone.isConnected.value ? 'bg-emerald-500' : 'bg-muted-foreground/40'"
/>
<span class="text-muted-foreground">{{ statusLabel }}</span>
</div>
</div>
<div v-if="softphone.aiSuggestions.value.length > 0" class="space-y-2">
<h3 class="text-sm font-semibold flex items-center gap-2">
<span>AI Assistant</span>
<span class="px-2 py-0.5 text-xs bg-blue-100 text-blue-700 rounded-full">
{{ softphone.aiSuggestions.value.length }}
</span>
</h3>
<div class="space-y-2 max-h-40 overflow-y-auto">
<div
v-for="(suggestion, index) in softphone.aiSuggestions.value.slice(0, 5)"
:key="index"
class="rounded-lg border p-3 text-sm transition-all"
:class="{
'bg-blue-50 border-blue-200': suggestion.type === 'response',
'bg-emerald-50 border-emerald-200': suggestion.type === 'action',
'bg-purple-50 border-purple-200': suggestion.type === 'insight',
}"
>
<div class="flex items-center gap-2 mb-1">
<span
class="text-xs font-semibold uppercase"
:class="{
'text-blue-700': suggestion.type === 'response',
'text-emerald-700': suggestion.type === 'action',
'text-purple-700': suggestion.type === 'insight',
}"
>
{{ suggestion.type }}
</span>
<span class="text-xs text-muted-foreground">just now</span>
</div>
<p class="leading-relaxed">{{ suggestion.text }}</p>
</div>
</div>
</div>
<div v-if="softphone.incomingCall.value" class="rounded-lg border border-blue-200 bg-blue-50/60 p-4">
<div class="text-center space-y-4">
<div>
<p class="text-sm text-muted-foreground">Incoming call from</p>
<p class="text-2xl font-semibold">
{{ formatPhoneNumber(softphone.incomingCall.value.fromNumber) }}
</p>
</div>
<div class="flex gap-2 justify-center">
<Button @click="handleAccept" class="bg-emerald-500 hover:bg-emerald-600">
<Phone class="h-4 w-4 mr-2" />
Accept
</Button>
<Button @click="handleReject" variant="destructive">
<PhoneOff class="h-4 w-4 mr-2" />
Reject
</Button>
</div>
</div>
</div>
<div v-if="softphone.currentCall.value" class="space-y-4">
<div class="rounded-lg border bg-muted/40 p-4 text-center space-y-2">
<p class="text-sm text-muted-foreground">
{{ softphone.currentCall.value.direction === 'outbound' ? 'Calling' : 'Connected with' }}
</p>
<p class="text-2xl font-semibold">
{{ formatPhoneNumber(
softphone.currentCall.value.direction === 'outbound'
? softphone.currentCall.value.toNumber
: softphone.currentCall.value.fromNumber
) }}
</p>
<p class="text-xs text-muted-foreground capitalize">{{ softphone.callStatus.value }}</p>
</div>
<div class="grid grid-cols-3 gap-2">
<Button variant="outline" size="sm" @click="softphone.toggleMute">
<Mic v-if="!softphone.isMuted.value" class="h-4 w-4" />
<MicOff v-else class="h-4 w-4" />
</Button>
<Button variant="outline" size="sm" @click="showDialpad = !showDialpad">
<Hash class="h-4 w-4" />
</Button>
<Button variant="destructive" size="sm" @click="handleEndCall">
<PhoneOff class="h-4 w-4" />
</Button>
</div>
<div v-if="showDialpad" class="grid grid-cols-3 gap-2">
<Button
v-for="digit in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#']"
:key="digit"
variant="outline"
size="sm"
@click="handleDtmf(digit)"
class="h-12 text-lg font-semibold"
>
{{ digit }}
</Button>
</div>
</div>
<div v-if="!softphone.currentCall.value && !softphone.incomingCall.value" class="space-y-4">
<div>
<label class="text-sm font-medium">Phone Number</label>
<Input
v-model="phoneNumber"
placeholder="+1234567890"
class="mt-1"
@keyup.enter="handleCall"
/>
</div>
<div class="grid grid-cols-3 gap-2">
<Button
v-for="digit in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#']"
:key="digit"
variant="outline"
@click="phoneNumber += digit"
class="h-12 text-lg font-semibold"
>
{{ digit }}
</Button>
</div>
<div class="flex gap-2">
<Button @click="handleCall" class="flex-1" :disabled="!phoneNumber">
<Phone class="h-4 w-4 mr-2" />
Call
</Button>
<Button @click="phoneNumber = ''" variant="outline">
<X class="h-4 w-4" />
</Button>
</div>
<div v-if="softphone.callHistory.value.length > 0" class="space-y-2">
<h3 class="text-sm font-semibold">Recent Calls</h3>
<div class="space-y-1 max-h-40 overflow-y-auto">
<div
v-for="call in softphone.callHistory.value.slice(0, 5)"
:key="call.callSid"
class="flex items-center justify-between rounded-md px-2 py-1 hover:bg-muted/40 cursor-pointer"
@click="phoneNumber = call.direction === 'outbound' ? call.toNumber : call.fromNumber"
>
<div class="flex items-center gap-2">
<Phone v-if="call.direction === 'outbound'" class="h-3 w-3 text-emerald-500" />
<PhoneIncoming v-else class="h-3 w-3 text-blue-500" />
<span class="text-sm">
{{ formatPhoneNumber(call.direction === 'outbound' ? call.toNumber : call.fromNumber) }}
</span>
</div>
<span class="text-xs text-muted-foreground">{{ formatDuration(call.duration) }}</span>
</div>
</div>
</div>
</div>
</div>
</TabsContent>
<TabsContent value="ai" class="h-full relative">
<div class="flex flex-col justify-end absolute bottom-0 w-full">
<AIChatBar />
</div>
</TabsContent>
</div>
</Tabs>
</div>
</div>
</template>

View File

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

View File

@@ -3,90 +3,32 @@ 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 = ''
const headers: Record<string, string> = { // Use the BFF login endpoint via useAuth
'Content-Type': 'application/json', const result = await login(email.value, password.value)
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>
@@ -118,8 +60,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="loading"> <Button type="submit" class="w-full" :disabled="isLoading">
{{ loading ? 'Logging in...' : 'Login' }} {{ isLoading ? 'Logging in...' : 'Login' }}
</Button> </Button>
</div> </div>
<div class="text-center text-sm"> <div class="text-center text-sm">

View File

@@ -28,22 +28,44 @@
</div> </div>
<!-- Available Fields Sidebar --> <!-- Available Fields Sidebar -->
<div class="w-80 border-l bg-white dark:bg-slate-950 p-4 overflow-auto"> <div class="w-80 border-l bg-white dark:bg-slate-950 p-4 overflow-auto space-y-6">
<h3 class="text-lg font-semibold mb-4">Available Fields</h3> <div>
<p class="text-xs text-muted-foreground mb-4">Click or drag to add field to grid</p> <h3 class="text-lg font-semibold mb-4">Available Fields</h3>
<div class="space-y-2" id="sidebar-fields"> <p class="text-xs text-muted-foreground mb-4">Click or drag to add field to grid</p>
<div <div class="space-y-2" id="sidebar-fields">
v-for="field in availableFields" <div
:key="field.id" v-for="field in availableFields"
class="p-3 border rounded cursor-move bg-white dark:bg-slate-900 hover:border-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors" :key="field.id"
:data-field-id="field.id" class="p-3 border rounded cursor-move bg-white dark:bg-slate-900 hover:border-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors"
draggable="true" :data-field-id="field.id"
@dragstart="handleDragStart($event, field)" draggable="true"
@click="addFieldToGrid(field)" @dragstart="handleDragStart($event, field)"
> @click="addFieldToGrid(field)"
<div class="font-medium text-sm">{{ field.label }}</div> >
<div class="text-xs text-muted-foreground">{{ field.apiName }}</div> <div class="font-medium text-sm">{{ field.label }}</div>
<div class="text-xs text-muted-foreground">Type: {{ field.type }}</div> <div class="text-xs text-muted-foreground">{{ field.apiName }}</div>
<div class="text-xs text-muted-foreground">Type: {{ field.type }}</div>
</div>
</div>
</div>
<div v-if="relatedLists.length > 0">
<h3 class="text-lg font-semibold mb-2">Related Lists</h3>
<p class="text-xs text-muted-foreground mb-4">Select related lists to show on detail views</p>
<div class="space-y-2">
<label
v-for="list in relatedLists"
:key="list.relationName"
class="flex items-center gap-2 text-sm"
>
<input
type="checkbox"
class="h-4 w-4"
:value="list.relationName"
v-model="selectedRelatedLists"
/>
<span>{{ list.title }}</span>
</label>
</div> </div>
</div> </div>
</div> </div>
@@ -52,26 +74,29 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue' import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { GridStack } from 'gridstack' import { GridStack } from 'gridstack'
import 'gridstack/dist/gridstack.min.css' import 'gridstack/dist/gridstack.min.css'
import type { FieldLayoutItem } from '~/types/page-layout' import type { FieldLayoutItem } from '~/types/page-layout'
import type { FieldConfig } from '~/types/field-types' import type { FieldConfig, RelatedListConfig } from '~/types/field-types'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
const props = defineProps<{ const props = defineProps<{
fields: FieldConfig[] fields: FieldConfig[]
relatedLists?: RelatedListConfig[]
initialLayout?: FieldLayoutItem[] initialLayout?: FieldLayoutItem[]
initialRelatedLists?: string[]
layoutName?: string layoutName?: string
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
save: [layout: FieldLayoutItem[]] save: [layout: { fields: FieldLayoutItem[]; relatedLists: string[] }]
}>() }>()
const gridContainer = ref<HTMLElement | null>(null) const gridContainer = ref<HTMLElement | null>(null)
let grid: GridStack | null = null let grid: GridStack | null = null
const gridItems = ref<Map<string, any>>(new Map()) const gridItems = ref<Map<string, any>>(new Map())
const selectedRelatedLists = ref<string[]>(props.initialRelatedLists || [])
// Fields that are already on the grid // Fields that are already on the grid
const placedFieldIds = ref<Set<string>>(new Set()) const placedFieldIds = ref<Set<string>>(new Set())
@@ -81,6 +106,10 @@ const availableFields = computed(() => {
return props.fields.filter(field => !placedFieldIds.value.has(field.id)) return props.fields.filter(field => !placedFieldIds.value.has(field.id))
}) })
const relatedLists = computed(() => {
return props.relatedLists || []
})
const initGrid = () => { const initGrid = () => {
if (!gridContainer.value) return if (!gridContainer.value) return
@@ -278,7 +307,10 @@ const handleSave = () => {
} }
}) })
emit('save', layout) emit('save', {
fields: layout,
relatedLists: selectedRelatedLists.value,
})
} }
onMounted(() => { onMounted(() => {
@@ -295,6 +327,13 @@ onBeforeUnmount(() => {
watch(() => props.fields, () => { watch(() => props.fields, () => {
updatePlacedFields() updatePlacedFields()
}, { deep: true }) }, { deep: true })
watch(
() => props.initialRelatedLists,
(value) => {
selectedRelatedLists.value = value ? [...value] : []
},
)
</script> </script>
<style> <style>

View File

@@ -17,6 +17,7 @@
:record-data="modelValue" :record-data="modelValue"
:mode="readonly ? VM.DETAIL : VM.EDIT" :mode="readonly ? VM.DETAIL : VM.EDIT"
@update:model-value="handleFieldUpdate(fieldItem.field.apiName, $event)" @update:model-value="handleFieldUpdate(fieldItem.field.apiName, $event)"
@update:related-fields="handleRelatedFieldsUpdate"
/> />
</div> </div>
</div> </div>
@@ -34,6 +35,7 @@
:record-data="modelValue" :record-data="modelValue"
:mode="readonly ? VM.DETAIL : VM.EDIT" :mode="readonly ? VM.DETAIL : VM.EDIT"
@update:model-value="handleFieldUpdate(field.apiName, $event)" @update:model-value="handleFieldUpdate(field.apiName, $event)"
@update:related-fields="handleRelatedFieldsUpdate"
/> />
</div> </div>
</div> </div>
@@ -96,6 +98,17 @@ const handleFieldUpdate = (fieldName: string, value: any) => {
emit('update:modelValue', updated) emit('update:modelValue', updated)
} }
const handleRelatedFieldsUpdate = (values: Record<string, any>) => {
if (props.readonly) return
const updated = {
...props.modelValue,
...values,
}
emit('update:modelValue', updated)
}
</script> </script>
<style scoped> <style scoped>

View File

@@ -186,6 +186,8 @@ 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>();
@@ -193,6 +195,11 @@ 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);
@@ -236,9 +243,7 @@ const loadShares = async () => {
try { try {
loading.value = true; loading.value = true;
error.value = null; error.value = null;
const response = await api.get( const response = await api.get(sharesBasePath.value);
`/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);
@@ -286,7 +291,7 @@ const createShare = async () => {
console.log('Final payload:', payload); console.log('Final payload:', payload);
await api.post( await api.post(
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`, sharesBasePath.value,
payload payload
); );
toast.success('Record shared successfully'); toast.success('Record shared successfully');
@@ -313,7 +318,7 @@ const removeShare = async (shareId: string) => {
try { try {
removing.value = shareId; removing.value = shareId;
await api.delete( await api.delete(
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares/${shareId}` `${sharesBasePath.value}/${shareId}`
); );
toast.success('Share removed successfully'); toast.success('Share removed successfully');
await loadShares(); await loadShares();

View File

@@ -11,6 +11,8 @@ interface RelatedListConfig {
relationName: string // e.g., 'domains', 'users' relationName: string // e.g., 'domains', 'users'
objectApiName: string // e.g., 'domains', 'users' objectApiName: string // e.g., 'domains', 'users'
fields: FieldConfig[] // Fields to display in the list fields: FieldConfig[] // Fields to display in the list
lookupFieldApiName?: string // Used to filter by parentId when fetching
parentObjectApiName?: string // Parent object API name, used to derive lookup field if missing
canCreate?: boolean canCreate?: boolean
createRoute?: string // Route to create new related record createRoute?: string // Route to create new related record
} }
@@ -19,11 +21,11 @@ interface Props {
config: RelatedListConfig config: RelatedListConfig
parentId: string parentId: string
relatedRecords?: any[] // Can be passed in if already fetched relatedRecords?: any[] // Can be passed in if already fetched
baseUrl?: string // Base API URL, defaults to '/central' baseUrl?: string // Base API URL, defaults to runtime objects
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
baseUrl: '/central', baseUrl: '/runtime/objects',
relatedRecords: undefined, relatedRecords: undefined,
}) })
@@ -53,14 +55,48 @@ const fetchRelatedRecords = async () => {
try { try {
// Replace :parentId placeholder in the API path // Replace :parentId placeholder in the API path
let apiPath = props.config.objectApiName.replace(':parentId', props.parentId) const sanitizedBase = props.baseUrl.replace(/\/$/, '')
let apiPath = props.config.objectApiName.replace(':parentId', props.parentId).replace(/^\/+/, '')
const isRuntimeObjects = sanitizedBase.endsWith('/runtime/objects')
// Default runtime object routes expect /:objectApiName/records
if (isRuntimeObjects && !apiPath.includes('/')) {
apiPath = `${apiPath}/records`
}
const response = await api.get(`${props.baseUrl}/${apiPath}`, { const findLookupKey = () => {
if (props.config.lookupFieldApiName) return props.config.lookupFieldApiName
const parentName = props.config.parentObjectApiName?.toLowerCase()
const fields = props.config.fields || []
const parentMatch = fields.find(field => {
const relation = (field as any).relationObject || (field as any).referenceObject
return relation && parentName && relation.toLowerCase() === parentName
})
if (parentMatch?.apiName) return parentMatch.apiName
const lookupMatch = fields.find(
field => (field.type || '').toString().toLowerCase() === 'lookup'
)
if (lookupMatch?.apiName) return lookupMatch.apiName
const idMatch = fields.find(field =>
field.apiName?.toLowerCase().endsWith('id')
)
if (idMatch?.apiName) return idMatch.apiName
return 'parentId'
}
const lookupKey = findLookupKey()
const response = await api.get(`${sanitizedBase}/${apiPath}`, {
params: { params: {
parentId: props.parentId, [lookupKey]: props.parentId,
}, },
}) })
records.value = response || [] records.value = response?.data || response || []
} catch (err: any) { } catch (err: any) {
console.error('Error fetching related records:', err) console.error('Error fetching related records:', err)
error.value = err.message || 'Failed to fetch related records' error.value = err.message || 'Failed to fetch related records'
@@ -77,20 +113,40 @@ const handleViewRecord = (recordId: string) => {
emit('navigate', props.config.objectApiName, recordId) emit('navigate', props.config.objectApiName, recordId)
} }
const formatValue = (value: any, field: FieldConfig): string => { const formatValue = (record: any, field: FieldConfig): string => {
const value = record?.[field.apiName]
if (value === null || value === undefined) return '-' if (value === null || value === undefined) return '-'
const type = (field.type || '').toString().toLowerCase()
// Lookup fields: use related object display value when available
if (type === 'lookup' || type === 'belongsto') {
const relationName = field.apiName.replace(/Id$/i, '').toLowerCase()
const related = record?.[relationName]
if (related && typeof related === 'object') {
const displayField = (field as any).relationDisplayField || 'name'
if (related[displayField]) return String(related[displayField])
// Fallback: first string-ish property or ID
const firstStringKey = Object.keys(related).find(
key => typeof related[key] === 'string'
)
if (firstStringKey) return String(related[firstStringKey])
if (related.id) return String(related.id)
}
// If no related object, show raw value
}
// Handle different field types // Handle different field types
if (field.type === 'date') { if (type === 'date') {
return new Date(value).toLocaleDateString() return new Date(value).toLocaleDateString()
} }
if (field.type === 'datetime') { if (type === 'datetime' || type === 'date_time' || type === 'date-time') {
return new Date(value).toLocaleString() return new Date(value).toLocaleString()
} }
if (field.type === 'boolean') { if (type === 'boolean') {
return value ? 'Yes' : 'No' return value ? 'Yes' : 'No'
} }
if (field.type === 'select' && field.options) { if (type === 'select' && field.options) {
const option = field.options.find(opt => opt.value === value) const option = field.options.find(opt => opt.value === value)
return option?.label || value return option?.label || value
} }
@@ -163,7 +219,7 @@ onMounted(() => {
<TableBody> <TableBody>
<TableRow v-for="record in displayRecords" :key="record.id"> <TableRow v-for="record in displayRecords" :key="record.id">
<TableCell v-for="field in config.fields" :key="field.id"> <TableCell v-for="field in config.fields" :key="field.id">
{{ formatValue(record[field.apiName], field) }} {{ formatValue(record, field) }}
</TableCell> </TableCell>
<TableCell> <TableCell>
<Button <Button

View File

@@ -0,0 +1,234 @@
<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>

View File

@@ -0,0 +1,195 @@
<template>
<div class="space-y-6">
<!-- Label -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Label</label>
<div class="col-span-3">
<input
v-model="formData.label"
type="text"
placeholder="Display name for this field"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<!-- API Name (Read-only if editing existing field) -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">API Name</label>
<div class="col-span-3">
<input
v-model="formData.apiName"
type="text"
placeholder="e.g., accountName"
:disabled="isEditing"
class="w-full px-3 py-2 border rounded-md text-sm disabled:bg-gray-100 disabled:text-gray-600"
/>
<p v-if="isEditing" class="text-xs text-gray-500 mt-1">
Cannot change API name on existing fields
</p>
</div>
</div>
<!-- Description -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Description</label>
<div class="col-span-3">
<textarea
v-model="formData.description"
placeholder="Describe the purpose of this field"
rows="3"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<!-- Placeholder -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Placeholder</label>
<div class="col-span-3">
<input
v-model="formData.placeholder"
type="text"
placeholder="e.g., Enter account name"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<!-- Help Text -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Help Text</label>
<div class="col-span-3">
<textarea
v-model="formData.helpText"
placeholder="Additional guidance for users"
rows="2"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<!-- Display Order -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Display Order</label>
<div class="col-span-3">
<input
v-model.number="formData.displayOrder"
type="number"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<!-- Required -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Required</label>
<div class="col-span-3 flex items-center">
<input
v-model="formData.isRequired"
type="checkbox"
class="w-4 h-4 border rounded"
/>
<span class="ml-2 text-sm text-gray-600">
{{ formData.isRequired ? 'Yes, this field is required' : 'No, this field is optional' }}
</span>
<p v-if="hasData && !wasRequired && formData.isRequired" class="ml-2 text-xs text-red-600">
Existing records may have empty values
</p>
</div>
</div>
<!-- Unique -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Unique</label>
<div class="col-span-3 flex items-center">
<input
v-model="formData.isUnique"
type="checkbox"
class="w-4 h-4 border rounded"
/>
<span class="ml-2 text-sm text-gray-600">
{{ formData.isUnique ? 'Yes, values must be unique' : 'No, duplicate values allowed' }}
</span>
<p v-if="hasData && !wasUnique && formData.isUnique" class="ml-2 text-xs text-red-600">
Existing records may have duplicate values
</p>
</div>
</div>
<!-- Default Value -->
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Default Value</label>
<div class="col-span-3">
<input
v-model="formData.defaultValue"
type="text"
placeholder="Value used when field is not provided"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
interface Props {
label?: string
apiName?: string
description?: string
placeholder?: string
helpText?: string
displayOrder?: number
isRequired?: boolean
isUnique?: boolean
defaultValue?: string
isEditing?: boolean
hasData?: boolean
}
interface Emits {
(e: 'update', data: any): void
}
const props = withDefaults(defineProps<Props>(), {
label: '',
apiName: '',
description: '',
placeholder: '',
helpText: '',
displayOrder: 0,
isRequired: false,
isUnique: false,
defaultValue: '',
isEditing: false,
hasData: false,
})
const emit = defineEmits<Emits>()
const formData = ref({
label: props.label,
apiName: props.apiName,
description: props.description,
placeholder: props.placeholder,
helpText: props.helpText,
displayOrder: props.displayOrder,
isRequired: props.isRequired,
isUnique: props.isUnique,
defaultValue: props.defaultValue,
})
const wasRequired = ref(props.isRequired)
const wasUnique = ref(props.isUnique)
onMounted(() => {
wasRequired.value = props.isRequired
wasUnique.value = props.isUnique
})
watch(formData, (newVal) => {
emit('update', newVal)
}, { deep: true })
</script>

View File

@@ -0,0 +1,296 @@
<template>
<div class="space-y-6">
<!-- Text Field Attributes -->
<div v-if="fieldType === 'text'" class="space-y-4">
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Max Length</label>
<div class="col-span-3">
<input
v-model.number="attributes.maxLength"
type="number"
min="1"
max="65535"
placeholder="Maximum character length (default: 255)"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
</div>
<!-- Textarea Attributes -->
<div v-if="fieldType === 'textarea'" class="space-y-4">
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Default Rows</label>
<div class="col-span-3">
<input
v-model.number="attributes.rows"
type="number"
min="2"
max="20"
:placeholder="`Default: 4 rows`"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
</div>
<!-- Number Field Attributes -->
<div v-if="fieldType === 'number'" class="space-y-4">
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Decimal Places</label>
<div class="col-span-3">
<input
v-model.number="attributes.scale"
type="number"
min="0"
max="10"
placeholder="0 for integers, 2 for decimals"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Min Value</label>
<div class="col-span-3">
<input
v-model.number="attributes.min"
type="number"
placeholder="Minimum allowed value"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Max Value</label>
<div class="col-span-3">
<input
v-model.number="attributes.max"
type="number"
placeholder="Maximum allowed value"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
</div>
<!-- Currency Field Attributes -->
<div v-if="fieldType === 'currency'" class="space-y-4">
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Currency Symbol</label>
<div class="col-span-3">
<input
v-model="attributes.prefix"
type="text"
placeholder="e.g., $, €, ¥"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Decimal Places</label>
<div class="col-span-3">
<input
v-model.number="attributes.scale"
type="number"
min="0"
max="4"
placeholder="Default: 2"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Min Value</label>
<div class="col-span-3">
<input
v-model.number="attributes.min"
type="number"
placeholder="Minimum allowed value"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Max Value</label>
<div class="col-span-3">
<input
v-model.number="attributes.max"
type="number"
placeholder="Maximum allowed value"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
</div>
</div>
</div>
<!-- Select/Picklist Attributes -->
<div v-if="fieldType === 'select' || fieldType === 'multiSelect'" class="space-y-4">
<div class="border rounded-lg p-4 bg-gray-50">
<div class="flex items-center justify-between mb-4">
<label class="text-sm font-medium">Options</label>
<button
type="button"
@click="addOption"
class="text-xs px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Add Option
</button>
</div>
<div class="space-y-2">
<div
v-for="(option, index) in attributes.options"
:key="index"
class="flex gap-2 items-center bg-white p-3 rounded border"
>
<input
v-model="option.value"
type="text"
placeholder="Value"
class="flex-1 px-2 py-1 border rounded text-sm"
/>
<input
v-model="option.label"
type="text"
placeholder="Label"
class="flex-1 px-2 py-1 border rounded text-sm"
/>
<button
type="button"
@click="removeOption(index)"
class="text-red-600 hover:text-red-800 text-sm font-medium"
>
Remove
</button>
</div>
</div>
<p v-if="!attributes.options || attributes.options.length === 0" class="text-sm text-gray-500 mt-4">
No options defined yet
</p>
</div>
</div>
<!-- Date Field Attributes -->
<div v-if="fieldType === 'date' || fieldType === 'datetime'" class="space-y-4">
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Include Time</label>
<div class="col-span-3 flex items-center">
<input
v-if="fieldType === 'datetime'"
:checked="true"
type="checkbox"
disabled
class="w-4 h-4 border rounded"
/>
<span class="ml-2 text-sm text-gray-600">{{ fieldType === 'datetime' ? 'Yes' : 'No' }}</span>
</div>
</div>
</div>
<!-- Lookup Field Attributes -->
<div v-if="fieldType === 'lookup' || fieldType === 'belongsTo'" class="space-y-4">
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Related Object</label>
<div class="col-span-3">
<input
v-model="attributes.relationObject"
type="text"
disabled
placeholder="Selected during field creation"
class="w-full px-3 py-2 border rounded-md text-sm bg-gray-100 disabled:text-gray-600"
/>
<p class="text-xs text-gray-500 mt-1">Cannot change relationship after creation</p>
</div>
</div>
<div class="grid grid-cols-4 gap-4">
<label class="text-sm font-medium leading-8">Display Field</label>
<div class="col-span-3">
<input
v-model="attributes.relationDisplayField"
type="text"
placeholder="e.g., name, label (field to show in lookup)"
class="w-full px-3 py-2 border rounded-md text-sm"
/>
<p class="text-xs text-gray-500 mt-1">Which field from the related object to display</p>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
interface FieldOption {
value: string | number
label: string
}
interface TypeAttributes {
maxLength?: number
rows?: number
scale?: number
min?: number
max?: number
prefix?: string
suffix?: string
options?: FieldOption[]
relationObject?: string
relationDisplayField?: string
}
interface Props {
fieldType: string
attributes?: TypeAttributes
}
interface Emits {
(e: 'update', data: TypeAttributes): void
}
const props = withDefaults(defineProps<Props>(), {
fieldType: 'text',
attributes: () => ({}),
})
const emit = defineEmits<Emits>()
const attributes = ref<TypeAttributes>({
...props.attributes,
})
watch(
() => props.fieldType,
(newType) => {
// Reset attributes when field type changes
attributes.value = {}
},
)
const addOption = () => {
if (!attributes.value.options) {
attributes.value.options = []
}
attributes.value.options.push({
value: '',
label: '',
})
emit('update', attributes.value)
}
const removeOption = (index: number) => {
if (attributes.value.options) {
attributes.value.options.splice(index, 1)
emit('update', attributes.value)
}
}
watch(
attributes,
(newVal) => {
emit('update', newVal)
},
{ deep: true },
)
</script>

View File

@@ -21,11 +21,13 @@ interface Props {
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
baseUrl: '/central', // Default to runtime objects endpoint; override when consuming central entities
baseUrl: '/runtime/objects',
}) })
const emit = defineEmits<{ const emit = defineEmits<{
'update:modelValue': [value: any] 'update:modelValue': [value: any]
'update:relatedFields': [value: Record<string, any>]
}>() }>()
const { api } = useApi() const { api } = useApi()
@@ -39,6 +41,10 @@ const isReadOnly = computed(() => props.readonly || props.field.isReadOnly || pr
const isEditMode = computed(() => props.mode === ViewMode.EDIT) const isEditMode = computed(() => props.mode === ViewMode.EDIT)
const isListMode = computed(() => props.mode === ViewMode.LIST) const isListMode = computed(() => props.mode === ViewMode.LIST)
const isDetailMode = computed(() => props.mode === ViewMode.DETAIL) const isDetailMode = computed(() => props.mode === ViewMode.DETAIL)
const relationTypeValue = computed(() => {
if (!props.field.relationTypeField) return null
return props.recordData?.[props.field.relationTypeField] ?? null
})
// Check if field is a relationship field // Check if field is a relationship field
const isRelationshipField = computed(() => { const isRelationshipField = computed(() => {
@@ -79,9 +85,31 @@ const formatValue = (val: any): string => {
case FieldType.BELONGS_TO: case FieldType.BELONGS_TO:
return relationshipDisplayValue.value return relationshipDisplayValue.value
case FieldType.DATE: case FieldType.DATE:
return val instanceof Date ? val.toLocaleDateString() : new Date(val).toLocaleDateString() try {
const date = val instanceof Date ? val : new Date(val)
return date.toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
} catch {
return String(val)
}
case FieldType.DATETIME: case FieldType.DATETIME:
return val instanceof Date ? val.toLocaleString() : new Date(val).toLocaleString() try {
const date = val instanceof Date ? val : new Date(val)
return date.toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
})
} catch {
return String(val)
}
case FieldType.BOOLEAN: case FieldType.BOOLEAN:
return val ? 'Yes' : 'No' return val ? 'Yes' : 'No'
case FieldType.CURRENCY: case FieldType.CURRENCY:
@@ -99,6 +127,13 @@ const formatValue = (val: any): string => {
return String(val) return String(val)
} }
} }
const handleRelationTypeUpdate = (value: string | null) => {
if (!props.field.relationTypeField) return
emit('update:relatedFields', {
[props.field.relationTypeField]: value,
})
}
</script> </script>
<template> <template>
@@ -161,7 +196,9 @@ const formatValue = (val: any): string => {
v-if="field.type === FieldType.BELONGS_TO" v-if="field.type === FieldType.BELONGS_TO"
:field="field" :field="field"
v-model="value" v-model="value"
:relation-type-value="relationTypeValue"
:base-url="baseUrl" :base-url="baseUrl"
@update:relation-type-value="handleRelationTypeUpdate"
/> />
<!-- Text Input --> <!-- Text Input -->
@@ -212,6 +249,51 @@ const formatValue = (val: any): string => {
</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">&times;</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" />

View File

@@ -0,0 +1,140 @@
<template>
<div class="space-y-4">
<label class="text-sm font-medium">Field Type</label>
<div class="grid grid-cols-2 gap-4">
<!-- Text Fields -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'text' }"
@click="$emit('update:modelValue', 'text')">
<div class="font-medium text-sm">Text</div>
<div class="text-xs text-gray-600">Single line text input</div>
</div>
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'textarea' }"
@click="$emit('update:modelValue', 'textarea')">
<div class="font-medium text-sm">Textarea</div>
<div class="text-xs text-gray-600">Multi-line text input</div>
</div>
<!-- Email & Phone -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'email' }"
@click="$emit('update:modelValue', 'email')">
<div class="font-medium text-sm">Email</div>
<div class="text-xs text-gray-600">Email with validation</div>
</div>
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'phone' }"
@click="$emit('update:modelValue', 'phone')">
<div class="font-medium text-sm">Phone</div>
<div class="text-xs text-gray-600">Phone number input</div>
</div>
<!-- Numeric Fields -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'number' }"
@click="$emit('update:modelValue', 'number')">
<div class="font-medium text-sm">Number</div>
<div class="text-xs text-gray-600">Integer or decimal</div>
</div>
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'currency' }"
@click="$emit('update:modelValue', 'currency')">
<div class="font-medium text-sm">Currency</div>
<div class="text-xs text-gray-600">Money amount with symbol</div>
</div>
<!-- Selection Fields -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'select' }"
@click="$emit('update:modelValue', 'select')">
<div class="font-medium text-sm">Picklist</div>
<div class="text-xs text-gray-600">Dropdown with predefined options</div>
</div>
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'multiSelect' }"
@click="$emit('update:modelValue', 'multiSelect')">
<div class="font-medium text-sm">Multi-select</div>
<div class="text-xs text-gray-600">Select multiple options</div>
</div>
<!-- Boolean -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'boolean' }"
@click="$emit('update:modelValue', 'boolean')">
<div class="font-medium text-sm">Checkbox</div>
<div class="text-xs text-gray-600">True/False toggle</div>
</div>
<!-- Date Fields -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'date' }"
@click="$emit('update:modelValue', 'date')">
<div class="font-medium text-sm">Date</div>
<div class="text-xs text-gray-600">Date picker without time</div>
</div>
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'datetime' }"
@click="$emit('update:modelValue', 'datetime')">
<div class="font-medium text-sm">DateTime</div>
<div class="text-xs text-gray-600">Date and time picker</div>
</div>
<!-- Relationship Fields -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'lookup' }"
@click="$emit('update:modelValue', 'lookup')">
<div class="font-medium text-sm">Lookup</div>
<div class="text-xs text-gray-600">Link to another object</div>
</div>
<!-- Rich Content -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'markdown' }"
@click="$emit('update:modelValue', 'markdown')">
<div class="font-medium text-sm">Rich Text</div>
<div class="text-xs text-gray-600">Markdown editor</div>
</div>
<!-- File -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'file' }"
@click="$emit('update:modelValue', 'file')">
<div class="font-medium text-sm">File</div>
<div class="text-xs text-gray-600">File upload</div>
</div>
<!-- URL -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'url' }"
@click="$emit('update:modelValue', 'url')">
<div class="font-medium text-sm">URL</div>
<div class="text-xs text-gray-600">Web address with validation</div>
</div>
<!-- Color -->
<div class="border rounded-lg p-4 cursor-pointer hover:bg-blue-50"
:class="{ 'bg-blue-100 border-blue-500': modelValue === 'color' }"
@click="$emit('update:modelValue', 'color')">
<div class="font-medium text-sm">Color</div>
<div class="text-xs text-gray-600">Color picker</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
defineProps<{
modelValue: string
}>()
defineEmits<{
'update:modelValue': [value: string]
}>()
</script>

View File

@@ -4,6 +4,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command' import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Check, ChevronsUpDown, X } from 'lucide-vue-next' import { Check, ChevronsUpDown, X } from 'lucide-vue-next'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import type { FieldConfig } from '@/types/field-types' import type { FieldConfig } from '@/types/field-types'
@@ -13,15 +14,18 @@ interface Props {
modelValue: string | null // The ID of the selected record modelValue: string | null // The ID of the selected record
readonly?: boolean readonly?: boolean
baseUrl?: string // Base API URL, defaults to '/central' baseUrl?: string // Base API URL, defaults to '/central'
relationTypeValue?: string | null
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
baseUrl: '/central', // Default to runtime objects endpoint; override when consuming central entities
baseUrl: '/runtime/objects',
modelValue: null, modelValue: null,
}) })
const emit = defineEmits<{ const emit = defineEmits<{
'update:modelValue': [value: string | null] 'update:modelValue': [value: string | null]
'update:relationTypeValue': [value: string | null]
}>() }>()
const { api } = useApi() const { api } = useApi()
@@ -30,10 +34,21 @@ const searchQuery = ref('')
const records = ref<any[]>([]) const records = ref<any[]>([])
const loading = ref(false) const loading = ref(false)
const selectedRecord = ref<any | null>(null) const selectedRecord = ref<any | null>(null)
const selectedRelationObject = ref<string | null>(null)
// Get the relation configuration // Get the relation configuration
const relationObject = computed(() => props.field.relationObject || props.field.apiName.replace('Id', '')) const availableRelationObjects = computed(() => {
if (props.field.relationObjects && props.field.relationObjects.length > 0) {
return props.field.relationObjects
}
const fallback = props.field.relationObject || props.field.apiName.replace('Id', '')
return fallback ? [fallback] : []
})
const relationObject = computed(() => selectedRelationObject.value || availableRelationObjects.value[0])
const displayField = computed(() => props.field.relationDisplayField || 'name') const displayField = computed(() => props.field.relationDisplayField || 'name')
const shouldShowTypeSelector = computed(() => availableRelationObjects.value.length > 1)
// Display value for the selected record // Display value for the selected record
const displayValue = computed(() => { const displayValue = computed(() => {
@@ -54,11 +69,18 @@ const filteredRecords = computed(() => {
// Fetch available records for the lookup // Fetch available records for the lookup
const fetchRecords = async () => { const fetchRecords = async () => {
if (!relationObject.value) {
records.value = []
return
}
loading.value = true loading.value = true
try { try {
const endpoint = `${props.baseUrl}/${relationObject.value}/records` const endpoint = `${props.baseUrl}/${relationObject.value}/records`
const response = await api.get(endpoint) const response = await api.get(endpoint)
records.value = response || [] records.value = Array.isArray(response)
? response
: response?.data || response?.records || []
// If we have a modelValue, find the selected record // If we have a modelValue, find the selected record
if (props.modelValue) { if (props.modelValue) {
@@ -71,6 +93,15 @@ const fetchRecords = async () => {
} }
} }
const handleRelationTypeChange = (value: string) => {
selectedRelationObject.value = value
emit('update:relationTypeValue', value)
searchQuery.value = ''
selectedRecord.value = null
emit('update:modelValue', null)
fetchRecords()
}
// Handle record selection // Handle record selection
const selectRecord = (record: any) => { const selectRecord = (record: any) => {
selectedRecord.value = record selectedRecord.value = record
@@ -93,7 +124,24 @@ watch(() => props.modelValue, (newValue) => {
} }
}) })
watch(() => props.relationTypeValue, (newValue) => {
if (!newValue) return
if (availableRelationObjects.value.includes(newValue)) {
selectedRelationObject.value = newValue
fetchRecords()
}
})
onMounted(() => { onMounted(() => {
selectedRelationObject.value = props.relationTypeValue && availableRelationObjects.value.includes(props.relationTypeValue)
? props.relationTypeValue
: availableRelationObjects.value[0] || null
// Emit initial relation type if we have a default selection so hidden relationTypeField gets populated
if (selectedRelationObject.value) {
emit('update:relationTypeValue', selectedRelationObject.value)
}
fetchRecords() fetchRecords()
}) })
</script> </script>
@@ -102,6 +150,25 @@ onMounted(() => {
<div class="lookup-field space-y-2"> <div class="lookup-field space-y-2">
<Popover v-model:open="open"> <Popover v-model:open="open">
<div class="flex gap-2"> <div class="flex gap-2">
<Select
v-if="shouldShowTypeSelector"
:model-value="relationObject"
:disabled="readonly || loading"
@update:model-value="handleRelationTypeChange"
>
<SelectTrigger class="w-40">
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent>
<SelectItem
v-for="option in availableRelationObjects"
:key="option"
:value="option"
>
{{ option }}
</SelectItem>
</SelectContent>
</Select>
<PopoverTrigger as-child> <PopoverTrigger as-child>
<Button <Button
variant="outline" variant="outline"
@@ -130,7 +197,7 @@ onMounted(() => {
<Command> <Command>
<CommandInput <CommandInput
v-model="searchQuery" v-model="searchQuery"
placeholder="Search..." :placeholder="relationObject ? `Search ${relationObject}...` : 'Search...'"
/> />
<CommandEmpty> <CommandEmpty>
{{ loading ? 'Loading...' : 'No results found.' }} {{ loading ? 'Loading...' : 'No results found.' }}

View File

@@ -0,0 +1,181 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Separator } from '@/components/ui/separator'
import { useApi } from '@/composables/useApi'
import { useAuth } from '@/composables/useAuth'
type CommentRecord = {
id: string
content: string
author_user_id: string
created_at: string
updated_at: string
}
interface Props {
objectApiName: string
recordId: string
}
const props = defineProps<Props>()
const { api } = useApi()
const { user } = useAuth()
const comments = ref<CommentRecord[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const newComment = ref('')
const saving = ref(false)
const editingId = ref<string | null>(null)
const editContent = ref('')
const isOwner = (comment: CommentRecord) => comment.author_user_id === user.value?.id
const formatDate = (value?: string) => {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return value
return date.toLocaleString()
}
const canSubmit = computed(() => newComment.value.trim().length > 0 && !saving.value)
const canSaveEdit = computed(() => editContent.value.trim().length > 0 && !saving.value)
const fetchComments = async () => {
if (!props.objectApiName || !props.recordId) return
loading.value = true
error.value = null
try {
const data = await api.get(`/knowledge/comments/${props.objectApiName}/${props.recordId}`)
comments.value = Array.isArray(data) ? data : []
} catch (e: any) {
error.value = e.message || 'Failed to load comments'
} finally {
loading.value = false
}
}
const addComment = async () => {
if (!canSubmit.value) return
saving.value = true
try {
await api.post('/knowledge/comments', {
parentObjectApiName: props.objectApiName,
parentRecordId: props.recordId,
content: newComment.value.trim(),
})
newComment.value = ''
await fetchComments()
} catch (e: any) {
error.value = e.message || 'Failed to add comment'
} finally {
saving.value = false
}
}
const startEdit = (comment: CommentRecord) => {
editingId.value = comment.id
editContent.value = comment.content
}
const cancelEdit = () => {
editingId.value = null
editContent.value = ''
}
const saveEdit = async () => {
if (!editingId.value || !canSaveEdit.value) return
saving.value = true
try {
await api.patch(`/knowledge/comments/${editingId.value}`, {
content: editContent.value.trim(),
})
editingId.value = null
editContent.value = ''
await fetchComments()
} catch (e: any) {
error.value = e.message || 'Failed to update comment'
} finally {
saving.value = false
}
}
const deleteComment = async (comment: CommentRecord) => {
if (!confirm('Delete this comment?')) return
saving.value = true
try {
await api.delete(`/knowledge/comments/${comment.id}`)
await fetchComments()
} catch (e: any) {
error.value = e.message || 'Failed to delete comment'
} finally {
saving.value = false
}
}
watch(
() => [props.objectApiName, props.recordId],
() => {
fetchComments()
},
{ immediate: true },
)
</script>
<template>
<Card>
<CardHeader>
<CardTitle>Comments</CardTitle>
</CardHeader>
<CardContent class="space-y-4">
<div class="space-y-3">
<Textarea
v-model="newComment"
placeholder="Add a comment..."
:disabled="saving"
class="min-h-[96px]"
/>
<div class="flex items-center justify-between">
<p class="text-sm text-muted-foreground" v-if="error">{{ error }}</p>
<Button size="sm" :disabled="!canSubmit" @click="addComment">
Add Comment
</Button>
</div>
</div>
<Separator />
<div v-if="loading" class="text-sm text-muted-foreground">Loading comments...</div>
<div v-else-if="comments.length === 0" class="text-sm text-muted-foreground">
No comments yet.
</div>
<div v-else class="space-y-4">
<div v-for="comment in comments" :key="comment.id" class="rounded-lg border p-4 space-y-2">
<div class="flex items-center justify-between">
<div class="text-xs text-muted-foreground">
<span>Author: {{ comment.author_user_id }}</span>
<span class="mx-2"></span>
<span>{{ formatDate(comment.created_at) }}</span>
</div>
<div class="flex items-center gap-2" v-if="isOwner(comment)">
<Button variant="ghost" size="sm" @click="startEdit(comment)">Edit</Button>
<Button variant="ghost" size="sm" @click="deleteComment(comment)">Delete</Button>
</div>
</div>
<div v-if="editingId === comment.id" class="space-y-2">
<Textarea v-model="editContent" :disabled="saving" class="min-h-[80px]" />
<div class="flex items-center gap-2">
<Button size="sm" :disabled="!canSaveEdit" @click="saveEdit">Save</Button>
<Button variant="ghost" size="sm" @click="cancelEdit">Cancel</Button>
</div>
</div>
<p v-else class="text-sm whitespace-pre-line">{{ comment.content }}</p>
</div>
</div>
</CardContent>
</Card>
</template>

View File

@@ -0,0 +1,220 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Separator } from '@/components/ui/separator'
import { useApi } from '@/composables/useApi'
type SemanticLink = {
id: string
source_entity_type: string
source_entity_id: string
target_entity_type: string
target_entity_id: string
link_type: string
status: string
origin: string
confidence?: number
reason?: string
evidence?: any
updated_at?: string
}
interface Props {
objectApiName: string
recordId: string
}
const props = defineProps<Props>()
const { api } = useApi()
const links = ref<SemanticLink[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const activeTab = ref<'all' | 'suggested' | 'approved' | 'rejected' | 'dismissed'>('suggested')
const formatDate = (value?: string) => {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return value
return date.toLocaleString()
}
const formatConfidence = (value?: number) => {
if (value === undefined || value === null) return '—'
return `${Math.round(value * 100)}%`
}
const getOtherSide = (link: SemanticLink) => {
const isSource =
link.source_entity_type === props.objectApiName &&
link.source_entity_id === props.recordId
return {
entityType: isSource ? link.target_entity_type : link.source_entity_type,
entityId: isSource ? link.target_entity_id : link.source_entity_id,
}
}
const parseEvidence = (raw: any) => {
if (!raw) return null
if (typeof raw === 'object') return raw
try {
return JSON.parse(raw)
} catch {
return null
}
}
const fetchLinks = async () => {
if (!props.objectApiName || !props.recordId) return
loading.value = true
error.value = null
try {
const params =
activeTab.value === 'all'
? undefined
: { status: activeTab.value }
const data = await api.get(`/knowledge/semantic/links/${props.objectApiName}/${props.recordId}`, {
params,
})
links.value = Array.isArray(data) ? data : []
} catch (e: any) {
error.value = e.message || 'Failed to load semantic links'
} finally {
loading.value = false
}
}
const reviewLink = async (id: string, status: 'approved' | 'rejected' | 'dismissed') => {
try {
await api.patch(`/knowledge/semantic/links/${id}/review`, { status })
await fetchLinks()
} catch (e: any) {
error.value = e.message || 'Failed to update link'
}
}
const canApprove = (status: string) => status !== 'approved'
const canReject = (status: string) => status !== 'rejected'
const canDismiss = (status: string) => status !== 'dismissed'
watch(
() => [props.objectApiName, props.recordId, activeTab.value],
() => {
fetchLinks()
},
{ immediate: true },
)
</script>
<template>
<Card>
<CardHeader class="flex flex-row items-center justify-between">
<CardTitle>Semantic Links</CardTitle>
<Button variant="ghost" size="sm" @click="fetchLinks">Refresh</Button>
</CardHeader>
<CardContent class="space-y-4">
<Tabs v-model="activeTab" class="space-y-4">
<TabsList>
<TabsTrigger value="suggested">Suggested</TabsTrigger>
<TabsTrigger value="approved">Approved</TabsTrigger>
<TabsTrigger value="rejected">Rejected</TabsTrigger>
<TabsTrigger value="dismissed">Dismissed</TabsTrigger>
<TabsTrigger value="all">All</TabsTrigger>
</TabsList>
<TabsContent :value="activeTab" class="space-y-4">
<div v-if="loading" class="text-sm text-muted-foreground">
Loading links...
</div>
<div v-else-if="error" class="text-sm text-destructive">
{{ error }}
</div>
<div v-else-if="links.length === 0" class="text-sm text-muted-foreground">
No links found.
</div>
<div v-else class="space-y-4">
<div
v-for="link in links"
:key="link.id"
class="rounded-lg border p-4 space-y-3"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="text-sm font-medium">
{{ getOtherSide(link).entityType }} · {{ getOtherSide(link).entityId }}
</div>
<div class="text-xs text-muted-foreground">
{{ link.link_type }} {{ link.origin }} {{ formatConfidence(link.confidence) }}
</div>
</div>
<div class="text-xs text-muted-foreground">
Status: <span class="font-medium text-foreground">{{ link.status }}</span>
<span v-if="link.updated_at" class="ml-2">Updated: {{ formatDate(link.updated_at) }}</span>
</div>
<p v-if="link.reason" class="text-sm">{{ link.reason }}</p>
<div v-if="parseEvidence(link.evidence)" class="text-xs text-muted-foreground space-y-2">
<Separator />
<div>
<div class="font-medium text-foreground">Evidence</div>
<div v-if="parseEvidence(link.evidence)?.sourceSignals?.length">
<div class="mt-1">Source signals:</div>
<ul class="list-disc pl-4">
<li
v-for="(signal, idx) in parseEvidence(link.evidence).sourceSignals"
:key="idx"
>
{{ signal.sourceKind }}: {{ signal.text }}
</li>
</ul>
</div>
<div v-if="parseEvidence(link.evidence)?.matchedChunks?.length" class="mt-2">
<div>Matched:</div>
<ul class="list-disc pl-4">
<li
v-for="(match, idx) in parseEvidence(link.evidence).matchedChunks"
:key="idx"
>
{{ match.sourceKind }}: {{ match.text }}
</li>
</ul>
</div>
</div>
</div>
<div class="flex items-center gap-2">
<Button
size="sm"
variant="outline"
@click="reviewLink(link.id, 'approved')"
:disabled="!canApprove(link.status)"
>
Approve
</Button>
<Button
size="sm"
variant="outline"
@click="reviewLink(link.id, 'rejected')"
:disabled="!canReject(link.status)"
>
Reject
</Button>
<Button
size="sm"
variant="outline"
@click="reviewLink(link.id, 'dismissed')"
:disabled="!canDismiss(link.status)"
>
Dismiss
</Button>
</div>
</div>
</div>
</TabsContent>
</Tabs>
</CardContent>
</Card>
</template>

View File

@@ -18,7 +18,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
<CheckboxRoot <CheckboxRoot
v-bind="forwarded" v-bind="forwarded"
:class=" :class="
cn('grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground', cn('grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
props.class)" props.class)"
> >
<CheckboxIndicator class="grid place-content-center text-current"> <CheckboxIndicator class="grid place-content-center text-current">

View File

@@ -0,0 +1,16 @@
<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>

View File

@@ -2,3 +2,4 @@ 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'

View File

@@ -5,6 +5,8 @@ import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
import FieldRenderer from '@/components/fields/FieldRenderer.vue' import FieldRenderer from '@/components/fields/FieldRenderer.vue'
import RelatedList from '@/components/RelatedList.vue' import RelatedList from '@/components/RelatedList.vue'
import RecordCommentsPanel from '@/components/knowledge/RecordCommentsPanel.vue'
import SemanticLinksPanel from '@/components/knowledge/SemanticLinksPanel.vue'
import { DetailViewConfig, ViewMode, FieldSection, FieldConfig, RelatedListConfig } from '@/types/field-types' import { DetailViewConfig, ViewMode, FieldSection, FieldConfig, RelatedListConfig } from '@/types/field-types'
import { Edit, Trash2, ArrowLeft } from 'lucide-vue-next' import { Edit, Trash2, ArrowLeft } from 'lucide-vue-next'
import { import {
@@ -167,6 +169,18 @@ const getFieldsBySection = (section: FieldSection) => {
@create="(objectApiName, parentId) => emit('createRelated', objectApiName, parentId)" @create="(objectApiName, parentId) => emit('createRelated', objectApiName, parentId)"
/> />
</div> </div>
<!-- Knowledge Panels -->
<div v-if="data?.id && config?.objectApiName" class="space-y-6">
<RecordCommentsPanel
:object-api-name="config.objectApiName"
:record-id="data.id"
/>
<SemanticLinksPanel
:object-api-name="config.objectApiName"
:record-id="data.id"
/>
</div>
</div> </div>
</template> </template>

View File

@@ -7,6 +7,8 @@ import FieldRenderer from '@/components/fields/FieldRenderer.vue'
import PageLayoutRenderer from '@/components/PageLayoutRenderer.vue' import PageLayoutRenderer from '@/components/PageLayoutRenderer.vue'
import RelatedList from '@/components/RelatedList.vue' import RelatedList from '@/components/RelatedList.vue'
import RecordSharing from '@/components/RecordSharing.vue' import RecordSharing from '@/components/RecordSharing.vue'
import RecordCommentsPanel from '@/components/knowledge/RecordCommentsPanel.vue'
import SemanticLinksPanel from '@/components/knowledge/SemanticLinksPanel.vue'
import { DetailViewConfig, ViewMode, FieldSection, FieldConfig, RelatedListConfig } from '@/types/field-types' import { DetailViewConfig, ViewMode, FieldSection, FieldConfig, RelatedListConfig } from '@/types/field-types'
import { Edit, Trash2, ArrowLeft } from 'lucide-vue-next' import { Edit, Trash2, ArrowLeft } from 'lucide-vue-next'
import { import {
@@ -87,6 +89,32 @@ const getFieldsBySection = (section: FieldSection) => {
const usePageLayout = computed(() => { const usePageLayout = computed(() => {
return pageLayout.value && pageLayout.value.fields && pageLayout.value.fields.length > 0 return pageLayout.value && pageLayout.value.fields && pageLayout.value.fields.length > 0
}) })
const visibleRelatedLists = computed<RelatedListConfig[]>(() => {
const relatedLists = props.config.relatedLists || []
if (!relatedLists.length) return []
if (!usePageLayout.value) {
return relatedLists
}
const layoutRelatedLists = pageLayout.value?.relatedLists
if (!layoutRelatedLists || layoutRelatedLists.length === 0) {
// Page layout has no related list selections; show all by default
return relatedLists
}
const normalize = (name: string) => name?.toLowerCase().replace(/[^a-z0-9]/g, '')
const layoutNormalized = layoutRelatedLists.map(normalize)
const filtered = relatedLists.filter(list => {
const name = list.relationName
return layoutRelatedLists.includes(name) || layoutNormalized.includes(normalize(name))
})
// If nothing matched (e.g., relationName changed), fall back to showing all
return filtered.length > 0 ? filtered : relatedLists
})
</script> </script>
<template> <template>
@@ -138,12 +166,15 @@ const usePageLayout = computed(() => {
<Tabs v-else default-value="details" class="space-y-6"> <Tabs v-else default-value="details" class="space-y-6">
<TabsList> <TabsList>
<TabsTrigger value="details">Details</TabsTrigger> <TabsTrigger value="details">Details</TabsTrigger>
<TabsTrigger v-if="config.relatedLists && config.relatedLists.length > 0" value="related"> <TabsTrigger v-if="visibleRelatedLists.length > 0" value="related">
Related Related
</TabsTrigger> </TabsTrigger>
<TabsTrigger v-if="showSharing && data.id" value="sharing"> <TabsTrigger v-if="showSharing && data.id" value="sharing">
Sharing Sharing
</TabsTrigger> </TabsTrigger>
<TabsTrigger v-if="data.id && config.objectApiName" value="knowledge">
Knowledge
</TabsTrigger>
</TabsList> </TabsList>
<!-- Details Tab --> <!-- Details Tab -->
@@ -224,13 +255,14 @@ const usePageLayout = computed(() => {
<!-- Related Lists Tab --> <!-- Related Lists Tab -->
<TabsContent value="related" class="space-y-6"> <TabsContent value="related" class="space-y-6">
<div v-if="config.relatedLists && config.relatedLists.length > 0"> <div v-if="visibleRelatedLists.length > 0">
<RelatedList <RelatedList
v-for="relatedList in config.relatedLists" v-for="relatedList in visibleRelatedLists"
:key="relatedList.relationName" :key="relatedList.relationName"
:config="relatedList" :config="relatedList"
:parent-id="data.id" :parent-id="data.id"
:related-records="data[relatedList.relationName]" :related-records="data[relatedList.relationName]"
:base-url="baseUrl"
@navigate="(objectApiName, recordId) => emit('navigate', objectApiName, recordId)" @navigate="(objectApiName, recordId) => emit('navigate', objectApiName, recordId)"
@create="(objectApiName, parentId) => emit('createRelated', objectApiName, parentId)" @create="(objectApiName, parentId) => emit('createRelated', objectApiName, parentId)"
/> />
@@ -250,6 +282,20 @@ const usePageLayout = computed(() => {
</CardContent> </CardContent>
</Card> </Card>
</TabsContent> </TabsContent>
<!-- Knowledge Tab -->
<TabsContent value="knowledge" class="space-y-6">
<RecordCommentsPanel
v-if="data.id && config.objectApiName"
:object-api-name="config.objectApiName"
:record-id="data.id"
/>
<SemanticLinksPanel
v-if="data.id && config.objectApiName"
:object-api-name="config.objectApiName"
:record-id="data.id"
/>
</TabsContent>
</Tabs> </Tabs>
</div> </div>
</template> </template>

View File

@@ -159,6 +159,13 @@ const updateFieldValue = (apiName: string, value: any) => {
delete errors.value[apiName] delete errors.value[apiName]
} }
} }
const handleRelatedFieldsUpdate = (values: Record<string, any>) => {
formData.value = {
...formData.value,
...values,
}
}
</script> </script>
<template> <template>
@@ -223,7 +230,9 @@ const updateFieldValue = (apiName: string, value: any) => {
:field="field" :field="field"
:model-value="formData[field.apiName]" :model-value="formData[field.apiName]"
:mode="ViewMode.EDIT" :mode="ViewMode.EDIT"
:record-data="formData"
@update:model-value="updateFieldValue(field.apiName, $event)" @update:model-value="updateFieldValue(field.apiName, $event)"
@update:related-fields="handleRelatedFieldsUpdate"
/> />
<p v-if="errors[field.apiName]" class="text-sm text-destructive"> <p v-if="errors[field.apiName]" class="text-sm text-destructive">
{{ errors[field.apiName] }} {{ errors[field.apiName] }}
@@ -252,7 +261,9 @@ const updateFieldValue = (apiName: string, value: any) => {
:field="field" :field="field"
:model-value="formData[field.apiName]" :model-value="formData[field.apiName]"
:mode="ViewMode.EDIT" :mode="ViewMode.EDIT"
:record-data="formData"
@update:model-value="updateFieldValue(field.apiName, $event)" @update:model-value="updateFieldValue(field.apiName, $event)"
@update:related-fields="handleRelatedFieldsUpdate"
/> />
<p v-if="errors[field.apiName]" class="text-sm text-destructive"> <p v-if="errors[field.apiName]" class="text-sm text-destructive">
{{ errors[field.apiName] }} {{ errors[field.apiName] }}

View File

@@ -176,6 +176,13 @@ const handleFieldUpdate = (fieldName: string, value: any) => {
delete errors.value[fieldName] delete errors.value[fieldName]
} }
} }
const handleRelatedFieldsUpdate = (values: Record<string, any>) => {
formData.value = {
...formData.value,
...values,
}
}
</script> </script>
<template> <template>
@@ -259,10 +266,12 @@ const handleFieldUpdate = (fieldName: string, value: any) => {
<FieldRenderer <FieldRenderer
:field="field" :field="field"
:model-value="formData[field.apiName]" :model-value="formData[field.apiName]"
:record-data="formData"
:mode="ViewMode.EDIT" :mode="ViewMode.EDIT"
:error="errors[field.apiName]" :error="errors[field.apiName]"
:base-url="baseUrl" :base-url="baseUrl"
@update:model-value="handleFieldUpdate(field.apiName, $event)" @update:model-value="handleFieldUpdate(field.apiName, $event)"
@update:related-fields="handleRelatedFieldsUpdate"
/> />
</div> </div>
</div> </div>
@@ -283,10 +292,12 @@ const handleFieldUpdate = (fieldName: string, value: any) => {
<FieldRenderer <FieldRenderer
:field="field" :field="field"
:model-value="formData[field.apiName]" :model-value="formData[field.apiName]"
:record-data="formData"
:mode="ViewMode.EDIT" :mode="ViewMode.EDIT"
:error="errors[field.apiName]" :error="errors[field.apiName]"
:base-url="baseUrl" :base-url="baseUrl"
@update:model-value="handleFieldUpdate(field.apiName, $event)" @update:model-value="handleFieldUpdate(field.apiName, $event)"
@update:related-fields="handleRelatedFieldsUpdate"
/> />
</div> </div>
</div> </div>

View File

@@ -1,5 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted } 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,
@@ -12,9 +16,18 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' 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 {
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 } from '@/types/field-types' import { ListViewConfig, ViewMode, FieldType, FieldConfig } from '@/types/field-types'
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit } from 'lucide-vue-next' import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit, Bookmark, BookmarkPlus, Settings2 } from 'lucide-vue-next'
import type { SavedView } from '@/composables/useSavedViews'
interface Props { interface Props {
config: ListViewConfig config: ListViewConfig
@@ -22,6 +35,16 @@ interface Props {
loading?: boolean loading?: boolean
selectable?: boolean selectable?: boolean
baseUrl?: string baseUrl?: string
totalCount?: number
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>(), {
@@ -29,6 +52,14 @@ const props = withDefaults(defineProps<Props>(), {
loading: false, loading: false,
selectable: false, selectable: false,
baseUrl: '/runtime/objects', baseUrl: '/runtime/objects',
searchSummary: '',
draftEdits: () => ({}),
cellErrors: () => ({}),
savingDrafts: false,
savedViews: () => [],
activeViewId: null,
currentSearchPlan: null,
savingView: false,
}) })
const emit = defineEmits<{ const emit = defineEmits<{
@@ -41,41 +72,103 @@ const emit = defineEmits<{
'sort': [field: string, direction: 'asc' | 'desc'] 'sort': [field: string, direction: 'asc' | 'desc']
'search': [query: string] 'search': [query: string]
'refresh': [] 'refresh': []
'page-change': [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
const selectedRows = ref<Set<string>>(new Set()) const normalizeId = (id: any) => String(id)
const selectedRowIds = ref<string[]>([])
const searchQuery = ref('') const searchQuery = ref('')
const sortField = ref<string>('') const sortField = ref<string>('')
const sortDirection = ref<'asc' | 'desc'>('asc') const sortDirection = ref<'asc' | 'desc'>('asc')
const currentPage = ref(1)
const bulkAction = ref('delete')
const viewMode = ref<'list' | 'spreadsheet'>('list')
const gridApi = ref<GridApi | null>(null)
// Computed // Computed
const visibleFields = computed(() => const visibleFields = computed(() =>
props.config.fields.filter(f => f.showOnList !== false) props.config.fields.filter(f => f.showOnList !== false)
) )
const pageSize = computed(() => props.config.pageSize ?? 10)
const maxFrontendRecords = computed(() => props.config.maxFrontendRecords ?? 500)
const totalRecords = computed(() =>
(props.totalCount && props.totalCount > 0)
? props.totalCount
: props.data.length
)
const useHybridPagination = computed(() => totalRecords.value > maxFrontendRecords.value)
const totalPages = computed(() => Math.max(1, Math.ceil(totalRecords.value / pageSize.value)))
const loadedPages = computed(() => Math.max(1, Math.ceil(props.data.length / pageSize.value)))
const availablePages = computed(() => {
if (useHybridPagination.value && props.totalCount && props.data.length < props.totalCount) {
return loadedPages.value
}
return totalPages.value
})
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)
const paginatedData = computed(() => {
const start = startIndex.value
const end = start + pageSize.value
return props.data.slice(start, end)
})
const pageStart = computed(() => (props.data.length === 0 ? 0 : startIndex.value + 1))
const pageEnd = computed(() => Math.min(startIndex.value + paginatedData.value.length, totalRecords.value))
const showPagination = computed(() => viewMode.value === 'list' && totalRecords.value > pageSize.value)
const canGoPrev = computed(() => currentPage.value > 1)
const canGoNext = computed(() => currentPage.value < availablePages.value)
const showLoadMore = computed(() => (
useHybridPagination.value &&
Boolean(props.totalCount) &&
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 && selectedRows.value.size === props.data.length, get: () => props.data.length > 0 && selectedRowIds.value.length === props.data.length,
set: (val: boolean) => { set: (val: boolean) => {
if (val) { if (val) {
selectedRows.value = new Set(props.data.map(row => row.id)) selectedRowIds.value = props.data.map(row => normalizeId(row.id))
} else { } else {
selectedRows.value.clear() selectedRowIds.value = []
} }
emit('row-select', getSelectedRows()) emit('row-select', getSelectedRows())
}, },
}) })
const getSelectedRows = () => { const getSelectedRows = () => {
return props.data.filter(row => selectedRows.value.has(row.id)) const idSet = new Set(selectedRowIds.value)
return props.data.filter(row => idSet.has(normalizeId(row.id)))
} }
const toggleRowSelection = (rowId: string) => { const toggleRowSelection = (rowId: string) => {
if (selectedRows.value.has(rowId)) { const normalizedId = normalizeId(rowId)
selectedRows.value.delete(rowId) const nextSelection = new Set(selectedRowIds.value)
nextSelection.has(normalizedId) ? nextSelection.delete(normalizedId) : nextSelection.add(normalizedId)
selectedRowIds.value = Array.from(nextSelection)
emit('row-select', getSelectedRows())
}
const setRowSelection = (rowId: string, checked: boolean) => {
const normalizedId = normalizeId(rowId)
const nextSelection = new Set(selectedRowIds.value)
if (checked) {
nextSelection.add(normalizedId)
} else { } else {
selectedRows.value.add(rowId) nextSelection.delete(normalizedId)
} }
selectedRowIds.value = Array.from(nextSelection)
emit('row-select', getSelectedRows()) emit('row-select', getSelectedRows())
} }
@@ -96,6 +189,214 @@ const handleSearch = () => {
const handleAction = (actionId: string) => { const handleAction = (actionId: string) => {
emit('action', actionId, getSelectedRows()) emit('action', actionId, getSelectedRows())
} }
const handleBulkAction = () => {
if (bulkAction.value === 'delete') {
emit('delete', getSelectedRows())
return
}
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 nextPage = Math.min(Math.max(page, 1), availablePages.value)
if (nextPage !== currentPage.value) {
currentPage.value = nextPage
emit('page-change', nextPage, pageSize.value)
}
}
const loadMore = () => {
const nextPage = Math.ceil(props.data.length / pageSize.value) + 1
emit('load-more', nextPage, pageSize.value)
}
watch(
() => [props.data.length, totalRecords.value, pageSize.value],
() => {
if (currentPage.value > availablePages.value) {
currentPage.value = availablePages.value
}
}
)
watch(
() => props.data,
(rows) => {
const rowIds = new Set(rows.map(row => normalizeId(row.id)))
const nextSelection = selectedRowIds.value.filter(id => rowIds.has(id))
if (nextSelection.length !== selectedRowIds.value.length) {
selectedRowIds.value = nextSelection
emit('row-select', getSelectedRows())
}
},
{ 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>
@@ -113,18 +414,120 @@ const handleAction = (actionId: string) => {
@keyup.enter="handleSearch" @keyup.enter="handleSearch"
/> />
</div> </div>
<p v-if="searchSummary" class="mt-2 text-xs text-muted-foreground">
{{ searchSummary }}
</p>
</div> </div>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<!-- Bulk Actions --> <!-- Saved Views dropdown + cog -->
<template v-if="selectedRows.size > 0"> <div class="flex items-center gap-1">
<Badge variant="secondary" class="px-3 py-1"> <DropdownMenu>
{{ selectedRows.size }} selected <DropdownMenuTrigger as-child>
</Badge> <Button variant="outline" size="sm" class="gap-2">
<Button variant="outline" size="sm" @click="emit('delete', getSelectedRows())"> <Bookmark class="h-4 w-4" />
<Trash2 class="h-4 w-4 mr-2" /> <span class="max-w-[120px] truncate">
Delete {{ 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> </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 -->
<template v-if="selectedRowIds.length > 0">
<Badge variant="secondary" class="px-3 py-1">
{{ selectedRowIds.length }} selected
</Badge>
<div class="flex items-center gap-2">
<Select v-model="bulkAction" @update:model-value="(value) => bulkAction = value">
<SelectTrigger class="h-8 w-[180px]">
<SelectValue placeholder="Select action" />
</SelectTrigger>
<SelectContent>
<SelectItem value="delete">Delete selected</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm" @click="handleBulkAction">
<Trash2 class="h-4 w-4 mr-2" />
Run
</Button>
</div>
</template> </template>
<!-- Custom Actions --> <!-- Custom Actions -->
@@ -154,11 +557,14 @@ const handleAction = (actionId: string) => {
<!-- Table --> <!-- Table -->
<div class="border rounded-lg"> <div class="border rounded-lg">
<Table> <Table v-if="viewMode === 'list'">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead v-if="selectable" class="w-12"> <TableHead v-if="selectable" class="w-12">
<Checkbox v-model:checked="allSelected" /> <Checkbox
:model-value="allSelected"
@update:model-value="(value: boolean) => (allSelected = value)"
/>
</TableHead> </TableHead>
<TableHead <TableHead
v-for="field in visibleFields" v-for="field in visibleFields"
@@ -192,15 +598,15 @@ const handleAction = (actionId: string) => {
</TableRow> </TableRow>
<TableRow <TableRow
v-else v-else
v-for="row in data" v-for="row in paginatedData"
:key="row.id" :key="row.id"
class="cursor-pointer hover:bg-muted/50" class="cursor-pointer hover:bg-muted/50"
@click="emit('row-click', row)" @click="emit('row-click', row)"
> >
<TableCell v-if="selectable" @click.stop> <TableCell v-if="selectable" @click.stop>
<Checkbox <Checkbox
:checked="selectedRows.has(row.id)" :model-value="selectedRowIds.includes(normalizeId(row.id))"
@update:checked="toggleRowSelection(row.id)" @update:model-value="(checked: boolean) => setRowSelection(normalizeId(row.id), checked)"
/> />
</TableCell> </TableCell>
<TableCell v-for="field in visibleFields" :key="field.id"> <TableCell v-for="field in visibleFields" :key="field.id">
@@ -225,9 +631,41 @@ const handleAction = (actionId: string) => {
</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>
<!-- Pagination would go here --> <div v-if="showPagination" class="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
<div class="flex items-center gap-2">
<span>Showing {{ pageStart }}-{{ pageEnd }} of {{ totalRecords }} records</span>
<span v-if="showLoadMore">
(loaded {{ data.length }})
</span>
</div>
<div class="flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" :disabled="!canGoPrev" @click="goToPage(currentPage - 1)">
Previous
</Button>
<span class="px-2">Page {{ currentPage }} of {{ totalPages }}</span>
<Button variant="outline" size="sm" :disabled="!canGoNext" @click="goToPage(currentPage + 1)">
Next
</Button>
<Button v-if="showLoadMore" variant="secondary" size="sm" @click="loadMore">
Load more
</Button>
</div>
</div>
</div> </div>
</template> </template>
@@ -243,4 +681,5 @@ const handleAction = (actionId: string) => {
.list-view :deep(input) { .list-view :deep(input) {
background-color: hsl(var(--background)); background-color: hsl(var(--background));
} }
</style> </style>

View File

@@ -1,40 +1,25 @@
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 = () => {
if (import.meta.client) { // All API calls go through Nitro proxy - works for both SSR and client
// In browser, use current hostname but with port 3000 for API return ''
const currentHost = window.location.hostname
const protocol = window.location.protocol
//return `${protocol}//${currentHost}:3000`
return `${protocol}//${currentHost}`
}
// Fallback for SSR
return config.public.apiBaseUrl
} }
const getHeaders = () => { const getHeaders = () => {
// Headers are now minimal - auth and tenant are handled by the Nitro proxy
const headers: Record<string, string> = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
// Add tenant ID from localStorage or state
if (import.meta.client) {
const tenantId = localStorage.getItem('tenantId')
if (tenantId) {
headers['x-tenant-id'] = tenantId
}
const token = localStorage.getItem('token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
}
return headers return headers
} }

View File

@@ -1,61 +1,131 @@
/**
* 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 = () => {
if (!import.meta.client) return false return isAuthenticated.value
const token = localStorage.getItem('token')
const tenantId = localStorage.getItem('tenantId')
return !!(token && tenantId)
} }
const logout = async () => { /**
if (import.meta.client) { * Login with email and password
// Call backend logout endpoint * Calls the Nitro BFF login endpoint which sets HTTP-only cookies
try { */
const token = localStorage.getItem('token') const login = async (email: string, password: string) => {
const tenantId = localStorage.getItem('tenantId') isLoading.value = true
if (token) { try {
await fetch(`${config.public.apiBaseUrl}/api/auth/logout`, { const response = await $fetch('/api/auth/login', {
method: 'POST', method: 'POST',
headers: { body: { email, password },
'Authorization': `Bearer ${token}`, })
...(tenantId && { 'x-tenant-id': tenantId }),
}, if (response.success) {
}) user.value = response.user
} isAuthenticated.value = true
} catch (error) { return { success: true, user: response.user }
console.error('Logout error:', error)
} }
// Clear local storage return { success: false, error: 'Login failed' }
localStorage.removeItem('token') } catch (error: any) {
localStorage.removeItem('tenantId') const message = error.data?.message || error.message || 'Login failed'
localStorage.removeItem('user') return { success: false, error: message }
} finally {
// Clear cookie for server-side check isLoading.value = false
tokenCookie.value = null
// Set flash message for login page
authMessageCookie.value = 'Logged out successfully'
// Redirect to login page
router.push('/login')
} }
} }
/**
* Logout user
* Calls the Nitro BFF logout endpoint which clears HTTP-only cookies
*/
const logout = async () => {
try {
await $fetch('/api/auth/logout', {
method: 'POST',
})
} catch (error) {
console.error('Logout error:', error)
}
// Clear local state
user.value = null
isAuthenticated.value = false
// Set flash message for login page
authMessageCookie.value = 'Logged out successfully'
// Redirect to login page
router.push('/login')
}
/**
* Check current authentication status
* Validates session with backend via Nitro BFF
*/
const checkAuth = async () => {
isLoading.value = true
try {
const response = await $fetch('/api/auth/me', {
method: 'GET',
})
if (response.authenticated && response.user) {
user.value = response.user
isAuthenticated.value = true
return true
}
} catch (error) {
// Session invalid or expired
user.value = null
isAuthenticated.value = false
} finally {
isLoading.value = false
}
return false
}
/**
* Get current user
*/
const getUser = () => { const getUser = () => {
if (!import.meta.client) return null return user.value
const userStr = localStorage.getItem('user') }
return userStr ? JSON.parse(userStr) : null
/**
* Get current tenant ID from cookie
*/
const getTenantId = () => {
return tenantCookie.value
} }
return { return {
// State
user,
isAuthenticated,
isLoading,
// Methods
isLoggedIn, isLoggedIn,
login,
logout, logout,
checkAuth,
getUser, getUser,
getTenantId,
} }
} }

View File

@@ -20,6 +20,9 @@ export const useFields = () => {
// Hide system fields and auto-generated fields on edit // Hide system fields and auto-generated fields on edit
const shouldHideOnEdit = isSystemField || isAutoGeneratedField const shouldHideOnEdit = isSystemField || isAutoGeneratedField
// Hide 'id' field from list view by default (check both apiName and id field)
const shouldHideOnList = fieldDef.apiName === 'id' || fieldDef.label === 'Id' || fieldDef.label === 'ID'
return { return {
id: fieldDef.id, id: fieldDef.id,
apiName: fieldDef.apiName, apiName: fieldDef.apiName,
@@ -37,7 +40,7 @@ export const useFields = () => {
validationRules: fieldDef.validationRules || [], validationRules: fieldDef.validationRules || [],
// View options - only hide system and auto-generated fields by default // View options - only hide system and auto-generated fields by default
showOnList: fieldDef.showOnList ?? true, showOnList: fieldDef.showOnList ?? !shouldHideOnList,
showOnDetail: fieldDef.showOnDetail ?? true, showOnDetail: fieldDef.showOnDetail ?? true,
showOnEdit: fieldDef.showOnEdit ?? !shouldHideOnEdit, showOnEdit: fieldDef.showOnEdit ?? !shouldHideOnEdit,
sortable: fieldDef.sortable ?? true, sortable: fieldDef.sortable ?? true,
@@ -50,7 +53,9 @@ export const useFields = () => {
step: fieldDef.step, step: fieldDef.step,
accept: fieldDef.accept, accept: fieldDef.accept,
relationObject: fieldDef.relationObject, relationObject: fieldDef.relationObject,
relationObjects: fieldDef.relationObjects,
relationDisplayField: fieldDef.relationDisplayField, relationDisplayField: fieldDef.relationDisplayField,
relationTypeField: fieldDef.relationTypeField,
// Formatting // Formatting
format: fieldDef.format, format: fieldDef.format,
@@ -65,18 +70,43 @@ export const useFields = () => {
/** /**
* Build a ListView configuration from object definition * Build a ListView configuration from object definition
* @param objectDef - The object definition containing fields
* @param customConfig - Optional custom configuration
* @param listLayoutConfig - Optional list view layout configuration from page_layouts
*/ */
const buildListViewConfig = ( const buildListViewConfig = (
objectDef: any, objectDef: any,
customConfig?: Partial<ListViewConfig> customConfig?: Partial<ListViewConfig>,
listLayoutConfig?: { fields: Array<{ fieldId: string; order?: number }> } | null
): ListViewConfig => { ): ListViewConfig => {
const fields = objectDef.fields?.map(mapFieldDefinitionToConfig) || [] let fields = objectDef.fields?.map(mapFieldDefinitionToConfig) || []
// If a list layout is provided, filter and order fields according to it
if (listLayoutConfig && listLayoutConfig.fields && listLayoutConfig.fields.length > 0) {
// Sort layout fields by order
const sortedLayoutFields = [...listLayoutConfig.fields].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
// Map layout fields to actual field configs, preserving order
const orderedFields: FieldConfig[] = []
for (const layoutField of sortedLayoutFields) {
const fieldConfig = fields.find((f: FieldConfig) => f.id === layoutField.fieldId)
if (fieldConfig) {
orderedFields.push(fieldConfig)
}
}
// Use ordered fields if we found any, otherwise fall back to all fields
if (orderedFields.length > 0) {
fields = orderedFields
}
}
return { return {
objectApiName: objectDef.apiName, objectApiName: objectDef.apiName,
mode: 'list' as ViewMode, mode: 'list' as ViewMode,
fields, fields,
pageSize: 25, pageSize: 10,
maxFrontendRecords: 500,
searchable: true, searchable: true,
filterable: true, filterable: true,
exportable: true, exportable: true,
@@ -97,6 +127,7 @@ export const useFields = () => {
objectApiName: objectDef.apiName, objectApiName: objectDef.apiName,
mode: 'detail' as ViewMode, mode: 'detail' as ViewMode,
fields, fields,
relatedLists: objectDef.relatedLists || [],
...customConfig, ...customConfig,
} }
} }
@@ -180,6 +211,7 @@ export const useViewState = <T extends { id?: string }>(
apiEndpoint: string apiEndpoint: string
) => { ) => {
const records = ref<T[]>([]) const records = ref<T[]>([])
const totalCount = ref(0)
const currentRecord = ref<T | null>(null) const currentRecord = ref<T | null>(null)
const currentView = ref<'list' | 'detail' | 'edit'>('list') const currentView = ref<'list' | 'detail' | 'edit'>('list')
const loading = ref(false) const loading = ref(false)
@@ -188,13 +220,51 @@ export const useViewState = <T extends { id?: string }>(
const { api } = useApi() const { api } = useApi()
const fetchRecords = async (params?: Record<string, any>) => { const normalizeListResponse = (response: any) => {
const payload: { data: T[]; totalCount: number; page?: number; pageSize?: number } = {
data: [],
totalCount: 0,
}
if (Array.isArray(response)) {
payload.data = response
payload.totalCount = response.length
return payload
}
if (response && typeof response === 'object') {
if (Array.isArray(response.data)) {
payload.data = response.data
} else if (Array.isArray((response as any).records)) {
payload.data = (response as any).records
} else if (Array.isArray((response as any).results)) {
payload.data = (response as any).results
}
payload.totalCount =
response.totalCount ??
response.total ??
response.count ??
payload.data.length ??
0
payload.page = response.page
payload.pageSize = response.pageSize
}
return payload
}
const fetchRecords = async (params?: Record<string, any>, options?: { append?: boolean }) => {
loading.value = true loading.value = true
error.value = null error.value = null
try { try {
const response = await api.get(apiEndpoint, { params }) const response = await api.get(apiEndpoint, { params })
// Handle response - data might be directly in response or in response.data const normalized = normalizeListResponse(response)
records.value = response.data || response || [] totalCount.value = normalized.totalCount ?? normalized.data.length ?? 0
records.value = options?.append
? [...records.value, ...normalized.data]
: normalized.data
return normalized
} catch (e: any) { } catch (e: any) {
error.value = e.message error.value = e.message
console.error('Failed to fetch records:', e) console.error('Failed to fetch records:', e)
@@ -227,6 +297,7 @@ export const useViewState = <T extends { id?: string }>(
// Handle response - it might be the data directly or wrapped in { data: ... } // Handle response - it might be the data directly or wrapped in { data: ... }
const recordData = response.data || response const recordData = response.data || response
records.value.push(recordData) records.value.push(recordData)
totalCount.value += 1
currentRecord.value = recordData currentRecord.value = recordData
return recordData return recordData
} catch (e: any) { } catch (e: any) {
@@ -269,6 +340,7 @@ export const useViewState = <T extends { id?: string }>(
try { try {
await api.delete(`${apiEndpoint}/${id}`) await api.delete(`${apiEndpoint}/${id}`)
records.value = records.value.filter(r => r.id !== id) records.value = records.value.filter(r => r.id !== id)
totalCount.value = Math.max(0, totalCount.value - 1)
if (currentRecord.value?.id === id) { if (currentRecord.value?.id === id) {
currentRecord.value = null currentRecord.value = null
} }
@@ -285,8 +357,25 @@ export const useViewState = <T extends { id?: string }>(
loading.value = true loading.value = true
error.value = null error.value = null
try { try {
const useBulkEndpoint = apiEndpoint.includes('/runtime/objects/')
if (useBulkEndpoint) {
const response = await api.post(`${apiEndpoint}/bulk-delete`, { ids })
const deletedIds = Array.isArray(response?.deletedIds) ? response.deletedIds : ids
records.value = records.value.filter(r => !deletedIds.includes(r.id!))
totalCount.value = Math.max(0, totalCount.value - deletedIds.length)
return {
deletedIds,
deniedIds: Array.isArray(response?.deniedIds) ? response.deniedIds : [],
}
}
await Promise.all(ids.map(id => api.delete(`${apiEndpoint}/${id}`))) await Promise.all(ids.map(id => api.delete(`${apiEndpoint}/${id}`)))
records.value = records.value.filter(r => !ids.includes(r.id!)) records.value = records.value.filter(r => !ids.includes(r.id!))
totalCount.value = Math.max(0, totalCount.value - ids.length)
return {
deletedIds: ids,
deniedIds: [],
}
} catch (e: any) { } catch (e: any) {
error.value = e.message error.value = e.message
console.error('Failed to delete records:', e) console.error('Failed to delete records:', e)
@@ -324,6 +413,7 @@ export const useViewState = <T extends { id?: string }>(
return { return {
// State // State
records, records,
totalCount,
currentRecord, currentRecord,
currentView, currentView,
loading, loading,

View File

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

Some files were not shown because too many files have changed in this diff Show More