Compare commits
6 Commits
ag-table-t
...
fb2533fa4c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb2533fa4c | ||
|
|
12304d5890 | ||
|
|
a0bdb09c03 | ||
|
|
c89dc04d4c | ||
|
|
7a175923b0 | ||
|
|
ed48623f27 |
@@ -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();
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizedPlan;
|
||||
}
|
||||
|
||||
private normalizeSearchPlan(plan: AiSearchPlan, message: string): AiSearchPlan {
|
||||
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[],
|
||||
|
||||
@@ -9,6 +9,7 @@ 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';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -24,6 +25,7 @@ import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
|
||||
PageLayoutModule,
|
||||
VoiceModule,
|
||||
AiAssistantModule,
|
||||
SavedListViewModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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'
|
||||
|
||||
@@ -17,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, FieldConfig } from '@/types/field-types'
|
||||
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit } from 'lucide-vue-next'
|
||||
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit, Bookmark, BookmarkPlus, Settings2 } from 'lucide-vue-next'
|
||||
import type { SavedView } from '@/composables/useSavedViews'
|
||||
|
||||
interface Props {
|
||||
config: ListViewConfig
|
||||
@@ -32,6 +40,11 @@ interface Props {
|
||||
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>(), {
|
||||
@@ -43,6 +56,10 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
draftEdits: () => ({}),
|
||||
cellErrors: () => ({}),
|
||||
savingDrafts: false,
|
||||
savedViews: () => [],
|
||||
activeViewId: null,
|
||||
currentSearchPlan: null,
|
||||
savingView: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -61,6 +78,10 @@ const emit = defineEmits<{
|
||||
'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
|
||||
@@ -399,6 +420,66 @@ 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" />
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -177,6 +191,16 @@ 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 {
|
||||
@@ -323,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'
|
||||
@@ -383,6 +420,8 @@ const handleSearch = async (query: string) => {
|
||||
searchQuery.value = trimmed
|
||||
if (!trimmed) {
|
||||
searchSummary.value = ''
|
||||
currentSearchPlan.value = null
|
||||
activeViewId.value = null
|
||||
await initializeListRecords()
|
||||
return
|
||||
}
|
||||
@@ -499,6 +538,103 @@ const handleDiscardDrafts = () => {
|
||||
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) => {
|
||||
@@ -547,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)
|
||||
}
|
||||
@@ -598,6 +736,10 @@ onMounted(async () => {
|
||||
: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"
|
||||
@@ -610,6 +752,9 @@ onMounted(async () => {
|
||||
@cell-edit="handleCellEdit"
|
||||
@save-drafts="handleSaveDrafts"
|
||||
@discard-drafts="handleDiscardDrafts"
|
||||
@apply-view="handleApplyView"
|
||||
@save-view="handleSaveView"
|
||||
@open-view-manager="handleOpenViewManager"
|
||||
/>
|
||||
|
||||
<!-- Detail View -->
|
||||
@@ -681,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>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user