Compare commits
19 Commits
nitro-bff
...
codex/enha
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96989d0ec3 | ||
|
|
12a82372f4 | ||
|
|
efa57c4ba8 | ||
|
|
3f9be316ce | ||
|
|
385a842ab8 | ||
|
|
320f8c4266 | ||
|
|
12b0a0881e | ||
|
|
dc18b08a3a | ||
|
|
df183230d8 | ||
|
|
baf3997fb6 | ||
|
|
a2d48f6a03 | ||
|
|
fb2533fa4c | ||
|
|
12304d5890 | ||
|
|
a0bdb09c03 | ||
|
|
c89dc04d4c | ||
|
|
7a175923b0 | ||
|
|
ed48623f27 | ||
|
|
228c3fb704 | ||
|
|
5f14a4050a |
@@ -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');
|
||||
};
|
||||
@@ -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();
|
||||
};
|
||||
@@ -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');
|
||||
});
|
||||
};
|
||||
@@ -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');
|
||||
};
|
||||
@@ -20,6 +20,8 @@ model User {
|
||||
password String
|
||||
firstName String?
|
||||
lastName String?
|
||||
alias String?
|
||||
name String?
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -38,4 +38,12 @@ export class AiAssistantController {
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('suggest-view-name')
|
||||
async suggestViewName(
|
||||
@TenantId() tenantId: string,
|
||||
@Body() payload: { objectLabel: string; filters: any[]; explanation?: string },
|
||||
) {
|
||||
return this.aiAssistantService.suggestViewName(tenantId, payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ type AiSearchPayload = {
|
||||
@Injectable()
|
||||
export class AiAssistantService {
|
||||
private readonly logger = new Logger(AiAssistantService.name);
|
||||
private readonly defaultModel = process.env.OPENAI_MODEL || 'gpt-4o';
|
||||
private readonly defaultModel = process.env.OPENAI_MODEL || 'gpt-5.4-mini';
|
||||
private readonly conversationState = new Map<
|
||||
string,
|
||||
{ fields: Record<string, any>; updatedAt: number }
|
||||
@@ -688,6 +688,8 @@ export class AiAssistantService {
|
||||
totalCount: meiliResults.total ?? records.totalCount ?? 0,
|
||||
strategy: plan.strategy,
|
||||
explanation: plan.explanation,
|
||||
filters: [],
|
||||
sort: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -702,16 +704,28 @@ export class AiAssistantService {
|
||||
...fallback,
|
||||
strategy: plan.strategy,
|
||||
explanation: plan.explanation,
|
||||
filters: [],
|
||||
sort: null,
|
||||
};
|
||||
}
|
||||
|
||||
console.log('AI search plan (query):', plan);
|
||||
|
||||
// Resolve any LOOKUP filter values (user typed a name, we find the related record ID)
|
||||
const resolvedFilters = await this.resolveRelatedFilters(
|
||||
resolvedTenantId,
|
||||
userId,
|
||||
objectDefinition,
|
||||
plan.filters || [],
|
||||
);
|
||||
|
||||
console.log('Resolved filters for query strategy:', resolvedFilters);
|
||||
|
||||
const filtered = await this.objectService.searchRecordsWithFilters(
|
||||
resolvedTenantId,
|
||||
payload.objectApiName,
|
||||
userId,
|
||||
plan.filters || [],
|
||||
resolvedFilters,
|
||||
{ page, pageSize },
|
||||
plan.sort || undefined,
|
||||
);
|
||||
@@ -720,9 +734,53 @@ export class AiAssistantService {
|
||||
...filtered,
|
||||
strategy: plan.strategy,
|
||||
explanation: plan.explanation,
|
||||
filters: resolvedFilters,
|
||||
sort: plan.sort || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the LLM to suggest a short, human-friendly name for a saved list view
|
||||
* based on the resolved filters / explanation.
|
||||
*/
|
||||
async suggestViewName(
|
||||
tenantId: string,
|
||||
payload: { objectLabel: string; filters: AiSearchFilter[]; explanation?: string },
|
||||
): Promise<{ suggestedName: string }> {
|
||||
const openAiConfig = await this.getOpenAiConfig(tenantId);
|
||||
if (!openAiConfig) {
|
||||
return { suggestedName: `${payload.objectLabel} View` };
|
||||
}
|
||||
|
||||
const model = new ChatOpenAI({
|
||||
apiKey: openAiConfig.apiKey,
|
||||
model: this.normalizeChatModel(openAiConfig.model),
|
||||
temperature: 0.4,
|
||||
});
|
||||
|
||||
const filterSummary = payload.explanation?.trim()
|
||||
|| payload.filters.map(f => `${f.field} ${f.operator} ${f.value ?? ''}`).join(', ')
|
||||
|| 'no filters';
|
||||
|
||||
try {
|
||||
const response = await model.invoke([
|
||||
new SystemMessage(
|
||||
'You are a CRM assistant. Suggest a very short (2–5 words), descriptive, and human-friendly name for a saved list view. ' +
|
||||
'Reply with ONLY the name, no quotes or punctuation.',
|
||||
),
|
||||
new HumanMessage(
|
||||
`Object: ${payload.objectLabel}.\nFilter summary: ${filterSummary}`,
|
||||
),
|
||||
]);
|
||||
|
||||
const raw = typeof response.content === 'string' ? response.content.trim() : '';
|
||||
const suggestedName = raw || `${payload.objectLabel} View`;
|
||||
return { suggestedName };
|
||||
} catch {
|
||||
return { suggestedName: `${payload.objectLabel} View` };
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Planning-Based LangGraph Workflow
|
||||
// ============================================
|
||||
@@ -2207,6 +2265,59 @@ export class AiAssistantService {
|
||||
return extracted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves LOOKUP filter values from human-readable names to actual record IDs.
|
||||
* When the AI produces a filter like { field: "familyId", operator: "eq", value: "Gaona Family" },
|
||||
* this method looks up "Gaona Family" in the referenced object and replaces the value with its ID.
|
||||
*/
|
||||
private async resolveRelatedFilters(
|
||||
tenantId: string,
|
||||
userId: string,
|
||||
objectDefinition: any,
|
||||
filters: AiSearchFilter[],
|
||||
): Promise<AiSearchFilter[]> {
|
||||
if (!filters || filters.length === 0) return filters;
|
||||
|
||||
const lookupFieldMap = new Map<string, string>(); // apiName → referenceObject
|
||||
for (const field of objectDefinition.fields || []) {
|
||||
if (field.type === 'LOOKUP' && field.referenceObject) {
|
||||
lookupFieldMap.set(field.apiName, field.referenceObject);
|
||||
}
|
||||
}
|
||||
|
||||
const resolved: AiSearchFilter[] = [];
|
||||
for (const filter of filters) {
|
||||
const referenceObject = lookupFieldMap.get(filter.field);
|
||||
if (
|
||||
referenceObject &&
|
||||
filter.value &&
|
||||
typeof filter.value === 'string' &&
|
||||
!this.isUuid(filter.value)
|
||||
) {
|
||||
// Try to resolve the name to an ID in the referenced object
|
||||
try {
|
||||
console.log(`Resolving LOOKUP filter: ${filter.field} → searching "${filter.value}" in ${referenceObject}`);
|
||||
const relatedRecord = await this.searchForExistingRecord(tenantId, userId, referenceObject, filter.value);
|
||||
if (relatedRecord?.id) {
|
||||
console.log(`Resolved "${filter.value}" → ID: ${relatedRecord.id}`);
|
||||
resolved.push({ ...filter, operator: 'eq', value: relatedRecord.id });
|
||||
} else {
|
||||
// Could not resolve; keep as-is so we get 0 results rather than wrong ones
|
||||
console.warn(`Could not resolve related record "${filter.value}" in ${referenceObject}; keeping original filter`);
|
||||
resolved.push(filter);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to resolve lookup filter for ${filter.field}: ${err.message}`);
|
||||
resolved.push(filter);
|
||||
}
|
||||
} else {
|
||||
resolved.push(filter);
|
||||
}
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private async buildSearchPlan(
|
||||
tenantId: string,
|
||||
message: string,
|
||||
@@ -2250,25 +2361,65 @@ export class AiAssistantService {
|
||||
apiName: field.apiName,
|
||||
label: field.label,
|
||||
type: field.type,
|
||||
...(field.referenceObject ? { referenceObject: field.referenceObject } : {}),
|
||||
}));
|
||||
|
||||
const formatInstructions = parser.getFormatInstructions();
|
||||
const today = new Date().toISOString();
|
||||
|
||||
const systemPromptLines = [
|
||||
`You are a CRM search assistant. The user is browsing a list of "${objectDefinition.label || objectDefinition.apiName}" records.`,
|
||||
``,
|
||||
`Your task: decide whether the user input is a KEYWORD search or a STRUCTURED QUERY, then return the correct JSON plan.`,
|
||||
``,
|
||||
`=== STRATEGY DECISION RULES ===`,
|
||||
`Use strategy="query" when the user:`,
|
||||
` - Describes a record attribute or property value (e.g. "list all golden retrievers" → filter the race field)`,
|
||||
` - Uses phrases like "list all X", "show all X", "find all X", "filter by X", "where X is Y"`,
|
||||
` - Mentions a specific field value, status, category, type, breed, color, size, or any distinguishing characteristic`,
|
||||
` - Requests records matching a condition (e.g. "created this week", "price > 100", "active only")`,
|
||||
` - Asks for sorted or ordered results (e.g. "newest first", "alphabetically")`,
|
||||
``,
|
||||
`Use strategy="keyword" ONLY when the user types a bare search term with no clear field or attribute intent`,
|
||||
` - e.g. a lone name or identifier: "rex", "john", "acme corp"`,
|
||||
``,
|
||||
`=== HOW TO MAP USER LANGUAGE TO FIELDS ===`,
|
||||
`When the user describes a characteristic or property value, find the best-matching field from the Fields list`,
|
||||
`and apply a "contains" filter (or "eq" for exact values). Do NOT fall back to keyword just because the`,
|
||||
`field name is not explicitly mentioned — infer the intent from context.`,
|
||||
``,
|
||||
`EXAMPLES (Object = Dog, fields include: name, race, size, color, createdAt, familyId[LOOKUP→Family]):`,
|
||||
` "list all cocker spaniels" → strategy=query, filter: race contains "cocker spaniel"`,
|
||||
` "show golden retrievers" → strategy=query, filter: race contains "golden retriever"`,
|
||||
` "large dogs" → strategy=query, filter: size contains "large"`,
|
||||
` "dogs added this week" → strategy=query, filter: createdAt between <monday> <today>`,
|
||||
` "dogs belonging to Gaona Family" → strategy=query, filter: familyId eq "Gaona Family"`,
|
||||
` "rex" → strategy=keyword, keyword="rex"`,
|
||||
``,
|
||||
`=== LOOKUP FIELDS ===`,
|
||||
`Fields with type LOOKUP store a reference (ID) to another object (referenceObject).`,
|
||||
`When the user refers to a related record by its name (e.g. "belonging to Gaona Family"),`,
|
||||
`output the human-readable name as the filter value — the system will resolve it to the correct ID.`,
|
||||
`Use the LOOKUP field apiName (e.g. familyId) as the filter field.`,
|
||||
``,
|
||||
`=== OUTPUT FORMAT ===`,
|
||||
`Return a JSON object with these keys:`,
|
||||
` strategy : "keyword" or "query"`,
|
||||
` explanation : short plain-language description of what the search does`,
|
||||
` keyword : the search term when strategy is "keyword", otherwise null`,
|
||||
` filters : array of filter objects for strategy="query" (empty array otherwise)`,
|
||||
` sort : {field, direction} when sorting is requested, otherwise null`,
|
||||
``,
|
||||
`Each filter object: { field: <apiName>, operator: <op>, value?, values?, from?, to? }`,
|
||||
`Valid operators: eq | neq | gt | gte | lt | lte | contains | startsWith | endsWith | in | notIn | isNull | notNull | between`,
|
||||
`Use "between" with {from, to} for date ranges.`,
|
||||
`Only use field apiName values exactly as they appear in the Fields list provided.`,
|
||||
``,
|
||||
formatInstructions,
|
||||
].join('\n');
|
||||
|
||||
const response = await model.invoke([
|
||||
new SystemMessage(
|
||||
`You are a CRM search assistant. Decide whether the user input is a keyword search or a structured query.` +
|
||||
`\nReturn a JSON object with keys: strategy, explanation, keyword, filters, sort.` +
|
||||
`\n- strategy must be "keyword" or "query".` +
|
||||
`\n- explanation must be a short sentence explaining the approach.` +
|
||||
`\n- keyword should be the search term when strategy is "keyword", otherwise null.` +
|
||||
`\n- filters is an array of {field, operator, value, values, from, to}.` +
|
||||
`\n- operators must be one of eq, neq, gt, gte, lt, lte, contains, startsWith, endsWith, in, notIn, isNull, notNull, between.` +
|
||||
`\n- Use between with from/to when the user gives date ranges like "yesterday" or "last week".` +
|
||||
`\n- sort should be {field, direction} when sorting is requested.` +
|
||||
`\n- Only use field apiName values exactly as provided.` +
|
||||
`\n${formatInstructions}`,
|
||||
),
|
||||
new SystemMessage(systemPromptLines),
|
||||
new HumanMessage(
|
||||
`Object: ${objectDefinition.label || objectDefinition.apiName}.\n` +
|
||||
`Fields: ${JSON.stringify(fields)}.\n` +
|
||||
@@ -2279,10 +2430,30 @@ export class AiAssistantService {
|
||||
|
||||
const content = typeof response.content === 'string' ? response.content : '{}';
|
||||
const parsed = await parser.parse(content);
|
||||
return this.normalizeSearchPlan(parsed, message);
|
||||
const normalizedPlan = this.normalizeSearchPlan(parsed, message, objectDefinition);
|
||||
|
||||
console.log('AI search plan:', normalizedPlan);
|
||||
|
||||
if (normalizedPlan.strategy === 'query') {
|
||||
const aiExplanation = await this.generateQueryExplanationWithAi(
|
||||
model,
|
||||
message,
|
||||
objectDefinition,
|
||||
normalizedPlan,
|
||||
);
|
||||
if (aiExplanation) {
|
||||
normalizedPlan.explanation = aiExplanation;
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeSearchPlan(plan: AiSearchPlan, message: string): AiSearchPlan {
|
||||
return normalizedPlan;
|
||||
}
|
||||
|
||||
private normalizeSearchPlan(
|
||||
plan: AiSearchPlan,
|
||||
message: string,
|
||||
objectDefinition?: any,
|
||||
): AiSearchPlan {
|
||||
if (!plan || typeof plan !== 'object') {
|
||||
return this.buildSearchPlanFallback(message);
|
||||
}
|
||||
@@ -2302,15 +2473,158 @@ export class AiAssistantService {
|
||||
};
|
||||
}
|
||||
|
||||
const queryExplanation = this.buildQueryExplanation(
|
||||
message,
|
||||
objectDefinition,
|
||||
Array.isArray(plan.filters) ? plan.filters : [],
|
||||
plan.sort || null,
|
||||
);
|
||||
|
||||
return {
|
||||
strategy,
|
||||
explanation,
|
||||
explanation: queryExplanation || explanation,
|
||||
keyword: null,
|
||||
filters: Array.isArray(plan.filters) ? plan.filters : [],
|
||||
sort: plan.sort || null,
|
||||
};
|
||||
}
|
||||
|
||||
private buildQueryExplanation(
|
||||
message: string,
|
||||
objectDefinition: any,
|
||||
filters: AiSearchFilter[],
|
||||
sort: { field: string; direction: 'asc' | 'desc' } | null,
|
||||
): string {
|
||||
const fieldLabelByApiName = new Map<string, string>(
|
||||
(objectDefinition?.fields || []).map((field: any) => [field.apiName, field.label || field.apiName]),
|
||||
);
|
||||
const objectLabel = objectDefinition?.label || objectDefinition?.apiName || 'records';
|
||||
|
||||
const filterParts = filters
|
||||
.map((filter) => this.describeFilter(filter, fieldLabelByApiName))
|
||||
.filter(Boolean) as string[];
|
||||
|
||||
const sortLabel = sort?.field
|
||||
? fieldLabelByApiName.get(sort.field) || sort.field
|
||||
: null;
|
||||
const sortPart =
|
||||
sortLabel && sort?.direction
|
||||
? `sorted by ${sortLabel} (${sort.direction === 'desc' ? 'newest/highest first' : 'oldest/lowest first'})`
|
||||
: '';
|
||||
|
||||
if (filterParts.length > 0 && sortPart) {
|
||||
return `Showing ${objectLabel} where ${filterParts.join(' and ')}, ${sortPart}.`;
|
||||
}
|
||||
|
||||
if (filterParts.length > 0) {
|
||||
return `Showing ${objectLabel} where ${filterParts.join(' and ')}.`;
|
||||
}
|
||||
|
||||
if (sortPart) {
|
||||
return `Showing ${objectLabel} ${sortPart}.`;
|
||||
}
|
||||
|
||||
return `Applied filters based on: "${message.trim()}".`;
|
||||
}
|
||||
|
||||
private describeFilter(filter: AiSearchFilter, fieldLabelByApiName: Map<string, string>): string {
|
||||
const fieldLabel = fieldLabelByApiName.get(filter.field) || filter.field;
|
||||
const formatValue = (value: any) =>
|
||||
value === null || value === undefined || value === ''
|
||||
? 'empty'
|
||||
: typeof value === 'string'
|
||||
? `"${value}"`
|
||||
: String(value);
|
||||
|
||||
switch (filter.operator) {
|
||||
case 'eq':
|
||||
return `${fieldLabel} is ${formatValue(filter.value)}`;
|
||||
case 'neq':
|
||||
return `${fieldLabel} is not ${formatValue(filter.value)}`;
|
||||
case 'gt':
|
||||
return `${fieldLabel} is greater than ${formatValue(filter.value)}`;
|
||||
case 'gte':
|
||||
return `${fieldLabel} is at least ${formatValue(filter.value)}`;
|
||||
case 'lt':
|
||||
return `${fieldLabel} is less than ${formatValue(filter.value)}`;
|
||||
case 'lte':
|
||||
return `${fieldLabel} is at most ${formatValue(filter.value)}`;
|
||||
case 'contains':
|
||||
return `${fieldLabel} contains ${formatValue(filter.value)}`;
|
||||
case 'startsWith':
|
||||
return `${fieldLabel} starts with ${formatValue(filter.value)}`;
|
||||
case 'endsWith':
|
||||
return `${fieldLabel} ends with ${formatValue(filter.value)}`;
|
||||
case 'in':
|
||||
return `${fieldLabel} is one of ${(filter.values || []).map(formatValue).join(', ')}`;
|
||||
case 'notIn':
|
||||
return `${fieldLabel} is not one of ${(filter.values || []).map(formatValue).join(', ')}`;
|
||||
case 'isNull':
|
||||
return `${fieldLabel} is empty`;
|
||||
case 'notNull':
|
||||
return `${fieldLabel} is not empty`;
|
||||
case 'between':
|
||||
if (filter.from && filter.to) {
|
||||
return `${fieldLabel} is between ${formatValue(filter.from)} and ${formatValue(filter.to)}`;
|
||||
}
|
||||
if (filter.from) {
|
||||
return `${fieldLabel} is from ${formatValue(filter.from)} onward`;
|
||||
}
|
||||
if (filter.to) {
|
||||
return `${fieldLabel} is up to ${formatValue(filter.to)}`;
|
||||
}
|
||||
return `${fieldLabel} uses a date range filter`;
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
private async generateQueryExplanationWithAi(
|
||||
model: ChatOpenAI,
|
||||
message: string,
|
||||
objectDefinition: any,
|
||||
plan: AiSearchPlan,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const fields = (objectDefinition?.fields || []).map((field: any) => ({
|
||||
apiName: field.apiName,
|
||||
label: field.label || field.apiName,
|
||||
}));
|
||||
|
||||
const response = await model.invoke([
|
||||
new SystemMessage(
|
||||
`You explain CRM list query results in plain language for end users.` +
|
||||
`\nWrite one short sentence (max 25 words).` +
|
||||
`\nDescribe the resulting filters/sort in business language.` +
|
||||
`\nDo NOT mention SQL, JSON, "strategy", "query mode", or AI decision process.` +
|
||||
`\nIf values are present, mention the most important ones clearly.`,
|
||||
),
|
||||
new HumanMessage(
|
||||
`Object: ${objectDefinition?.label || objectDefinition?.apiName || 'records'}\n` +
|
||||
`User request: ${message}\n` +
|
||||
`Available fields: ${JSON.stringify(fields)}\n` +
|
||||
`Applied filters: ${JSON.stringify(plan.filters || [])}\n` +
|
||||
`Applied sort: ${JSON.stringify(plan.sort || null)}\n` +
|
||||
`Current explanation draft: ${plan.explanation}`,
|
||||
),
|
||||
]);
|
||||
|
||||
const content = Array.isArray(response.content)
|
||||
? response.content
|
||||
.map((part: any) => (typeof part === 'string' ? part : part?.text || ''))
|
||||
.join(' ')
|
||||
: String(response.content || '');
|
||||
const cleaned = content.trim().replace(/\s+/g, ' ');
|
||||
|
||||
console.log('AI-generated query explanation:', cleaned);
|
||||
|
||||
return cleaned || null;
|
||||
} catch (error) {
|
||||
this.logger.warn(`AI query explanation refinement failed: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sanitizeUserOwnerFields(
|
||||
fields: Record<string, any>,
|
||||
fieldDefinitions: any[],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { BullModule } from '@nestjs/bullmq';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { TenantModule } from './tenant/tenant.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
@@ -9,12 +10,20 @@ import { AppBuilderModule } from './app-builder/app-builder.module';
|
||||
import { PageLayoutModule } from './page-layout/page-layout.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({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
}),
|
||||
BullModule.forRoot({
|
||||
connection: {
|
||||
host: process.env.REDIS_HOST || 'platform-redis',
|
||||
port: parseInt(process.env.REDIS_PORT || '6379', 10),
|
||||
},
|
||||
}),
|
||||
PrismaModule,
|
||||
TenantModule,
|
||||
AuthModule,
|
||||
@@ -24,6 +33,8 @@ import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
|
||||
PageLayoutModule,
|
||||
VoiceModule,
|
||||
AiAssistantModule,
|
||||
SavedListViewModule,
|
||||
KnowledgeModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
24
backend/src/knowledge/dto/comment.dto.ts
Normal file
24
backend/src/knowledge/dto/comment.dto.ts
Normal 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;
|
||||
}
|
||||
52
backend/src/knowledge/dto/semantic-link.dto.ts
Normal file
52
backend/src/knowledge/dto/semantic-link.dto.ts
Normal 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>;
|
||||
}
|
||||
124
backend/src/knowledge/knowledge.controller.ts
Normal file
124
backend/src/knowledge/knowledge.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
31
backend/src/knowledge/knowledge.module.ts
Normal file
31
backend/src/knowledge/knowledge.module.ts
Normal 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 {}
|
||||
3
backend/src/knowledge/semantic-refresh.constants.ts
Normal file
3
backend/src/knowledge/semantic-refresh.constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const SEMANTIC_REFRESH_QUEUE = 'semantic-refresh';
|
||||
|
||||
export const SEMANTIC_REFRESH_JOB = 'refresh-record';
|
||||
45
backend/src/knowledge/semantic-refresh.processor.ts
Normal file
45
backend/src/knowledge/semantic-refresh.processor.ts
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
115
backend/src/knowledge/services/comment.service.ts
Normal file
115
backend/src/knowledge/services/comment.service.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
71
backend/src/knowledge/services/semantic-chunker.service.ts
Normal file
71
backend/src/knowledge/services/semantic-chunker.service.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
20
backend/src/knowledge/services/semantic-link.service.spec.ts
Normal file
20
backend/src/knowledge/services/semantic-link.service.spec.ts
Normal 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',
|
||||
});
|
||||
});
|
||||
});
|
||||
186
backend/src/knowledge/services/semantic-link.service.ts
Normal file
186
backend/src/knowledge/services/semantic-link.service.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
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 });
|
||||
}
|
||||
|
||||
const links = await query;
|
||||
if (!links.length) return links;
|
||||
|
||||
const typeSet = new Set<string>();
|
||||
for (const link of links) {
|
||||
typeSet.add(link.source_entity_type);
|
||||
typeSet.add(link.target_entity_type);
|
||||
}
|
||||
|
||||
const definitions = await knex('object_definitions')
|
||||
.whereIn('apiName', Array.from(typeSet))
|
||||
.select('apiName', 'label', 'pluralLabel', 'tableName', 'fields');
|
||||
const definitionByType = new Map<string, any>(
|
||||
definitions.map((item: any) => [item.apiName, item]),
|
||||
);
|
||||
|
||||
const displayNameCache = new Map<string, string>();
|
||||
const getDisplayField = (definition: any) => {
|
||||
let fields = [];
|
||||
if (Array.isArray(definition?.fields)) {
|
||||
fields = definition.fields;
|
||||
} else if (typeof definition?.fields === 'string') {
|
||||
try {
|
||||
fields = JSON.parse(definition.fields);
|
||||
} catch {
|
||||
fields = [];
|
||||
}
|
||||
}
|
||||
if (fields.some((field: any) => field?.apiName === 'name')) return 'name';
|
||||
const textField = fields.find((field: any) =>
|
||||
['STRING', 'TEXT', 'EMAIL'].includes(String(field?.type || '').toUpperCase()),
|
||||
);
|
||||
return textField?.apiName || 'id';
|
||||
};
|
||||
|
||||
const resolveTableName = (definition: any) => {
|
||||
if (definition?.tableName) return definition.tableName;
|
||||
if (definition?.pluralLabel) {
|
||||
return String(definition.pluralLabel).toLowerCase().replace(/[^a-z0-9]+/g, '_');
|
||||
}
|
||||
return `${String(definition?.apiName || '').toLowerCase()}s`;
|
||||
};
|
||||
|
||||
const loadDisplayName = async (type: string, id: string) => {
|
||||
const cacheKey = `${type}:${id}`;
|
||||
if (displayNameCache.has(cacheKey)) return displayNameCache.get(cacheKey);
|
||||
const definition = definitionByType.get(type);
|
||||
if (!definition) {
|
||||
displayNameCache.set(cacheKey, id);
|
||||
return id;
|
||||
}
|
||||
const tableName = resolveTableName(definition);
|
||||
const displayField = getDisplayField(definition);
|
||||
const record = await knex(tableName).where({ id }).first();
|
||||
const display = record?.[displayField] ? String(record[displayField]) : id;
|
||||
displayNameCache.set(cacheKey, display);
|
||||
return display;
|
||||
};
|
||||
|
||||
for (const link of links) {
|
||||
link.source_entity_label = definitionByType.get(link.source_entity_type)?.label || link.source_entity_type;
|
||||
link.target_entity_label = definitionByType.get(link.target_entity_type)?.label || link.target_entity_type;
|
||||
link.source_entity_name = await loadDisplayName(link.source_entity_type, link.source_entity_id);
|
||||
link.target_entity_name = await loadDisplayName(link.target_entity_type, link.target_entity_id);
|
||||
}
|
||||
|
||||
return links;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
540
backend/src/knowledge/services/semantic-orchestrator.service.ts
Normal file
540
backend/src/knowledge/services/semantic-orchestrator.service.ts
Normal file
@@ -0,0 +1,540 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { HumanMessage, SystemMessage } from '@langchain/core/messages';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
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;
|
||||
private readonly defaultChatModel = process.env.OPENAI_CHAT_MODEL || 'gpt-4o-mini';
|
||||
|
||||
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; rankingDetails?: any }>();
|
||||
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,
|
||||
rankingDetails: hit._rankingScoreDetails || null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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, rankingDetails }] of candidates.entries()) {
|
||||
const [targetType, targetId] = key.split(':');
|
||||
const llmAssessment = await this.assessLinkWithLlm(
|
||||
openAiConfig,
|
||||
trigger,
|
||||
projection,
|
||||
chunks,
|
||||
hit,
|
||||
confidence,
|
||||
rankingDetails,
|
||||
);
|
||||
const reason =
|
||||
llmAssessment?.reason ||
|
||||
this.humanizeTrigger(trigger) ||
|
||||
'Suggested from semantic similarity.';
|
||||
await this.semanticLinkService.upsertSuggestedLink(knex, {
|
||||
sourceEntityType: projection.entityType,
|
||||
sourceEntityId: projection.entityId,
|
||||
targetEntityType: targetType,
|
||||
targetEntityId: targetId,
|
||||
linkType: llmAssessment?.linkType || 'related',
|
||||
status: 'suggested',
|
||||
origin: 'semantic',
|
||||
confidence,
|
||||
reason,
|
||||
evidence: this.buildEvidencePayload(
|
||||
trigger,
|
||||
chunks,
|
||||
hit,
|
||||
confidence,
|
||||
rankingDetails,
|
||||
llmAssessment,
|
||||
),
|
||||
suggestedByUserId: userId || null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private buildEvidencePayload(
|
||||
trigger: string,
|
||||
chunks: any[],
|
||||
hit: any,
|
||||
confidence: number,
|
||||
rankingDetails: any,
|
||||
llmAssessment?: {
|
||||
reason?: string;
|
||||
explanation?: string;
|
||||
matchedSignals?: string[];
|
||||
} | null,
|
||||
) {
|
||||
return {
|
||||
trigger,
|
||||
explanation:
|
||||
llmAssessment?.explanation ||
|
||||
llmAssessment?.reason ||
|
||||
'Suggested using semantic similarity and ranked chunk evidence.',
|
||||
sourceSignals: chunks.slice(0, 2).map((chunk) => ({
|
||||
sourceKind: chunk.sourceKind,
|
||||
text: chunk.text.slice(0, 220),
|
||||
})),
|
||||
matchedSignals: llmAssessment?.matchedSignals || [],
|
||||
matchedChunks: [
|
||||
{
|
||||
sourceKind: hit.sourceKind,
|
||||
text: String(hit.text || '').slice(0, 220),
|
||||
score: confidence,
|
||||
rankingDetails: rankingDetails || null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
private async assessLinkWithLlm(
|
||||
openAiConfig: OpenAIConfig | null,
|
||||
trigger: string,
|
||||
projection: any,
|
||||
chunks: any[],
|
||||
hit: any,
|
||||
confidence: number,
|
||||
rankingDetails: any,
|
||||
): Promise<{ linkType: string; reason?: string; explanation?: string; matchedSignals?: string[] } | null> {
|
||||
if (!openAiConfig?.apiKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const promptPayload = {
|
||||
trigger,
|
||||
source: {
|
||||
entityType: projection.entityType,
|
||||
title: projection.title,
|
||||
narrative: String(projection.narrative || '').slice(0, 900),
|
||||
keySignals: chunks.slice(0, 3).map((chunk) => ({
|
||||
sourceKind: chunk.sourceKind,
|
||||
text: String(chunk.text || '').slice(0, 220),
|
||||
})),
|
||||
},
|
||||
target: {
|
||||
entityType: hit.entityType,
|
||||
title: hit.title,
|
||||
sourceKind: hit.sourceKind,
|
||||
text: String(hit.text || '').slice(0, 300),
|
||||
},
|
||||
confidence,
|
||||
rankingDetails: rankingDetails || {},
|
||||
allowedLinkTypes: [
|
||||
'related',
|
||||
'supports',
|
||||
'contradicts',
|
||||
'expands',
|
||||
'duplicate_of',
|
||||
'references',
|
||||
'depends_on',
|
||||
],
|
||||
};
|
||||
|
||||
try {
|
||||
const model = new ChatOpenAI({
|
||||
apiKey: openAiConfig.apiKey,
|
||||
model: openAiConfig.model || this.defaultChatModel,
|
||||
temperature: 0.1,
|
||||
});
|
||||
|
||||
const response = await model.invoke([
|
||||
new SystemMessage(
|
||||
'Classify semantic relationship. Return valid JSON only with keys: linkType, reason, explanation, matchedSignals. linkType must be one of related|supports|contradicts|expands|duplicate_of|references|depends_on.',
|
||||
),
|
||||
new HumanMessage(JSON.stringify(promptPayload)),
|
||||
]);
|
||||
|
||||
const content = typeof response.content === 'string'
|
||||
? response.content
|
||||
: Array.isArray(response.content)
|
||||
? response.content.map((part: any) => (typeof part === 'string' ? part : part?.text || '')).join('')
|
||||
: '';
|
||||
const normalized = this.extractJsonObject(content);
|
||||
if (!normalized) return null;
|
||||
|
||||
const linkType = this.normalizeLinkType(normalized.linkType);
|
||||
return {
|
||||
linkType,
|
||||
reason: typeof normalized.reason === 'string' ? normalized.reason.trim() : undefined,
|
||||
explanation:
|
||||
typeof normalized.explanation === 'string' ? normalized.explanation.trim() : undefined,
|
||||
matchedSignals: Array.isArray(normalized.matchedSignals)
|
||||
? normalized.matchedSignals
|
||||
.map((item: any) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 3)
|
||||
: undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.warn(`Semantic LLM assessment failed: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private extractJsonObject(raw: string): Record<string, any> | null {
|
||||
if (!raw) return null;
|
||||
const trimmed = raw.trim();
|
||||
try {
|
||||
return JSON.parse(trimmed);
|
||||
} catch {
|
||||
const match = trimmed.match(/\{[\s\S]*\}/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return JSON.parse(match[0]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeLinkType(value: any): string {
|
||||
const supported = new Set([
|
||||
'related',
|
||||
'supports',
|
||||
'contradicts',
|
||||
'expands',
|
||||
'duplicate_of',
|
||||
'references',
|
||||
'depends_on',
|
||||
]);
|
||||
const normalized = String(value || '').trim().toLowerCase();
|
||||
if (supported.has(normalized)) return normalized;
|
||||
return 'related';
|
||||
}
|
||||
|
||||
private humanizeTrigger(trigger: string): string {
|
||||
if (!trigger) return 'Suggested from semantic similarity.';
|
||||
const map: Record<string, string> = {
|
||||
comment_created: 'Suggested based on a comment added to the record.',
|
||||
comment_updated: 'Suggested based on a comment update.',
|
||||
manual_refresh: 'Suggested after a manual semantic refresh.',
|
||||
batch_reindex: 'Suggested during semantic reindexing.',
|
||||
};
|
||||
return map[trigger] || 'Suggested from semantic similarity.';
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BaseModel } from './base.model';
|
||||
import { ModelOptions, QueryContext } from 'objection';
|
||||
|
||||
export class User extends BaseModel {
|
||||
static tableName = 'users';
|
||||
@@ -8,6 +9,8 @@ export class User extends BaseModel {
|
||||
password: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
alias?: string;
|
||||
name?: string;
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
@@ -22,11 +25,37 @@ export class User extends BaseModel {
|
||||
password: { type: 'string' },
|
||||
firstName: { type: 'string' },
|
||||
lastName: { type: 'string' },
|
||||
alias: { type: 'string' },
|
||||
name: { type: 'string' },
|
||||
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() {
|
||||
const { UserRole } = require('./user-role.model');
|
||||
const { Role } = require('./role.model');
|
||||
|
||||
@@ -152,6 +152,7 @@ export class FieldMapperService {
|
||||
'phone': 'text',
|
||||
'picklist': 'select',
|
||||
'multipicklist': 'multiSelect',
|
||||
'multi_picklist': 'multiSelect',
|
||||
'lookup': 'belongsTo',
|
||||
'master-detail': 'belongsTo',
|
||||
'currency': 'currency',
|
||||
|
||||
@@ -10,9 +10,10 @@ import { RbacModule } from '../rbac/rbac.module';
|
||||
import { ModelRegistry } from './models/model.registry';
|
||||
import { ModelService } from './models/model.service';
|
||||
import { MeilisearchModule } from '../search/meilisearch.module';
|
||||
import { KnowledgeModule } from '../knowledge/knowledge.module';
|
||||
|
||||
@Module({
|
||||
imports: [TenantModule, MigrationModule, RbacModule, MeilisearchModule],
|
||||
imports: [TenantModule, MigrationModule, RbacModule, MeilisearchModule, KnowledgeModule],
|
||||
providers: [
|
||||
ObjectService,
|
||||
SchemaManagementService,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { FieldDefinition } from '../models/field-definition.model';
|
||||
import { User } from '../models/user.model';
|
||||
import { ObjectMetadata } from './models/dynamic-model.factory';
|
||||
import { MeilisearchService } from '../search/meilisearch.service';
|
||||
import { SemanticRefreshQueueService } from '../knowledge/services/semantic-refresh-queue.service';
|
||||
|
||||
type SearchFilter = {
|
||||
field: string;
|
||||
@@ -39,6 +40,7 @@ export class ObjectService {
|
||||
private modelService: ModelService,
|
||||
private authService: AuthorizationService,
|
||||
private meilisearchService: MeilisearchService,
|
||||
private semanticRefreshQueue: SemanticRefreshQueueService,
|
||||
) {}
|
||||
|
||||
// Setup endpoints - Object metadata management
|
||||
@@ -336,13 +338,27 @@ export class ObjectService {
|
||||
updated_at: knex.fn.now(),
|
||||
};
|
||||
|
||||
// Store relationDisplayField in UI metadata if provided
|
||||
if (data.relationDisplayField || data.relationObjects || data.relationTypeField) {
|
||||
fieldData.ui_metadata = JSON.stringify({
|
||||
relationDisplayField: data.relationDisplayField,
|
||||
relationObjects: data.relationObjects,
|
||||
relationTypeField: data.relationTypeField,
|
||||
});
|
||||
// Build UI metadata from all sources
|
||||
const uiMetadataObj: any = {};
|
||||
|
||||
// Merge general uiMetadata (options, placeholder, helpText, etc.)
|
||||
if (data.uiMetadata && typeof data.uiMetadata === 'object') {
|
||||
Object.assign(uiMetadataObj, data.uiMetadata);
|
||||
}
|
||||
|
||||
// Store relation-specific fields in UI metadata if provided
|
||||
if (data.relationDisplayField) {
|
||||
uiMetadataObj.relationDisplayField = data.relationDisplayField;
|
||||
}
|
||||
if (data.relationObjects) {
|
||||
uiMetadataObj.relationObjects = data.relationObjects;
|
||||
}
|
||||
if (data.relationTypeField) {
|
||||
uiMetadataObj.relationTypeField = data.relationTypeField;
|
||||
}
|
||||
|
||||
if (Object.keys(uiMetadataObj).length > 0) {
|
||||
fieldData.ui_metadata = JSON.stringify(uiMetadataObj);
|
||||
}
|
||||
|
||||
await knex('field_definitions').insert(fieldData);
|
||||
@@ -1114,6 +1130,13 @@ export class ObjectService {
|
||||
);
|
||||
const record = await boundModel.query().insert(normalizedRecordData);
|
||||
await this.indexRecord(resolvedTenantId, objectApiName, objectDefModel.fields, record);
|
||||
await this.semanticRefreshQueue.enqueue(
|
||||
resolvedTenantId,
|
||||
objectApiName,
|
||||
record.id,
|
||||
userId,
|
||||
'record_created',
|
||||
);
|
||||
return record;
|
||||
}
|
||||
|
||||
@@ -1183,6 +1206,13 @@ export class ObjectService {
|
||||
await boundModel.query().patch(normalizedEditableData).where({ id: recordId });
|
||||
const record = await boundModel.query().where({ id: recordId }).first();
|
||||
await this.indexRecord(resolvedTenantId, objectApiName, objectDefModel.fields, record);
|
||||
await this.semanticRefreshQueue.enqueue(
|
||||
resolvedTenantId,
|
||||
objectApiName,
|
||||
recordId,
|
||||
userId,
|
||||
'record_updated',
|
||||
);
|
||||
return record;
|
||||
}
|
||||
|
||||
|
||||
@@ -111,4 +111,33 @@ export class RuntimeObjectController {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export class SetupUsersController {
|
||||
@Post()
|
||||
async createUser(
|
||||
@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 knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
||||
@@ -52,6 +52,7 @@ export class SetupUsersController {
|
||||
password: hashedPassword,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
alias: data.alias,
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
@@ -62,7 +63,7 @@ export class SetupUsersController {
|
||||
async updateUser(
|
||||
@TenantId() tenantId: 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 knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
||||
@@ -72,6 +73,7 @@ export class SetupUsersController {
|
||||
if (data.email) updateData.email = data.email;
|
||||
if (data.firstName !== undefined) updateData.firstName = data.firstName;
|
||||
if (data.lastName !== undefined) updateData.lastName = data.lastName;
|
||||
if (data.alias !== undefined) updateData.alias = data.alias;
|
||||
|
||||
// Hash password if provided
|
||||
if (data.password) {
|
||||
|
||||
53
backend/src/saved-list-view/dto/saved-list-view.dto.ts
Normal file
53
backend/src/saved-list-view/dto/saved-list-view.dto.ts
Normal 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;
|
||||
}
|
||||
92
backend/src/saved-list-view/saved-list-view.controller.ts
Normal file
92
backend/src/saved-list-view/saved-list-view.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
12
backend/src/saved-list-view/saved-list-view.module.ts
Normal file
12
backend/src/saved-list-view/saved-list-view.module.ts
Normal 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 {}
|
||||
264
backend/src/saved-list-view/saved-list-view.service.ts
Normal file
264
backend/src/saved-list-view/saved-list-view.service.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,23 @@ type MeiliConfig = {
|
||||
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());
|
||||
@@ -158,6 +172,100 @@ export class MeilisearchService {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -198,7 +306,7 @@ export class MeilisearchService {
|
||||
}
|
||||
|
||||
private requestJson(
|
||||
method: 'POST' | 'DELETE',
|
||||
method: 'POST' | 'DELETE' | 'PATCH' | 'GET',
|
||||
url: string,
|
||||
payload: any,
|
||||
headers: Record<string, string>,
|
||||
@@ -235,10 +343,141 @@ export class MeilisearchService {
|
||||
);
|
||||
|
||||
request.on('error', reject);
|
||||
if (payload !== undefined) {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface OpenAIConfig {
|
||||
apiKey: string;
|
||||
assistantId?: string;
|
||||
model?: string;
|
||||
embeddingModel?: string;
|
||||
voice?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -186,6 +186,8 @@ interface Props {
|
||||
objectApiName: string;
|
||||
recordId: string;
|
||||
ownerId?: string;
|
||||
/** Optional base URL override for shares API. Defaults to /runtime/objects/{objectApiName}/records/{recordId}/shares */
|
||||
basePath?: string;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
@@ -193,6 +195,11 @@ const props = defineProps<Props>();
|
||||
const { api } = useApi();
|
||||
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 sharing = ref(false);
|
||||
const removing = ref<string | null>(null);
|
||||
@@ -236,9 +243,7 @@ const loadShares = async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
const response = await api.get(
|
||||
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`
|
||||
);
|
||||
const response = await api.get(sharesBasePath.value);
|
||||
shares.value = response || [];
|
||||
} catch (e: any) {
|
||||
console.error('Failed to load shares:', e);
|
||||
@@ -286,7 +291,7 @@ const createShare = async () => {
|
||||
console.log('Final payload:', payload);
|
||||
|
||||
await api.post(
|
||||
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`,
|
||||
sharesBasePath.value,
|
||||
payload
|
||||
);
|
||||
toast.success('Record shared successfully');
|
||||
@@ -313,7 +318,7 @@ const removeShare = async (shareId: string) => {
|
||||
try {
|
||||
removing.value = shareId;
|
||||
await api.delete(
|
||||
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares/${shareId}`
|
||||
`${sharesBasePath.value}/${shareId}`
|
||||
);
|
||||
toast.success('Share removed successfully');
|
||||
await loadShares();
|
||||
|
||||
234
frontend/components/SavedViewPanel.vue
Normal file
234
frontend/components/SavedViewPanel.vue
Normal 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>
|
||||
@@ -249,6 +249,51 @@ const handleRelationTypeUpdate = (value: string | null) => {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<!-- Multi-Select -->
|
||||
<div v-else-if="field.type === FieldType.MULTI_SELECT" class="space-y-2">
|
||||
<div class="flex flex-wrap gap-1 min-h-[36px] rounded-md border border-input bg-background px-3 py-2">
|
||||
<Badge
|
||||
v-for="selectedVal in (Array.isArray(value) ? value : [])"
|
||||
:key="String(selectedVal)"
|
||||
variant="secondary"
|
||||
class="gap-1 cursor-pointer"
|
||||
@click="value = (value || []).filter((v: any) => v !== selectedVal)"
|
||||
>
|
||||
{{ field.options?.find(o => o.value === selectedVal)?.label || selectedVal }}
|
||||
<span class="text-xs ml-1">×</span>
|
||||
</Badge>
|
||||
<span v-if="!value || (Array.isArray(value) && value.length === 0)" class="text-sm text-muted-foreground">
|
||||
{{ field.placeholder || 'Select options...' }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="space-y-1">
|
||||
<div
|
||||
v-for="option in field.options"
|
||||
:key="String(option.value)"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<Checkbox
|
||||
:id="`${field.id}-${option.value}`"
|
||||
:checked="Array.isArray(value) && value.includes(option.value)"
|
||||
@update:checked="(checked: boolean) => {
|
||||
const current = Array.isArray(value) ? [...value] : []
|
||||
if (checked) {
|
||||
current.push(option.value)
|
||||
} else {
|
||||
const idx = current.indexOf(option.value)
|
||||
if (idx > -1) current.splice(idx, 1)
|
||||
}
|
||||
value = current
|
||||
}"
|
||||
:disabled="field.isReadOnly"
|
||||
/>
|
||||
<Label :for="`${field.id}-${option.value}`" class="text-sm font-normal cursor-pointer">
|
||||
{{ option.label }}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Boolean - Checkbox -->
|
||||
<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" />
|
||||
|
||||
181
frontend/components/knowledge/RecordCommentsPanel.vue
Normal file
181
frontend/components/knowledge/RecordCommentsPanel.vue
Normal 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>
|
||||
237
frontend/components/knowledge/SemanticLinksPanel.vue
Normal file
237
frontend/components/knowledge/SemanticLinksPanel.vue
Normal file
@@ -0,0 +1,237 @@
|
||||
<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
|
||||
source_entity_label?: string
|
||||
target_entity_label?: string
|
||||
source_entity_name?: string
|
||||
target_entity_name?: 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,
|
||||
entityLabel: isSource ? link.target_entity_label : link.source_entity_label,
|
||||
entityName: isSource ? link.target_entity_name : link.source_entity_name,
|
||||
}
|
||||
}
|
||||
|
||||
const formatLinkType = (value?: string) => {
|
||||
if (!value) return 'Related'
|
||||
return value
|
||||
.replace(/_/g, ' ')
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
}
|
||||
|
||||
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).entityLabel || getOtherSide(link).entityType }} ·
|
||||
{{ getOtherSide(link).entityName || getOtherSide(link).entityId }}
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground">
|
||||
{{ formatLinkType(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>
|
||||
<p v-if="parseEvidence(link.evidence)?.explanation" class="mt-1 text-foreground">
|
||||
{{ parseEvidence(link.evidence).explanation }}
|
||||
</p>
|
||||
<div v-if="parseEvidence(link.evidence)?.matchedSignals?.length" class="mt-2">
|
||||
<div>Matched context:</div>
|
||||
<ul class="list-disc pl-4">
|
||||
<li
|
||||
v-for="(signal, idx) in parseEvidence(link.evidence).matchedSignals"
|
||||
:key="idx"
|
||||
>
|
||||
{{ signal }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div v-if="parseEvidence(link.evidence)?.matchedChunks?.length" class="mt-2">
|
||||
<div>Matched excerpts:</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>
|
||||
@@ -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>
|
||||
@@ -2,3 +2,4 @@ export { default as DropdownMenu } from './DropdownMenu.vue'
|
||||
export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue'
|
||||
export { default as DropdownMenuContent } from './DropdownMenuContent.vue'
|
||||
export { default as DropdownMenuItem } from './DropdownMenuItem.vue'
|
||||
export { default as DropdownMenuSeparator } from './DropdownMenuSeparator.vue'
|
||||
|
||||
@@ -5,6 +5,8 @@ import { Button } from '@/components/ui/button'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import FieldRenderer from '@/components/fields/FieldRenderer.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 { Edit, Trash2, ArrowLeft } from 'lucide-vue-next'
|
||||
import {
|
||||
@@ -167,6 +169,18 @@ const getFieldsBySection = (section: FieldSection) => {
|
||||
@create="(objectApiName, parentId) => emit('createRelated', objectApiName, parentId)"
|
||||
/>
|
||||
</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>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import FieldRenderer from '@/components/fields/FieldRenderer.vue'
|
||||
import PageLayoutRenderer from '@/components/PageLayoutRenderer.vue'
|
||||
import RelatedList from '@/components/RelatedList.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 { Edit, Trash2, ArrowLeft } from 'lucide-vue-next'
|
||||
import {
|
||||
@@ -170,6 +172,9 @@ const visibleRelatedLists = computed<RelatedListConfig[]>(() => {
|
||||
<TabsTrigger v-if="showSharing && data.id" value="sharing">
|
||||
Sharing
|
||||
</TabsTrigger>
|
||||
<TabsTrigger v-if="data.id && config.objectApiName" value="knowledge">
|
||||
Knowledge
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<!-- Details Tab -->
|
||||
@@ -277,6 +282,20 @@ const visibleRelatedLists = computed<RelatedListConfig[]>(() => {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</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>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
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 {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -13,9 +17,17 @@ import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
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 { ListViewConfig, ViewMode, FieldType } from '@/types/field-types'
|
||||
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit } from 'lucide-vue-next'
|
||||
import { ListViewConfig, ViewMode, FieldType, FieldConfig } from '@/types/field-types'
|
||||
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit, Bookmark, BookmarkPlus, Settings2 } from 'lucide-vue-next'
|
||||
import type { SavedView } from '@/composables/useSavedViews'
|
||||
|
||||
interface Props {
|
||||
config: ListViewConfig
|
||||
@@ -25,6 +37,14 @@ interface Props {
|
||||
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>(), {
|
||||
@@ -33,6 +53,13 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
selectable: false,
|
||||
baseUrl: '/runtime/objects',
|
||||
searchSummary: '',
|
||||
draftEdits: () => ({}),
|
||||
cellErrors: () => ({}),
|
||||
savingDrafts: false,
|
||||
savedViews: () => [],
|
||||
activeViewId: null,
|
||||
currentSearchPlan: null,
|
||||
savingView: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -47,6 +74,14 @@ const emit = defineEmits<{
|
||||
'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
|
||||
@@ -57,6 +92,8 @@ const sortField = ref<string>('')
|
||||
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
|
||||
const visibleFields = computed(() =>
|
||||
@@ -87,7 +124,7 @@ const paginatedData = computed(() => {
|
||||
})
|
||||
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(() => totalRecords.value > pageSize.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(() => (
|
||||
@@ -95,6 +132,8 @@ const showLoadMore = computed(() => (
|
||||
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({
|
||||
get: () => props.data.length > 0 && selectedRowIds.value.length === props.data.length,
|
||||
@@ -159,6 +198,154 @@ const handleBulkAction = () => {
|
||||
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) {
|
||||
@@ -193,6 +380,23 @@ watch(
|
||||
},
|
||||
{ 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>
|
||||
|
||||
<template>
|
||||
@@ -216,6 +420,95 @@ watch(
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<!-- Saved Views dropdown + cog -->
|
||||
<div class="flex items-center gap-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger as-child>
|
||||
<Button variant="outline" size="sm" class="gap-2">
|
||||
<Bookmark class="h-4 w-4" />
|
||||
<span class="max-w-[120px] truncate">
|
||||
{{ savedViews.find(v => v.id === activeViewId)?.name || 'Views' }}
|
||||
</span>
|
||||
<ChevronDown class="h-3 w-3 opacity-60" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" class="w-56">
|
||||
<DropdownMenuItem
|
||||
v-if="savedViews.length === 0"
|
||||
disabled
|
||||
class="text-muted-foreground"
|
||||
>
|
||||
No saved views yet
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
v-for="view in savedViews"
|
||||
:key="view.id"
|
||||
:class="{ 'font-medium': view.id === activeViewId }"
|
||||
@click="emit('apply-view', view)"
|
||||
>
|
||||
<span class="flex-1 truncate">{{ view.name }}</span>
|
||||
<Badge v-if="view.isShared" variant="secondary" class="ml-2 text-[10px] px-1.5 py-0">Shared</Badge>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator v-if="savedViews.length > 0" />
|
||||
<DropdownMenuItem @click="emit('open-view-manager')">
|
||||
Manage views…
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-8 w-8"
|
||||
title="Manage saved views"
|
||||
@click="emit('open-view-manager')"
|
||||
>
|
||||
<Settings2 class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- Save current search as a view (only for query strategy) -->
|
||||
<Button
|
||||
v-if="currentSearchPlan?.strategy === 'query'"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="savingView"
|
||||
class="gap-2"
|
||||
@click="emit('save-view')"
|
||||
>
|
||||
<BookmarkPlus class="h-4 w-4" />
|
||||
Save view
|
||||
</Button>
|
||||
|
||||
<Select v-model="viewMode">
|
||||
<SelectTrigger class="h-8 w-[180px]">
|
||||
<SelectValue placeholder="Select view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="list">List view</SelectItem>
|
||||
<SelectItem value="spreadsheet">Spreadsheet view</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<template v-if="viewMode === 'spreadsheet'">
|
||||
<Badge v-if="draftRowCount > 0" variant="secondary" class="px-3 py-1">
|
||||
{{ draftCellCount }} change{{ draftCellCount === 1 ? '' : 's' }}
|
||||
</Badge>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="draftRowCount === 0 || savingDrafts"
|
||||
@click="emit('discard-drafts')"
|
||||
>
|
||||
Discard changes
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="draftRowCount === 0 || savingDrafts"
|
||||
@click="emit('save-drafts')"
|
||||
>
|
||||
Save changes ({{ draftRowCount }})
|
||||
</Button>
|
||||
</template>
|
||||
<!-- Bulk Actions -->
|
||||
<template v-if="selectedRowIds.length > 0">
|
||||
<Badge variant="secondary" class="px-3 py-1">
|
||||
@@ -264,7 +557,7 @@ watch(
|
||||
|
||||
<!-- Table -->
|
||||
<div class="border rounded-lg">
|
||||
<Table>
|
||||
<Table v-if="viewMode === 'list'">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead v-if="selectable" class="w-12">
|
||||
@@ -338,6 +631,19 @@ watch(
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</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 v-if="showPagination" class="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
|
||||
@@ -375,4 +681,5 @@ watch(
|
||||
.list-view :deep(input) {
|
||||
background-color: hsl(var(--background));
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
107
frontend/composables/useSavedViews.ts
Normal file
107
frontend/composables/useSavedViews.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
export interface SavedViewFilter {
|
||||
field: string
|
||||
operator: string
|
||||
value?: any
|
||||
values?: any[]
|
||||
from?: string
|
||||
to?: string
|
||||
}
|
||||
|
||||
export interface SavedViewSort {
|
||||
field: string
|
||||
direction: 'asc' | 'desc'
|
||||
}
|
||||
|
||||
export interface SavedView {
|
||||
id: string
|
||||
name: string
|
||||
objectApiName: string
|
||||
userId: string
|
||||
isOwner: boolean
|
||||
isShared: boolean
|
||||
strategy: 'query'
|
||||
filters: SavedViewFilter[]
|
||||
sort: SavedViewSort | null
|
||||
description: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface CreateSavedViewPayload {
|
||||
name: string
|
||||
objectApiName: string
|
||||
filters: SavedViewFilter[]
|
||||
sort?: SavedViewSort | null
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface UpdateSavedViewPayload {
|
||||
name?: string
|
||||
filters?: SavedViewFilter[]
|
||||
sort?: SavedViewSort | null
|
||||
description?: string
|
||||
}
|
||||
|
||||
export function useSavedViews() {
|
||||
const { api } = useApi()
|
||||
|
||||
const savedViews = ref<SavedView[]>([])
|
||||
const loading = ref(false)
|
||||
|
||||
async function fetchSavedViews(objectApiName: string) {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await api.get(`/saved-views/${objectApiName}`)
|
||||
savedViews.value = Array.isArray(data) ? data : []
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch saved views', e)
|
||||
savedViews.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function createSavedView(payload: CreateSavedViewPayload): Promise<SavedView> {
|
||||
const created = await api.post('/saved-views', payload)
|
||||
savedViews.value = [...savedViews.value, created]
|
||||
return created
|
||||
}
|
||||
|
||||
async function updateSavedView(id: string, payload: UpdateSavedViewPayload): Promise<SavedView> {
|
||||
const updated = await api.patch(`/saved-views/${id}`, payload)
|
||||
savedViews.value = savedViews.value.map(v => (v.id === id ? updated : v))
|
||||
return updated
|
||||
}
|
||||
|
||||
async function deleteSavedView(id: string) {
|
||||
await api.delete(`/saved-views/${id}`)
|
||||
savedViews.value = savedViews.value.filter(v => v.id !== id)
|
||||
}
|
||||
|
||||
async function suggestViewName(
|
||||
objectLabel: string,
|
||||
filters: SavedViewFilter[],
|
||||
explanation?: string,
|
||||
): Promise<string> {
|
||||
try {
|
||||
const result = await api.post('/ai/suggest-view-name', {
|
||||
objectLabel,
|
||||
filters,
|
||||
explanation,
|
||||
})
|
||||
return result?.suggestedName || `${objectLabel} View`
|
||||
} catch {
|
||||
return `${objectLabel} View`
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
savedViews,
|
||||
loading,
|
||||
fetchSavedViews,
|
||||
createSavedView,
|
||||
updateSavedView,
|
||||
deleteSavedView,
|
||||
suggestViewName,
|
||||
}
|
||||
}
|
||||
27
frontend/package-lock.json
generated
27
frontend/package-lock.json
generated
@@ -13,6 +13,8 @@
|
||||
"@nuxtjs/tailwindcss": "^6.11.4",
|
||||
"@twilio/voice-sdk": "^2.11.2",
|
||||
"@vueuse/core": "^10.11.1",
|
||||
"ag-grid-community": "^32.3.4",
|
||||
"ag-grid-vue3": "^32.3.4",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"gridstack": "^12.4.1",
|
||||
@@ -4976,6 +4978,31 @@
|
||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ag-charts-types": {
|
||||
"version": "10.3.9",
|
||||
"resolved": "https://registry.npmjs.org/ag-charts-types/-/ag-charts-types-10.3.9.tgz",
|
||||
"integrity": "sha512-drcRiJVencliC8LnRwk4MmeQDNNBg5GzmOoLFihO3/k0CUK0VF/N+2nc7iFozwaNG0btSB9vAhYuJLjqHMtRrQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ag-grid-community": {
|
||||
"version": "32.3.9",
|
||||
"resolved": "https://registry.npmjs.org/ag-grid-community/-/ag-grid-community-32.3.9.tgz",
|
||||
"integrity": "sha512-l07SB0mCbGPkC1R8rQQFgBtI5+1FoXBi3RUk1+dHKV/UPeorMEFAzCokcsOhz0qwcWCPrHauUsbRa1SIxfVEJQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ag-charts-types": "10.3.9"
|
||||
}
|
||||
},
|
||||
"node_modules/ag-grid-vue3": {
|
||||
"version": "32.3.9",
|
||||
"resolved": "https://registry.npmjs.org/ag-grid-vue3/-/ag-grid-vue3-32.3.9.tgz",
|
||||
"integrity": "sha512-86Xynbfg8bq/tGW0Yfl2O8HSUgT7nDtNzioMs4r8hNfPiqOfKUUWrTveP5S4Acs8Astr495ZdKKFDIcQVLx3Yg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ag-grid-community": "32.3.9",
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
"@nuxtjs/tailwindcss": "^6.11.4",
|
||||
"@twilio/voice-sdk": "^2.11.2",
|
||||
"@vueuse/core": "^10.11.1",
|
||||
"ag-grid-community": "^32.3.4",
|
||||
"ag-grid-vue3": "^32.3.4",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"gridstack": "^12.4.1",
|
||||
|
||||
@@ -4,9 +4,12 @@ import { useRoute, useRouter } from 'vue-router'
|
||||
import { useApi } from '@/composables/useApi'
|
||||
import { useFields, useViewState } from '@/composables/useFieldViews'
|
||||
import { usePageLayouts } from '@/composables/usePageLayouts'
|
||||
import { useSavedViews } from '@/composables/useSavedViews'
|
||||
import type { SavedView } from '@/composables/useSavedViews'
|
||||
import ListView from '@/components/views/ListView.vue'
|
||||
import DetailView from '@/components/views/DetailViewEnhanced.vue'
|
||||
import EditView from '@/components/views/EditViewEnhanced.vue'
|
||||
import SavedViewPanel from '@/components/SavedViewPanel.vue'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -15,12 +18,23 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { api } = useApi()
|
||||
const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields()
|
||||
const { getDefaultPageLayout } = usePageLayouts()
|
||||
const {
|
||||
savedViews,
|
||||
fetchSavedViews,
|
||||
createSavedView,
|
||||
updateSavedView,
|
||||
deleteSavedView,
|
||||
suggestViewName,
|
||||
} = useSavedViews()
|
||||
|
||||
// Use breadcrumbs composable
|
||||
const { setBreadcrumbs } = useBreadcrumbs()
|
||||
@@ -57,6 +71,7 @@ const {
|
||||
fetchRecord,
|
||||
deleteRecord,
|
||||
deleteRecords,
|
||||
updateRecord,
|
||||
handleSave,
|
||||
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
|
||||
|
||||
@@ -165,11 +180,27 @@ const deleteDialogOpen = ref(false)
|
||||
const deleteSubmitting = ref(false)
|
||||
const pendingDeleteRows = ref<any[]>([])
|
||||
const deleteSummary = ref<{ deletedIds: string[]; deniedIds: string[] } | null>(null)
|
||||
const normalizeRecordId = (id: any) => String(id)
|
||||
|
||||
const draftEdits = ref<Record<string, Record<string, any>>>({})
|
||||
const draftOriginals = ref<Record<string, Record<string, any>>>({})
|
||||
const cellErrors = ref<Record<string, Record<string, string>>>({})
|
||||
const savingDrafts = ref(false)
|
||||
|
||||
const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
|
||||
const pendingDeleteCount = computed(() => pendingDeleteRows.value.length)
|
||||
const deniedDeleteCount = computed(() => deleteSummary.value?.deniedIds.length ?? 0)
|
||||
|
||||
// ── Saved views state ──────────────────────────────────────────────────────
|
||||
const activeViewId = ref<string | null>(null)
|
||||
const currentSearchPlan = ref<{
|
||||
strategy: string; filters: any[]; sort: any; explanation: string
|
||||
} | null>(null)
|
||||
const viewPanelOpen = ref(false)
|
||||
const saveViewDialogOpen = ref(false)
|
||||
const saveViewName = ref('')
|
||||
const savingView = ref(false)
|
||||
|
||||
// Fetch object definition
|
||||
const fetchObjectDefinition = async () => {
|
||||
try {
|
||||
@@ -316,6 +347,19 @@ const searchListRecords = async (
|
||||
records.value = options?.append ? [...records.value, ...data] : data
|
||||
totalCount.value = total
|
||||
searchSummary.value = response?.explanation || ''
|
||||
|
||||
// Capture the plan for the "Save view" feature (only when strategy is query)
|
||||
if (response?.strategy === 'query') {
|
||||
currentSearchPlan.value = {
|
||||
strategy: response.strategy,
|
||||
filters: response.filters || [],
|
||||
sort: response.sort || null,
|
||||
explanation: response.explanation || '',
|
||||
}
|
||||
} else {
|
||||
currentSearchPlan.value = null
|
||||
}
|
||||
|
||||
return response
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to search records'
|
||||
@@ -355,17 +399,266 @@ const handleLoadMore = async (page: number, pageSize: number) => {
|
||||
await loadListRecords(page, { append: true, pageSize })
|
||||
}
|
||||
|
||||
const loadAllListRecords = async () => {
|
||||
if (!records.value.length) {
|
||||
await loadListRecords(1)
|
||||
}
|
||||
const resolvedTotal = totalCount.value ?? records.value.length
|
||||
if (resolvedTotal > records.value.length) {
|
||||
await loadListRecords(1, { append: false, pageSize: resolvedTotal })
|
||||
}
|
||||
}
|
||||
|
||||
const handleViewChange = async (mode: 'list' | 'spreadsheet') => {
|
||||
if (mode === 'spreadsheet' && !isSearchActive.value) {
|
||||
await loadAllListRecords()
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearch = async (query: string) => {
|
||||
const trimmed = query.trim()
|
||||
searchQuery.value = trimmed
|
||||
if (!trimmed) {
|
||||
searchSummary.value = ''
|
||||
currentSearchPlan.value = null
|
||||
activeViewId.value = null
|
||||
await initializeListRecords()
|
||||
return
|
||||
}
|
||||
await searchListRecords(1, { append: false, pageSize: listPageSize.value })
|
||||
}
|
||||
|
||||
const handleCellEdit = async (payload: { row: any; field: any; newValue: any; oldValue: any }) => {
|
||||
if (!payload?.row?.id || payload.newValue === payload.oldValue) return
|
||||
const recordKey = normalizeRecordId(payload.row.id)
|
||||
const fieldName = payload.field.apiName
|
||||
const originalRow = draftOriginals.value[recordKey]
|
||||
const originalValue = originalRow && Object.prototype.hasOwnProperty.call(originalRow, fieldName)
|
||||
? originalRow[fieldName]
|
||||
: payload.oldValue
|
||||
|
||||
if (Object.is(payload.newValue, originalValue)) {
|
||||
const nextDrafts = { ...draftEdits.value }
|
||||
const nextRowDrafts = { ...(nextDrafts[recordKey] || {}) }
|
||||
delete nextRowDrafts[fieldName]
|
||||
if (Object.keys(nextRowDrafts).length === 0) {
|
||||
delete nextDrafts[recordKey]
|
||||
} else {
|
||||
nextDrafts[recordKey] = nextRowDrafts
|
||||
}
|
||||
draftEdits.value = nextDrafts
|
||||
|
||||
const nextOriginals = { ...draftOriginals.value }
|
||||
const nextRowOriginals = { ...(nextOriginals[recordKey] || {}) }
|
||||
delete nextRowOriginals[fieldName]
|
||||
if (Object.keys(nextRowOriginals).length === 0) {
|
||||
delete nextOriginals[recordKey]
|
||||
} else {
|
||||
nextOriginals[recordKey] = nextRowOriginals
|
||||
}
|
||||
draftOriginals.value = nextOriginals
|
||||
} else {
|
||||
draftEdits.value = {
|
||||
...draftEdits.value,
|
||||
[recordKey]: {
|
||||
...(draftEdits.value[recordKey] || {}),
|
||||
[fieldName]: payload.newValue,
|
||||
},
|
||||
}
|
||||
if (!originalRow || !Object.prototype.hasOwnProperty.call(originalRow, fieldName)) {
|
||||
draftOriginals.value = {
|
||||
...draftOriginals.value,
|
||||
[recordKey]: {
|
||||
...(draftOriginals.value[recordKey] || {}),
|
||||
[fieldName]: payload.oldValue,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cellErrors.value[recordKey]?.[fieldName]) {
|
||||
const nextErrors = { ...cellErrors.value }
|
||||
const nextRowErrors = { ...(nextErrors[recordKey] || {}) }
|
||||
delete nextRowErrors[fieldName]
|
||||
if (Object.keys(nextRowErrors).length === 0) {
|
||||
delete nextErrors[recordKey]
|
||||
} else {
|
||||
nextErrors[recordKey] = nextRowErrors
|
||||
}
|
||||
cellErrors.value = nextErrors
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveDrafts = async () => {
|
||||
if (Object.keys(draftEdits.value).length === 0) return
|
||||
savingDrafts.value = true
|
||||
const nextErrors: Record<string, Record<string, string>> = {}
|
||||
const nextDrafts = { ...draftEdits.value }
|
||||
const nextOriginals = { ...draftOriginals.value }
|
||||
|
||||
for (const [recordKey, changes] of Object.entries(draftEdits.value)) {
|
||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
||||
if (!record) {
|
||||
delete nextDrafts[recordKey]
|
||||
delete nextOriginals[recordKey]
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await updateRecord(record.id, changes)
|
||||
delete nextDrafts[recordKey]
|
||||
delete nextOriginals[recordKey]
|
||||
} catch (e: any) {
|
||||
const message = e.message || 'Failed to update record'
|
||||
nextErrors[recordKey] = {}
|
||||
for (const fieldName of Object.keys(changes)) {
|
||||
nextErrors[recordKey][fieldName] = message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
draftEdits.value = nextDrafts
|
||||
draftOriginals.value = nextOriginals
|
||||
cellErrors.value = nextErrors
|
||||
savingDrafts.value = false
|
||||
if (Object.keys(nextErrors).length > 0) {
|
||||
error.value = 'Some updates failed. Fix highlighted cells and try again.'
|
||||
}
|
||||
}
|
||||
|
||||
const handleDiscardDrafts = () => {
|
||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
||||
if (!record) continue
|
||||
for (const [fieldName, originalValue] of Object.entries(fields)) {
|
||||
record[fieldName] = originalValue
|
||||
}
|
||||
}
|
||||
draftEdits.value = {}
|
||||
draftOriginals.value = {}
|
||||
cellErrors.value = {}
|
||||
}
|
||||
|
||||
// ── Saved view handlers ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Apply a saved view: execute its stored filters directly without re-running AI.
|
||||
*/
|
||||
const handleApplyView = async (view: SavedView) => {
|
||||
activeViewId.value = view.id
|
||||
searchQuery.value = ''
|
||||
searchSummary.value = view.description || ''
|
||||
currentSearchPlan.value = {
|
||||
strategy: view.strategy,
|
||||
filters: view.filters,
|
||||
sort: view.sort,
|
||||
explanation: view.description || '',
|
||||
}
|
||||
searchLoading.value = true
|
||||
try {
|
||||
const response = await api.post(
|
||||
`/runtime/objects/${objectApiName.value}/records/search`,
|
||||
{
|
||||
filters: view.filters,
|
||||
sort: view.sort,
|
||||
page: 1,
|
||||
pageSize: listPageSize.value,
|
||||
},
|
||||
)
|
||||
const data = response?.data ?? []
|
||||
records.value = data
|
||||
totalCount.value = response?.totalCount ?? data.length
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to apply saved view'
|
||||
} finally {
|
||||
searchLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the "Save view" dialog, pre-filling the name via AI suggestion.
|
||||
*/
|
||||
const handleSaveView = async () => {
|
||||
if (!currentSearchPlan.value) return
|
||||
saveViewName.value = ''
|
||||
saveViewDialogOpen.value = true
|
||||
// Async-suggest a name while dialog is open
|
||||
const objectLabel = objectDefinition.value?.label || objectApiName.value
|
||||
const suggested = await suggestViewName(
|
||||
objectLabel,
|
||||
currentSearchPlan.value.filters,
|
||||
currentSearchPlan.value.explanation,
|
||||
)
|
||||
// Only auto-fill if user hasn't typed anything yet
|
||||
if (!saveViewName.value) {
|
||||
saveViewName.value = suggested
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm the save: persist the view and close the dialog.
|
||||
*/
|
||||
const confirmSaveView = async () => {
|
||||
const name = saveViewName.value.trim()
|
||||
if (!name || !currentSearchPlan.value) return
|
||||
savingView.value = true
|
||||
try {
|
||||
await createSavedView({
|
||||
name,
|
||||
objectApiName: objectApiName.value,
|
||||
filters: currentSearchPlan.value.filters,
|
||||
sort: currentSearchPlan.value.sort,
|
||||
description: currentSearchPlan.value.explanation,
|
||||
})
|
||||
saveViewDialogOpen.value = false
|
||||
saveViewName.value = ''
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to save view'
|
||||
} finally {
|
||||
savingView.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenViewManager = () => {
|
||||
viewPanelOpen.value = true
|
||||
}
|
||||
|
||||
const handleUpdateView = async (id: string, payload: any) => {
|
||||
await updateSavedView(id, payload)
|
||||
}
|
||||
|
||||
const handleDeleteView = async (view: SavedView) => {
|
||||
await deleteSavedView(view.id)
|
||||
if (activeViewId.value === view.id) {
|
||||
activeViewId.value = null
|
||||
currentSearchPlan.value = null
|
||||
await initializeListRecords()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => records.value.map(record => normalizeRecordId(record.id)),
|
||||
(ids) => {
|
||||
const idSet = new Set(ids)
|
||||
const nextDrafts: Record<string, Record<string, any>> = {}
|
||||
const nextOriginals: Record<string, Record<string, any>> = {}
|
||||
const nextErrors: Record<string, Record<string, string>> = {}
|
||||
|
||||
for (const [recordKey, fields] of Object.entries(draftEdits.value)) {
|
||||
if (idSet.has(recordKey)) nextDrafts[recordKey] = fields
|
||||
}
|
||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
||||
if (idSet.has(recordKey)) nextOriginals[recordKey] = fields
|
||||
}
|
||||
for (const [recordKey, fields] of Object.entries(cellErrors.value)) {
|
||||
if (idSet.has(recordKey)) nextErrors[recordKey] = fields
|
||||
}
|
||||
|
||||
draftEdits.value = nextDrafts
|
||||
draftOriginals.value = nextOriginals
|
||||
cellErrors.value = nextErrors
|
||||
}
|
||||
)
|
||||
|
||||
// Watch for route changes
|
||||
watch(() => route.params, async (newParams, oldParams) => {
|
||||
// Reset current record when navigating to 'new'
|
||||
@@ -390,6 +683,8 @@ onMounted(async () => {
|
||||
|
||||
if (view.value === 'list') {
|
||||
await initializeListRecords()
|
||||
// Load saved views for this object
|
||||
fetchSavedViews(objectApiName.value).catch(() => {})
|
||||
} else if (recordId.value && recordId.value !== 'new') {
|
||||
await fetchRecord(recordId.value)
|
||||
}
|
||||
@@ -438,6 +733,13 @@ onMounted(async () => {
|
||||
:total-count="totalCount"
|
||||
:search-summary="searchSummary"
|
||||
:base-url="`/runtime/objects`"
|
||||
:draft-edits="draftEdits"
|
||||
:cell-errors="cellErrors"
|
||||
:saving-drafts="savingDrafts"
|
||||
:saved-views="savedViews"
|
||||
:active-view-id="activeViewId"
|
||||
:current-search-plan="currentSearchPlan"
|
||||
:saving-view="savingView"
|
||||
selectable
|
||||
@row-click="handleRowClick"
|
||||
@create="handleCreate"
|
||||
@@ -446,6 +748,13 @@ onMounted(async () => {
|
||||
@search="handleSearch"
|
||||
@page-change="handlePageChange"
|
||||
@load-more="handleLoadMore"
|
||||
@view-change="handleViewChange"
|
||||
@cell-edit="handleCellEdit"
|
||||
@save-drafts="handleSaveDrafts"
|
||||
@discard-drafts="handleDiscardDrafts"
|
||||
@apply-view="handleApplyView"
|
||||
@save-view="handleSaveView"
|
||||
@open-view-manager="handleOpenViewManager"
|
||||
/>
|
||||
|
||||
<!-- Detail View -->
|
||||
@@ -517,6 +826,46 @@ onMounted(async () => {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- Save view dialog -->
|
||||
<Dialog v-model:open="saveViewDialogOpen">
|
||||
<DialogContent class="sm:max-w-[420px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Save view</DialogTitle>
|
||||
<DialogDescription>
|
||||
Give this search a name so you can reuse it later.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div class="space-y-2 py-2">
|
||||
<Label for="view-name">View name</Label>
|
||||
<Input
|
||||
id="view-name"
|
||||
v-model="saveViewName"
|
||||
placeholder="e.g. Cocker Spaniels"
|
||||
@keyup.enter="confirmSaveView"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="saveViewDialogOpen = false" :disabled="savingView">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button @click="confirmSaveView" :disabled="savingView || !saveViewName.trim()">
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- Saved views slide-over panel -->
|
||||
<SavedViewPanel
|
||||
v-model:open="viewPanelOpen"
|
||||
:views="savedViews"
|
||||
:object-label="objectDefinition?.pluralLabel || objectDefinition?.label || objectApiName"
|
||||
:active-view-id="activeViewId"
|
||||
@apply-view="handleApplyView"
|
||||
@update-view="handleUpdateView"
|
||||
@delete-view="handleDeleteView"
|
||||
/>
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ const {
|
||||
fetchRecord,
|
||||
deleteRecord,
|
||||
deleteRecords,
|
||||
updateRecord,
|
||||
handleSave,
|
||||
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
|
||||
|
||||
@@ -90,6 +91,12 @@ const editConfig = computed(() => {
|
||||
|
||||
const listPageSize = computed(() => listConfig.value?.pageSize ?? 25)
|
||||
const maxFrontendRecords = computed(() => listConfig.value?.maxFrontendRecords ?? 500)
|
||||
const normalizeRecordId = (id: any) => String(id)
|
||||
|
||||
const draftEdits = ref<Record<string, Record<string, any>>>({})
|
||||
const draftOriginals = ref<Record<string, Record<string, any>>>({})
|
||||
const cellErrors = ref<Record<string, Record<string, string>>>({})
|
||||
const savingDrafts = ref(false)
|
||||
|
||||
// Fetch object definition
|
||||
const fetchObjectDefinition = async () => {
|
||||
@@ -212,6 +219,156 @@ const handleLoadMore = async (page: number, pageSize: number) => {
|
||||
await loadListRecords(page, { append: true, pageSize })
|
||||
}
|
||||
|
||||
const loadAllListRecords = async () => {
|
||||
if (!records.value.length) {
|
||||
await loadListRecords(1)
|
||||
}
|
||||
const resolvedTotal = totalCount.value ?? records.value.length
|
||||
if (resolvedTotal > records.value.length) {
|
||||
await loadListRecords(1, { append: false, pageSize: resolvedTotal })
|
||||
}
|
||||
}
|
||||
|
||||
const handleViewChange = async (mode: 'list' | 'spreadsheet') => {
|
||||
if (mode === 'spreadsheet') {
|
||||
await loadAllListRecords()
|
||||
}
|
||||
}
|
||||
|
||||
const handleCellEdit = async (payload: { row: any; field: any; newValue: any; oldValue: any }) => {
|
||||
if (!payload?.row?.id || payload.newValue === payload.oldValue) return
|
||||
const recordKey = normalizeRecordId(payload.row.id)
|
||||
const fieldName = payload.field.apiName
|
||||
const originalRow = draftOriginals.value[recordKey]
|
||||
const originalValue = originalRow && Object.prototype.hasOwnProperty.call(originalRow, fieldName)
|
||||
? originalRow[fieldName]
|
||||
: payload.oldValue
|
||||
|
||||
if (Object.is(payload.newValue, originalValue)) {
|
||||
const nextDrafts = { ...draftEdits.value }
|
||||
const nextRowDrafts = { ...(nextDrafts[recordKey] || {}) }
|
||||
delete nextRowDrafts[fieldName]
|
||||
if (Object.keys(nextRowDrafts).length === 0) {
|
||||
delete nextDrafts[recordKey]
|
||||
} else {
|
||||
nextDrafts[recordKey] = nextRowDrafts
|
||||
}
|
||||
draftEdits.value = nextDrafts
|
||||
|
||||
const nextOriginals = { ...draftOriginals.value }
|
||||
const nextRowOriginals = { ...(nextOriginals[recordKey] || {}) }
|
||||
delete nextRowOriginals[fieldName]
|
||||
if (Object.keys(nextRowOriginals).length === 0) {
|
||||
delete nextOriginals[recordKey]
|
||||
} else {
|
||||
nextOriginals[recordKey] = nextRowOriginals
|
||||
}
|
||||
draftOriginals.value = nextOriginals
|
||||
} else {
|
||||
draftEdits.value = {
|
||||
...draftEdits.value,
|
||||
[recordKey]: {
|
||||
...(draftEdits.value[recordKey] || {}),
|
||||
[fieldName]: payload.newValue,
|
||||
},
|
||||
}
|
||||
if (!originalRow || !Object.prototype.hasOwnProperty.call(originalRow, fieldName)) {
|
||||
draftOriginals.value = {
|
||||
...draftOriginals.value,
|
||||
[recordKey]: {
|
||||
...(draftOriginals.value[recordKey] || {}),
|
||||
[fieldName]: payload.oldValue,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cellErrors.value[recordKey]?.[fieldName]) {
|
||||
const nextErrors = { ...cellErrors.value }
|
||||
const nextRowErrors = { ...(nextErrors[recordKey] || {}) }
|
||||
delete nextRowErrors[fieldName]
|
||||
if (Object.keys(nextRowErrors).length === 0) {
|
||||
delete nextErrors[recordKey]
|
||||
} else {
|
||||
nextErrors[recordKey] = nextRowErrors
|
||||
}
|
||||
cellErrors.value = nextErrors
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveDrafts = async () => {
|
||||
if (Object.keys(draftEdits.value).length === 0) return
|
||||
savingDrafts.value = true
|
||||
const nextErrors: Record<string, Record<string, string>> = {}
|
||||
const nextDrafts = { ...draftEdits.value }
|
||||
const nextOriginals = { ...draftOriginals.value }
|
||||
|
||||
for (const [recordKey, changes] of Object.entries(draftEdits.value)) {
|
||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
||||
if (!record) {
|
||||
delete nextDrafts[recordKey]
|
||||
delete nextOriginals[recordKey]
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await updateRecord(record.id, changes)
|
||||
delete nextDrafts[recordKey]
|
||||
delete nextOriginals[recordKey]
|
||||
} catch (e: any) {
|
||||
const message = e.message || 'Failed to update record'
|
||||
nextErrors[recordKey] = {}
|
||||
for (const fieldName of Object.keys(changes)) {
|
||||
nextErrors[recordKey][fieldName] = message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
draftEdits.value = nextDrafts
|
||||
draftOriginals.value = nextOriginals
|
||||
cellErrors.value = nextErrors
|
||||
savingDrafts.value = false
|
||||
if (Object.keys(nextErrors).length > 0) {
|
||||
error.value = 'Some updates failed. Fix highlighted cells and try again.'
|
||||
}
|
||||
}
|
||||
|
||||
const handleDiscardDrafts = () => {
|
||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
||||
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
|
||||
if (!record) continue
|
||||
for (const [fieldName, originalValue] of Object.entries(fields)) {
|
||||
record[fieldName] = originalValue
|
||||
}
|
||||
}
|
||||
draftEdits.value = {}
|
||||
draftOriginals.value = {}
|
||||
cellErrors.value = {}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => records.value.map(record => normalizeRecordId(record.id)),
|
||||
(ids) => {
|
||||
const idSet = new Set(ids)
|
||||
const nextDrafts: Record<string, Record<string, any>> = {}
|
||||
const nextOriginals: Record<string, Record<string, any>> = {}
|
||||
const nextErrors: Record<string, Record<string, string>> = {}
|
||||
|
||||
for (const [recordKey, fields] of Object.entries(draftEdits.value)) {
|
||||
if (idSet.has(recordKey)) nextDrafts[recordKey] = fields
|
||||
}
|
||||
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
|
||||
if (idSet.has(recordKey)) nextOriginals[recordKey] = fields
|
||||
}
|
||||
for (const [recordKey, fields] of Object.entries(cellErrors.value)) {
|
||||
if (idSet.has(recordKey)) nextErrors[recordKey] = fields
|
||||
}
|
||||
|
||||
draftEdits.value = nextDrafts
|
||||
draftOriginals.value = nextOriginals
|
||||
cellErrors.value = nextErrors
|
||||
}
|
||||
)
|
||||
|
||||
// Watch for route changes
|
||||
watch(() => route.params, async (newParams, oldParams) => {
|
||||
// Reset current record when navigating to 'new'
|
||||
@@ -278,6 +435,9 @@ onMounted(async () => {
|
||||
:data="records"
|
||||
:loading="dataLoading"
|
||||
:total-count="totalCount"
|
||||
:draft-edits="draftEdits"
|
||||
:cell-errors="cellErrors"
|
||||
:saving-drafts="savingDrafts"
|
||||
selectable
|
||||
@row-click="handleRowClick"
|
||||
@create="handleCreate"
|
||||
@@ -285,6 +445,10 @@ onMounted(async () => {
|
||||
@delete="handleDelete"
|
||||
@page-change="handlePageChange"
|
||||
@load-more="handleLoadMore"
|
||||
@view-change="handleViewChange"
|
||||
@cell-edit="handleCellEdit"
|
||||
@save-drafts="handleSaveDrafts"
|
||||
@discard-drafts="handleDiscardDrafts"
|
||||
/>
|
||||
|
||||
<!-- Detail View -->
|
||||
|
||||
@@ -33,6 +33,10 @@
|
||||
<Label class="text-muted-foreground">Email</Label>
|
||||
<p class="font-medium">{{ user?.email }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="text-muted-foreground">Alias</Label>
|
||||
<p class="font-medium">{{ user?.alias || 'N/A' }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="text-muted-foreground">First Name</Label>
|
||||
<p class="font-medium">{{ user?.firstName || 'N/A' }}</p>
|
||||
@@ -210,6 +214,9 @@ const removeRole = async (roleId: string) => {
|
||||
|
||||
const getUserName = (user: any) => {
|
||||
if (!user) return 'User';
|
||||
if (user.alias) {
|
||||
return user.alias;
|
||||
}
|
||||
if (user.firstName || user.lastName) {
|
||||
return [user.firstName, user.lastName].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
@@ -95,6 +95,10 @@
|
||||
<Label for="lastName">Last Name (Optional)</Label>
|
||||
<Input id="lastName" v-model="newUser.lastName" placeholder="Doe" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Label for="alias">Alias (Optional)</Label>
|
||||
<Input id="alias" v-model="newUser.alias" placeholder="Display name" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="showCreateDialog = false">Cancel</Button>
|
||||
@@ -131,6 +135,10 @@
|
||||
<Label for="edit-lastName">Last Name</Label>
|
||||
<Input id="edit-lastName" v-model="editUser.lastName" placeholder="Doe" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Label for="edit-alias">Alias</Label>
|
||||
<Input id="edit-alias" v-model="editUser.alias" placeholder="Display name" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="showEditDialog = false">Cancel</Button>
|
||||
@@ -187,6 +195,7 @@ const newUser = ref({
|
||||
password: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
alias: '',
|
||||
});
|
||||
const editUser = ref({
|
||||
id: '',
|
||||
@@ -194,6 +203,7 @@ const editUser = ref({
|
||||
password: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
alias: '',
|
||||
});
|
||||
const userToDelete = ref<any>(null);
|
||||
|
||||
@@ -215,7 +225,7 @@ const createUser = async () => {
|
||||
await api.post('/setup/users', newUser.value);
|
||||
toast.success('User created successfully');
|
||||
showCreateDialog.value = false;
|
||||
newUser.value = { email: '', password: '', firstName: '', lastName: '' };
|
||||
newUser.value = { email: '', password: '', firstName: '', lastName: '', alias: '' };
|
||||
await loadUsers();
|
||||
} catch (error: any) {
|
||||
console.error('Failed to create user:', error);
|
||||
@@ -230,6 +240,7 @@ const openEditDialog = (user: any) => {
|
||||
password: '',
|
||||
firstName: user.firstName || '',
|
||||
lastName: user.lastName || '',
|
||||
alias: user.alias || '',
|
||||
};
|
||||
showEditDialog.value = true;
|
||||
};
|
||||
@@ -240,6 +251,7 @@ const updateUser = async () => {
|
||||
email: editUser.value.email,
|
||||
firstName: editUser.value.firstName,
|
||||
lastName: editUser.value.lastName,
|
||||
alias: editUser.value.alias,
|
||||
};
|
||||
if (editUser.value.password) {
|
||||
payload.password = editUser.value.password;
|
||||
@@ -273,6 +285,9 @@ const deleteUser = async () => {
|
||||
};
|
||||
|
||||
const getUserName = (user: any) => {
|
||||
if (user.alias) {
|
||||
return user.alias;
|
||||
}
|
||||
if (user.firstName || user.lastName) {
|
||||
return [user.firstName, user.lastName].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user