Compare commits

..

8 Commits

Author SHA1 Message Date
Francisco Gaona
baf3997fb6 WIP - fix displaying name for owner field 2026-04-10 22:19:11 +02:00
Francisco Gaona
a2d48f6a03 WIP - Fix options for picklist field, some progress on multi picklist. 2026-04-10 21:41:13 +02:00
Francisco Gaona
fb2533fa4c WIP - sharing list views 2026-04-10 10:57:20 +02:00
Francisco Gaona
12304d5890 WIP - saving list views 2026-04-10 10:37:11 +02:00
Francisco Gaona
a0bdb09c03 WIP - resolving related look ups for search filtering 2026-04-10 09:07:06 +02:00
Francisco Gaona
c89dc04d4c WIP - improve list filtering explanation 2026-04-09 21:46:29 +02:00
Francisco Gaona
7a175923b0 Merge branch 'codex/fix-ai-search-result-explanation' into integrate-query-explain-fix 2026-04-09 19:06:37 +02:00
phyroslam
ed48623f27 Use LLM refinement for query explanation text 2026-04-09 08:58:09 -07:00
26 changed files with 1672 additions and 34 deletions

View File

@@ -0,0 +1,55 @@
/**
* Creates the saved_list_views table.
* Each row stores a named, reusable search/filter configuration for a specific
* CRM object type. Views can be private to the owning user or shared with the
* whole tenant.
*
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = function (knex) {
return knex.schema.createTable('saved_list_views', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('(UUID())'));
// Human-readable name given by the user (or AI-suggested)
table.string('name').notNullable();
// The object this view belongs to (e.g. "Dog", "Contact")
table.string('object_api_name').notNullable();
// The user who created/owns this view
table.uuid('user_id').notNullable();
// When true the view is visible to all users in the tenant
table.boolean('is_shared').notNullable().defaultTo(false);
// Strategy is always "query" for saved views (keyword views are not saved)
table.string('strategy').notNullable().defaultTo('query');
// Resolved filters as JSON array of AiSearchFilter objects
table.json('filters').notNullable();
// Optional sort: { field: string, direction: "asc" | "desc" }
table.json('sort').nullable();
// AI-generated plain-language explanation of what this view shows
table.text('description').nullable();
table.timestamps(true, true);
// Foreign key to users
table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
// Primary lookup: all views for an object visible to a user
table.index(['object_api_name', 'user_id']);
table.index(['object_api_name', 'is_shared']);
});
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = function (knex) {
return knex.schema.dropTableIfExists('saved_list_views');
};

View File

@@ -0,0 +1,35 @@
/**
* Inserts a system object_definition row for SavedListView.
* This allows saved_list_views records to be shared via record_shares
* (which requires a valid objectDefinitionId FK).
*
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = async function (knex) {
// Only insert if it doesn't already exist (idempotent)
const existing = await knex('object_definitions')
.where({ apiName: 'SavedListView' })
.first();
if (!existing) {
await knex('object_definitions').insert({
apiName: 'SavedListView',
label: 'Saved List View',
pluralLabel: 'Saved List Views',
description: 'System object for sharing saved list views via record_shares',
isSystem: true,
isCustom: false,
});
}
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = async function (knex) {
await knex('object_definitions')
.where({ apiName: 'SavedListView' })
.delete();
};

View File

@@ -0,0 +1,30 @@
/**
* Add 'alias' and virtual 'name' column to users table.
*
* - alias: a user-editable display name / nickname
* - name: a generated column that returns COALESCE(alias, CONCAT(firstName, ' ', lastName), email)
* so that lookup fields referencing User.name always resolve.
*/
exports.up = function (knex) {
return knex.schema.alterTable('users', (table) => {
table.string('alias', 255).nullable().after('lastName');
table.string('name', 512).nullable().after('alias');
}).then(() => {
// Backfill existing rows: name = alias, or firstName + lastName, or email
return knex.raw(`
UPDATE users
SET name = COALESCE(
NULLIF(alias, ''),
NULLIF(TRIM(CONCAT(COALESCE(firstName, ''), ' ', COALESCE(lastName, ''))), ''),
email
)
`);
});
};
exports.down = function (knex) {
return knex.schema.alterTable('users', (table) => {
table.dropColumn('name');
table.dropColumn('alias');
});
};

View File

@@ -20,6 +20,8 @@ model User {
password String password String
firstName String? firstName String?
lastName String? lastName String?
alias String?
name String?
isActive Boolean @default(true) isActive Boolean @default(true)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt

View File

@@ -38,4 +38,12 @@ export class AiAssistantController {
payload, payload,
); );
} }
@Post('suggest-view-name')
async suggestViewName(
@TenantId() tenantId: string,
@Body() payload: { objectLabel: string; filters: any[]; explanation?: string },
) {
return this.aiAssistantService.suggestViewName(tenantId, payload);
}
} }

View File

@@ -49,7 +49,7 @@ type AiSearchPayload = {
@Injectable() @Injectable()
export class AiAssistantService { export class AiAssistantService {
private readonly logger = new Logger(AiAssistantService.name); private readonly logger = new Logger(AiAssistantService.name);
private readonly defaultModel = process.env.OPENAI_MODEL || 'gpt-4o'; private readonly defaultModel = process.env.OPENAI_MODEL || 'gpt-5.4-mini';
private readonly conversationState = new Map< private readonly conversationState = new Map<
string, string,
{ fields: Record<string, any>; updatedAt: number } { fields: Record<string, any>; updatedAt: number }
@@ -688,6 +688,8 @@ export class AiAssistantService {
totalCount: meiliResults.total ?? records.totalCount ?? 0, totalCount: meiliResults.total ?? records.totalCount ?? 0,
strategy: plan.strategy, strategy: plan.strategy,
explanation: plan.explanation, explanation: plan.explanation,
filters: [],
sort: null,
}; };
} }
@@ -702,16 +704,28 @@ export class AiAssistantService {
...fallback, ...fallback,
strategy: plan.strategy, strategy: plan.strategy,
explanation: plan.explanation, explanation: plan.explanation,
filters: [],
sort: null,
}; };
} }
console.log('AI search plan (query):', plan); console.log('AI search plan (query):', plan);
// Resolve any LOOKUP filter values (user typed a name, we find the related record ID)
const resolvedFilters = await this.resolveRelatedFilters(
resolvedTenantId,
userId,
objectDefinition,
plan.filters || [],
);
console.log('Resolved filters for query strategy:', resolvedFilters);
const filtered = await this.objectService.searchRecordsWithFilters( const filtered = await this.objectService.searchRecordsWithFilters(
resolvedTenantId, resolvedTenantId,
payload.objectApiName, payload.objectApiName,
userId, userId,
plan.filters || [], resolvedFilters,
{ page, pageSize }, { page, pageSize },
plan.sort || undefined, plan.sort || undefined,
); );
@@ -720,9 +734,53 @@ export class AiAssistantService {
...filtered, ...filtered,
strategy: plan.strategy, strategy: plan.strategy,
explanation: plan.explanation, explanation: plan.explanation,
filters: resolvedFilters,
sort: plan.sort || null,
}; };
} }
/**
* Asks the LLM to suggest a short, human-friendly name for a saved list view
* based on the resolved filters / explanation.
*/
async suggestViewName(
tenantId: string,
payload: { objectLabel: string; filters: AiSearchFilter[]; explanation?: string },
): Promise<{ suggestedName: string }> {
const openAiConfig = await this.getOpenAiConfig(tenantId);
if (!openAiConfig) {
return { suggestedName: `${payload.objectLabel} View` };
}
const model = new ChatOpenAI({
apiKey: openAiConfig.apiKey,
model: this.normalizeChatModel(openAiConfig.model),
temperature: 0.4,
});
const filterSummary = payload.explanation?.trim()
|| payload.filters.map(f => `${f.field} ${f.operator} ${f.value ?? ''}`).join(', ')
|| 'no filters';
try {
const response = await model.invoke([
new SystemMessage(
'You are a CRM assistant. Suggest a very short (25 words), descriptive, and human-friendly name for a saved list view. ' +
'Reply with ONLY the name, no quotes or punctuation.',
),
new HumanMessage(
`Object: ${payload.objectLabel}.\nFilter summary: ${filterSummary}`,
),
]);
const raw = typeof response.content === 'string' ? response.content.trim() : '';
const suggestedName = raw || `${payload.objectLabel} View`;
return { suggestedName };
} catch {
return { suggestedName: `${payload.objectLabel} View` };
}
}
// ============================================ // ============================================
// Planning-Based LangGraph Workflow // Planning-Based LangGraph Workflow
// ============================================ // ============================================
@@ -2207,6 +2265,59 @@ export class AiAssistantService {
return extracted; return extracted;
} }
/**
* Resolves LOOKUP filter values from human-readable names to actual record IDs.
* When the AI produces a filter like { field: "familyId", operator: "eq", value: "Gaona Family" },
* this method looks up "Gaona Family" in the referenced object and replaces the value with its ID.
*/
private async resolveRelatedFilters(
tenantId: string,
userId: string,
objectDefinition: any,
filters: AiSearchFilter[],
): Promise<AiSearchFilter[]> {
if (!filters || filters.length === 0) return filters;
const lookupFieldMap = new Map<string, string>(); // apiName → referenceObject
for (const field of objectDefinition.fields || []) {
if (field.type === 'LOOKUP' && field.referenceObject) {
lookupFieldMap.set(field.apiName, field.referenceObject);
}
}
const resolved: AiSearchFilter[] = [];
for (const filter of filters) {
const referenceObject = lookupFieldMap.get(filter.field);
if (
referenceObject &&
filter.value &&
typeof filter.value === 'string' &&
!this.isUuid(filter.value)
) {
// Try to resolve the name to an ID in the referenced object
try {
console.log(`Resolving LOOKUP filter: ${filter.field} → searching "${filter.value}" in ${referenceObject}`);
const relatedRecord = await this.searchForExistingRecord(tenantId, userId, referenceObject, filter.value);
if (relatedRecord?.id) {
console.log(`Resolved "${filter.value}" → ID: ${relatedRecord.id}`);
resolved.push({ ...filter, operator: 'eq', value: relatedRecord.id });
} else {
// Could not resolve; keep as-is so we get 0 results rather than wrong ones
console.warn(`Could not resolve related record "${filter.value}" in ${referenceObject}; keeping original filter`);
resolved.push(filter);
}
} catch (err) {
this.logger.warn(`Failed to resolve lookup filter for ${filter.field}: ${err.message}`);
resolved.push(filter);
}
} else {
resolved.push(filter);
}
}
return resolved;
}
private async buildSearchPlan( private async buildSearchPlan(
tenantId: string, tenantId: string,
message: string, message: string,
@@ -2250,25 +2361,65 @@ export class AiAssistantService {
apiName: field.apiName, apiName: field.apiName,
label: field.label, label: field.label,
type: field.type, type: field.type,
...(field.referenceObject ? { referenceObject: field.referenceObject } : {}),
})); }));
const formatInstructions = parser.getFormatInstructions(); const formatInstructions = parser.getFormatInstructions();
const today = new Date().toISOString(); const today = new Date().toISOString();
const systemPromptLines = [
`You are a CRM search assistant. The user is browsing a list of "${objectDefinition.label || objectDefinition.apiName}" records.`,
``,
`Your task: decide whether the user input is a KEYWORD search or a STRUCTURED QUERY, then return the correct JSON plan.`,
``,
`=== STRATEGY DECISION RULES ===`,
`Use strategy="query" when the user:`,
` - Describes a record attribute or property value (e.g. "list all golden retrievers" → filter the race field)`,
` - Uses phrases like "list all X", "show all X", "find all X", "filter by X", "where X is Y"`,
` - Mentions a specific field value, status, category, type, breed, color, size, or any distinguishing characteristic`,
` - Requests records matching a condition (e.g. "created this week", "price > 100", "active only")`,
` - Asks for sorted or ordered results (e.g. "newest first", "alphabetically")`,
``,
`Use strategy="keyword" ONLY when the user types a bare search term with no clear field or attribute intent`,
` - e.g. a lone name or identifier: "rex", "john", "acme corp"`,
``,
`=== HOW TO MAP USER LANGUAGE TO FIELDS ===`,
`When the user describes a characteristic or property value, find the best-matching field from the Fields list`,
`and apply a "contains" filter (or "eq" for exact values). Do NOT fall back to keyword just because the`,
`field name is not explicitly mentioned — infer the intent from context.`,
``,
`EXAMPLES (Object = Dog, fields include: name, race, size, color, createdAt, familyId[LOOKUP→Family]):`,
` "list all cocker spaniels" → strategy=query, filter: race contains "cocker spaniel"`,
` "show golden retrievers" → strategy=query, filter: race contains "golden retriever"`,
` "large dogs" → strategy=query, filter: size contains "large"`,
` "dogs added this week" → strategy=query, filter: createdAt between <monday> <today>`,
` "dogs belonging to Gaona Family" → strategy=query, filter: familyId eq "Gaona Family"`,
` "rex" → strategy=keyword, keyword="rex"`,
``,
`=== LOOKUP FIELDS ===`,
`Fields with type LOOKUP store a reference (ID) to another object (referenceObject).`,
`When the user refers to a related record by its name (e.g. "belonging to Gaona Family"),`,
`output the human-readable name as the filter value — the system will resolve it to the correct ID.`,
`Use the LOOKUP field apiName (e.g. familyId) as the filter field.`,
``,
`=== OUTPUT FORMAT ===`,
`Return a JSON object with these keys:`,
` strategy : "keyword" or "query"`,
` explanation : short plain-language description of what the search does`,
` keyword : the search term when strategy is "keyword", otherwise null`,
` filters : array of filter objects for strategy="query" (empty array otherwise)`,
` sort : {field, direction} when sorting is requested, otherwise null`,
``,
`Each filter object: { field: <apiName>, operator: <op>, value?, values?, from?, to? }`,
`Valid operators: eq | neq | gt | gte | lt | lte | contains | startsWith | endsWith | in | notIn | isNull | notNull | between`,
`Use "between" with {from, to} for date ranges.`,
`Only use field apiName values exactly as they appear in the Fields list provided.`,
``,
formatInstructions,
].join('\n');
const response = await model.invoke([ const response = await model.invoke([
new SystemMessage( new SystemMessage(systemPromptLines),
`You are a CRM search assistant. Decide whether the user input is a keyword search or a structured query.` +
`\nReturn a JSON object with keys: strategy, explanation, keyword, filters, sort.` +
`\n- strategy must be "keyword" or "query".` +
`\n- explanation must be a short sentence explaining the approach.` +
`\n- keyword should be the search term when strategy is "keyword", otherwise null.` +
`\n- filters is an array of {field, operator, value, values, from, to}.` +
`\n- operators must be one of eq, neq, gt, gte, lt, lte, contains, startsWith, endsWith, in, notIn, isNull, notNull, between.` +
`\n- Use between with from/to when the user gives date ranges like "yesterday" or "last week".` +
`\n- sort should be {field, direction} when sorting is requested.` +
`\n- Only use field apiName values exactly as provided.` +
`\n${formatInstructions}`,
),
new HumanMessage( new HumanMessage(
`Object: ${objectDefinition.label || objectDefinition.apiName}.\n` + `Object: ${objectDefinition.label || objectDefinition.apiName}.\n` +
`Fields: ${JSON.stringify(fields)}.\n` + `Fields: ${JSON.stringify(fields)}.\n` +
@@ -2279,10 +2430,30 @@ export class AiAssistantService {
const content = typeof response.content === 'string' ? response.content : '{}'; const content = typeof response.content === 'string' ? response.content : '{}';
const parsed = await parser.parse(content); const parsed = await parser.parse(content);
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') { if (!plan || typeof plan !== 'object') {
return this.buildSearchPlanFallback(message); 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 { return {
strategy, strategy,
explanation, explanation: queryExplanation || explanation,
keyword: null, keyword: null,
filters: Array.isArray(plan.filters) ? plan.filters : [], filters: Array.isArray(plan.filters) ? plan.filters : [],
sort: plan.sort || null, sort: plan.sort || null,
}; };
} }
private buildQueryExplanation(
message: string,
objectDefinition: any,
filters: AiSearchFilter[],
sort: { field: string; direction: 'asc' | 'desc' } | null,
): string {
const fieldLabelByApiName = new Map<string, string>(
(objectDefinition?.fields || []).map((field: any) => [field.apiName, field.label || field.apiName]),
);
const objectLabel = objectDefinition?.label || objectDefinition?.apiName || 'records';
const filterParts = filters
.map((filter) => this.describeFilter(filter, fieldLabelByApiName))
.filter(Boolean) as string[];
const sortLabel = sort?.field
? fieldLabelByApiName.get(sort.field) || sort.field
: null;
const sortPart =
sortLabel && sort?.direction
? `sorted by ${sortLabel} (${sort.direction === 'desc' ? 'newest/highest first' : 'oldest/lowest first'})`
: '';
if (filterParts.length > 0 && sortPart) {
return `Showing ${objectLabel} where ${filterParts.join(' and ')}, ${sortPart}.`;
}
if (filterParts.length > 0) {
return `Showing ${objectLabel} where ${filterParts.join(' and ')}.`;
}
if (sortPart) {
return `Showing ${objectLabel} ${sortPart}.`;
}
return `Applied filters based on: "${message.trim()}".`;
}
private describeFilter(filter: AiSearchFilter, fieldLabelByApiName: Map<string, string>): string {
const fieldLabel = fieldLabelByApiName.get(filter.field) || filter.field;
const formatValue = (value: any) =>
value === null || value === undefined || value === ''
? 'empty'
: typeof value === 'string'
? `"${value}"`
: String(value);
switch (filter.operator) {
case 'eq':
return `${fieldLabel} is ${formatValue(filter.value)}`;
case 'neq':
return `${fieldLabel} is not ${formatValue(filter.value)}`;
case 'gt':
return `${fieldLabel} is greater than ${formatValue(filter.value)}`;
case 'gte':
return `${fieldLabel} is at least ${formatValue(filter.value)}`;
case 'lt':
return `${fieldLabel} is less than ${formatValue(filter.value)}`;
case 'lte':
return `${fieldLabel} is at most ${formatValue(filter.value)}`;
case 'contains':
return `${fieldLabel} contains ${formatValue(filter.value)}`;
case 'startsWith':
return `${fieldLabel} starts with ${formatValue(filter.value)}`;
case 'endsWith':
return `${fieldLabel} ends with ${formatValue(filter.value)}`;
case 'in':
return `${fieldLabel} is one of ${(filter.values || []).map(formatValue).join(', ')}`;
case 'notIn':
return `${fieldLabel} is not one of ${(filter.values || []).map(formatValue).join(', ')}`;
case 'isNull':
return `${fieldLabel} is empty`;
case 'notNull':
return `${fieldLabel} is not empty`;
case 'between':
if (filter.from && filter.to) {
return `${fieldLabel} is between ${formatValue(filter.from)} and ${formatValue(filter.to)}`;
}
if (filter.from) {
return `${fieldLabel} is from ${formatValue(filter.from)} onward`;
}
if (filter.to) {
return `${fieldLabel} is up to ${formatValue(filter.to)}`;
}
return `${fieldLabel} uses a date range filter`;
default:
return '';
}
}
private async generateQueryExplanationWithAi(
model: ChatOpenAI,
message: string,
objectDefinition: any,
plan: AiSearchPlan,
): Promise<string | null> {
try {
const fields = (objectDefinition?.fields || []).map((field: any) => ({
apiName: field.apiName,
label: field.label || field.apiName,
}));
const response = await model.invoke([
new SystemMessage(
`You explain CRM list query results in plain language for end users.` +
`\nWrite one short sentence (max 25 words).` +
`\nDescribe the resulting filters/sort in business language.` +
`\nDo NOT mention SQL, JSON, "strategy", "query mode", or AI decision process.` +
`\nIf values are present, mention the most important ones clearly.`,
),
new HumanMessage(
`Object: ${objectDefinition?.label || objectDefinition?.apiName || 'records'}\n` +
`User request: ${message}\n` +
`Available fields: ${JSON.stringify(fields)}\n` +
`Applied filters: ${JSON.stringify(plan.filters || [])}\n` +
`Applied sort: ${JSON.stringify(plan.sort || null)}\n` +
`Current explanation draft: ${plan.explanation}`,
),
]);
const content = Array.isArray(response.content)
? response.content
.map((part: any) => (typeof part === 'string' ? part : part?.text || ''))
.join(' ')
: String(response.content || '');
const cleaned = content.trim().replace(/\s+/g, ' ');
console.log('AI-generated query explanation:', cleaned);
return cleaned || null;
} catch (error) {
this.logger.warn(`AI query explanation refinement failed: ${error.message}`);
return null;
}
}
private sanitizeUserOwnerFields( private sanitizeUserOwnerFields(
fields: Record<string, any>, fields: Record<string, any>,
fieldDefinitions: any[], fieldDefinitions: any[],

View File

@@ -9,6 +9,7 @@ import { AppBuilderModule } from './app-builder/app-builder.module';
import { PageLayoutModule } from './page-layout/page-layout.module'; import { PageLayoutModule } from './page-layout/page-layout.module';
import { VoiceModule } from './voice/voice.module'; import { VoiceModule } from './voice/voice.module';
import { AiAssistantModule } from './ai-assistant/ai-assistant.module'; import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
import { SavedListViewModule } from './saved-list-view/saved-list-view.module';
@Module({ @Module({
imports: [ imports: [
@@ -24,6 +25,7 @@ import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
PageLayoutModule, PageLayoutModule,
VoiceModule, VoiceModule,
AiAssistantModule, AiAssistantModule,
SavedListViewModule,
], ],
}) })
export class AppModule {} export class AppModule {}

View File

@@ -1,4 +1,5 @@
import { BaseModel } from './base.model'; import { BaseModel } from './base.model';
import { ModelOptions, QueryContext } from 'objection';
export class User extends BaseModel { export class User extends BaseModel {
static tableName = 'users'; static tableName = 'users';
@@ -8,6 +9,8 @@ export class User extends BaseModel {
password: string; password: string;
firstName?: string; firstName?: string;
lastName?: string; lastName?: string;
alias?: string;
name?: string;
isActive: boolean; isActive: boolean;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
@@ -22,11 +25,37 @@ export class User extends BaseModel {
password: { type: 'string' }, password: { type: 'string' },
firstName: { type: 'string' }, firstName: { type: 'string' },
lastName: { type: 'string' }, lastName: { type: 'string' },
alias: { type: 'string' },
name: { type: 'string' },
isActive: { type: 'boolean' }, isActive: { type: 'boolean' },
}, },
}; };
} }
/**
* Compute the `name` column before insert/update so lookup fields
* referencing User.name always have a value.
*/
private computeName() {
if (this.alias) {
this.name = this.alias;
} else if (this.firstName || this.lastName) {
this.name = [this.firstName, this.lastName].filter(Boolean).join(' ');
} else if (this.email) {
this.name = this.email;
}
}
$beforeInsert(queryContext: QueryContext) {
super.$beforeInsert(queryContext);
this.computeName();
}
$beforeUpdate(opt: ModelOptions, queryContext: QueryContext) {
super.$beforeUpdate(opt, queryContext);
this.computeName();
}
static get relationMappings() { static get relationMappings() {
const { UserRole } = require('./user-role.model'); const { UserRole } = require('./user-role.model');
const { Role } = require('./role.model'); const { Role } = require('./role.model');

View File

@@ -152,6 +152,7 @@ export class FieldMapperService {
'phone': 'text', 'phone': 'text',
'picklist': 'select', 'picklist': 'select',
'multipicklist': 'multiSelect', 'multipicklist': 'multiSelect',
'multi_picklist': 'multiSelect',
'lookup': 'belongsTo', 'lookup': 'belongsTo',
'master-detail': 'belongsTo', 'master-detail': 'belongsTo',
'currency': 'currency', 'currency': 'currency',

View File

@@ -336,13 +336,27 @@ export class ObjectService {
updated_at: knex.fn.now(), updated_at: knex.fn.now(),
}; };
// Store relationDisplayField in UI metadata if provided // Build UI metadata from all sources
if (data.relationDisplayField || data.relationObjects || data.relationTypeField) { const uiMetadataObj: any = {};
fieldData.ui_metadata = JSON.stringify({
relationDisplayField: data.relationDisplayField, // Merge general uiMetadata (options, placeholder, helpText, etc.)
relationObjects: data.relationObjects, if (data.uiMetadata && typeof data.uiMetadata === 'object') {
relationTypeField: data.relationTypeField, 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); await knex('field_definitions').insert(fieldData);

View File

@@ -111,4 +111,33 @@ export class RuntimeObjectController {
user.userId, user.userId,
); );
} }
/**
* Direct filter-based search — used when applying a saved list view.
* Bypasses the AI planning step; accepts pre-resolved structured filters.
*/
@Post(':objectApiName/records/search')
async searchRecords(
@TenantId() tenantId: string,
@Param('objectApiName') objectApiName: string,
@CurrentUser() user: any,
@Body() body: {
filters?: Array<{ field: string; operator: string; value?: any; values?: any[]; from?: string; to?: string }>;
sort?: { field: string; direction: 'asc' | 'desc' } | null;
page?: number;
pageSize?: number;
},
) {
const page = Number.isFinite(Number(body?.page)) ? Number(body.page) : 1;
const pageSize = Number.isFinite(Number(body?.pageSize)) ? Number(body.pageSize) : 25;
return this.objectService.searchRecordsWithFilters(
tenantId,
objectApiName,
user.userId,
body?.filters || [],
{ page, pageSize },
body?.sort || undefined,
);
}
} }

View File

@@ -39,7 +39,7 @@ export class SetupUsersController {
@Post() @Post()
async createUser( async createUser(
@TenantId() tenantId: string, @TenantId() tenantId: string,
@Body() data: { email: string; password: string; firstName?: string; lastName?: string }, @Body() data: { email: string; password: string; firstName?: string; lastName?: string; alias?: string },
) { ) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId); const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId); const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
@@ -52,6 +52,7 @@ export class SetupUsersController {
password: hashedPassword, password: hashedPassword,
firstName: data.firstName, firstName: data.firstName,
lastName: data.lastName, lastName: data.lastName,
alias: data.alias,
isActive: true, isActive: true,
}); });
@@ -62,7 +63,7 @@ export class SetupUsersController {
async updateUser( async updateUser(
@TenantId() tenantId: string, @TenantId() tenantId: string,
@Param('id') id: string, @Param('id') id: string,
@Body() data: { email?: string; password?: string; firstName?: string; lastName?: string }, @Body() data: { email?: string; password?: string; firstName?: string; lastName?: string; alias?: string },
) { ) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId); const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId); const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
@@ -72,6 +73,7 @@ export class SetupUsersController {
if (data.email) updateData.email = data.email; if (data.email) updateData.email = data.email;
if (data.firstName !== undefined) updateData.firstName = data.firstName; if (data.firstName !== undefined) updateData.firstName = data.firstName;
if (data.lastName !== undefined) updateData.lastName = data.lastName; if (data.lastName !== undefined) updateData.lastName = data.lastName;
if (data.alias !== undefined) updateData.alias = data.alias;
// Hash password if provided // Hash password if provided
if (data.password) { if (data.password) {

View File

@@ -0,0 +1,53 @@
import { IsString, IsNotEmpty, IsArray, IsOptional } from 'class-validator';
export class CreateSavedViewDto {
@IsString()
@IsNotEmpty()
name: string;
@IsString()
@IsNotEmpty()
objectApiName: string;
@IsArray()
filters: Array<{
field: string;
operator: string;
value?: any;
values?: any[];
from?: string;
to?: string;
}>;
@IsOptional()
sort?: { field: string; direction: 'asc' | 'desc' } | null;
@IsOptional()
@IsString()
description?: string;
}
export class UpdateSavedViewDto {
@IsOptional()
@IsString()
@IsNotEmpty()
name?: string;
@IsOptional()
@IsArray()
filters?: Array<{
field: string;
operator: string;
value?: any;
values?: any[];
from?: string;
to?: string;
}>;
@IsOptional()
sort?: { field: string; direction: 'asc' | 'desc' } | null;
@IsOptional()
@IsString()
description?: string;
}

View File

@@ -0,0 +1,92 @@
import {
Controller,
Get,
Post,
Patch,
Delete,
Body,
Param,
UseGuards,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { TenantId } from '../tenant/tenant.decorator';
import { SavedListViewService } from './saved-list-view.service';
import { CreateSavedViewDto, UpdateSavedViewDto } from './dto/saved-list-view.dto';
import { CreateRecordShareDto } from '../rbac/dto/create-record-share.dto';
@Controller('saved-views')
@UseGuards(JwtAuthGuard)
export class SavedListViewController {
constructor(private readonly savedListViewService: SavedListViewService) {}
@Get(':objectApiName')
findByObject(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Param('objectApiName') objectApiName: string,
) {
return this.savedListViewService.findByObject(tenantId, user.userId, objectApiName);
}
@Post()
create(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Body() dto: CreateSavedViewDto,
) {
return this.savedListViewService.create(tenantId, user.userId, dto);
}
@Patch(':id')
update(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Param('id') id: string,
@Body() dto: UpdateSavedViewDto,
) {
return this.savedListViewService.update(tenantId, user.userId, id, dto);
}
@Delete(':id')
remove(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Param('id') id: string,
) {
return this.savedListViewService.remove(tenantId, user.userId, id);
}
// ── Sharing endpoints (reuse record_shares table) ────────────────────────
@Get(':id/shares')
getShares(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Param('id') id: string,
) {
return this.savedListViewService.getShares(tenantId, user.userId, id);
}
@Post(':id/shares')
createShare(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Param('id') id: string,
@Body() dto: CreateRecordShareDto,
) {
return this.savedListViewService.createShare(tenantId, user.userId, id, dto);
}
@Delete(':id/shares/:shareId')
removeShare(
@TenantId() tenantId: string,
@CurrentUser() user: any,
@Param('id') id: string,
@Param('shareId') shareId: string,
) {
return this.savedListViewService.removeShare(tenantId, user.userId, id, shareId);
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { SavedListViewService } from './saved-list-view.service';
import { SavedListViewController } from './saved-list-view.controller';
import { TenantModule } from '../tenant/tenant.module';
@Module({
imports: [TenantModule],
controllers: [SavedListViewController],
providers: [SavedListViewService],
exports: [SavedListViewService],
})
export class SavedListViewModule {}

View File

@@ -0,0 +1,264 @@
import { Injectable, NotFoundException, ForbiddenException, BadRequestException } from '@nestjs/common';
import { TenantDatabaseService } from '../tenant/tenant-database.service';
import { CreateSavedViewDto, UpdateSavedViewDto } from './dto/saved-list-view.dto';
import { RecordShare } from '../models/record-share.model';
import { ObjectDefinition } from '../models/object-definition.model';
@Injectable()
export class SavedListViewService {
constructor(private readonly tenantDbService: TenantDatabaseService) {}
// ── Helpers ──────────────────────────────────────────────────────────────
/**
* Resolves the system object_definition ID for SavedListView.
* This is needed to create record_shares rows for saved views.
*/
private async getSavedViewObjectDefId(knex: any): Promise<string> {
const objectDef = await ObjectDefinition.query(knex)
.findOne({ apiName: 'SavedListView' });
if (!objectDef) {
throw new BadRequestException(
'SavedListView system object not found. Please run migrations.',
);
}
return objectDef.id;
}
// ── CRUD ─────────────────────────────────────────────────────────────────
/**
* Returns all saved views visible to the user for a given object:
* - Views owned by the user
* - Views shared with the user via record_shares
*/
async findByObject(tenantId: string, userId: string, objectApiName: string) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const objectDefId = await this.getSavedViewObjectDefId(knex);
// IDs of views shared with this user via record_shares
const sharedViewIds = await RecordShare.query(knex)
.where({ objectDefinitionId: objectDefId, granteeUserId: userId })
.whereNull('revokedAt')
.where(builder => {
builder.whereNull('expiresAt').orWhere('expiresAt', '>', new Date());
})
.select('recordId');
const sharedIds = sharedViewIds.map((s: any) => s.recordId);
const rows = await knex('saved_list_views')
.where({ object_api_name: objectApiName })
.andWhere(function () {
this.where({ user_id: userId });
if (sharedIds.length > 0) {
this.orWhereIn('id', sharedIds);
}
})
.orderBy('created_at', 'asc');
return rows.map((r: any) => this.deserialize(r, userId));
}
async create(tenantId: string, userId: string, dto: CreateSavedViewDto) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const id = require('crypto').randomUUID();
await knex('saved_list_views').insert({
id,
name: dto.name,
object_api_name: dto.objectApiName,
user_id: userId,
is_shared: false,
strategy: 'query',
filters: JSON.stringify(dto.filters || []),
sort: dto.sort ? JSON.stringify(dto.sort) : null,
description: dto.description || null,
});
const row = await knex('saved_list_views').where({ id }).first();
return this.deserialize(row, userId);
}
async update(tenantId: string, userId: string, id: string, dto: UpdateSavedViewDto) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const existing = await knex('saved_list_views').where({ id }).first();
if (!existing) throw new NotFoundException(`Saved view ${id} not found`);
if (existing.user_id !== userId) {
throw new ForbiddenException('You can only modify views you own');
}
const updates: Record<string, any> = { updated_at: knex.fn.now() };
if (dto.name !== undefined) updates.name = dto.name;
if (dto.filters !== undefined) updates.filters = JSON.stringify(dto.filters);
if (dto.sort !== undefined) updates.sort = dto.sort ? JSON.stringify(dto.sort) : null;
if (dto.description !== undefined) updates.description = dto.description;
await knex('saved_list_views').where({ id }).update(updates);
const row = await knex('saved_list_views').where({ id }).first();
return this.deserialize(row, userId);
}
async remove(tenantId: string, userId: string, id: string) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const existing = await knex('saved_list_views').where({ id }).first();
if (!existing) throw new NotFoundException(`Saved view ${id} not found`);
if (existing.user_id !== userId) {
throw new ForbiddenException('You can only delete views you own');
}
// Also clean up any record_shares for this view
const objectDefId = await this.getSavedViewObjectDefId(knex);
await RecordShare.query(knex)
.where({ objectDefinitionId: objectDefId, recordId: id })
.delete();
await knex('saved_list_views').where({ id }).delete();
return { deleted: true };
}
// ── Sharing via record_shares ────────────────────────────────────────────
async getShares(tenantId: string, userId: string, viewId: string) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const view = await knex('saved_list_views').where({ id: viewId }).first();
if (!view) throw new NotFoundException('Saved view not found');
if (view.user_id !== userId) {
throw new ForbiddenException('Only the view owner can manage sharing');
}
const objectDefId = await this.getSavedViewObjectDefId(knex);
const shares = await RecordShare.query(knex)
.where({ objectDefinitionId: objectDefId, recordId: viewId })
.whereNull('revokedAt')
.where(builder => {
builder.whereNull('expiresAt').orWhere('expiresAt', '>', new Date());
})
.withGraphFetched('[granteeUser]')
.orderBy('createdAt', 'desc');
return shares;
}
async createShare(
tenantId: string,
userId: string,
viewId: string,
dto: { granteeUserId: string; canRead: boolean; canEdit: boolean; canDelete: boolean; expiresAt?: string },
) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const view = await knex('saved_list_views').where({ id: viewId }).first();
if (!view) throw new NotFoundException('Saved view not found');
if (view.user_id !== userId) {
throw new ForbiddenException('Only the view owner can share it');
}
if (dto.granteeUserId === userId) {
throw new BadRequestException('Cannot share a view with yourself');
}
const objectDefId = await this.getSavedViewObjectDefId(knex);
// Upsert: if non-revoked share already exists for this grantee, update it
const existing = await RecordShare.query(knex)
.where({
objectDefinitionId: objectDefId,
recordId: viewId,
granteeUserId: dto.granteeUserId,
})
.whereNull('revokedAt')
.first();
if (existing) {
await RecordShare.query(knex)
.patchAndFetchById(existing.id, {
accessLevel: {
canRead: dto.canRead,
canEdit: dto.canEdit,
canDelete: dto.canDelete,
},
expiresAt: dto.expiresAt
? (knex.raw('?', [new Date(dto.expiresAt).toISOString().slice(0, 19).replace('T', ' ')]) as any)
: null,
} as any);
return RecordShare.query(knex)
.findById(existing.id)
.withGraphFetched('[granteeUser]');
}
const share = await RecordShare.query(knex).insertAndFetch({
objectDefinitionId: objectDefId,
recordId: viewId,
granteeUserId: dto.granteeUserId,
grantedByUserId: userId,
accessLevel: {
canRead: dto.canRead,
canEdit: dto.canEdit,
canDelete: dto.canDelete,
},
expiresAt: dto.expiresAt
? (knex.raw('?', [new Date(dto.expiresAt).toISOString().slice(0, 19).replace('T', ' ')]) as any)
: null,
} as any);
return RecordShare.query(knex)
.findById(share.id)
.withGraphFetched('[granteeUser]');
}
async removeShare(tenantId: string, userId: string, viewId: string, shareId: string) {
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
const view = await knex('saved_list_views').where({ id: viewId }).first();
if (!view) throw new NotFoundException('Saved view not found');
if (view.user_id !== userId) {
throw new ForbiddenException('Only the view owner can manage sharing');
}
const share = await RecordShare.query(knex).findById(shareId);
if (!share) throw new NotFoundException('Share not found');
// Soft-revoke
await RecordShare.query(knex)
.findById(shareId)
.patch({ revokedAt: knex.fn.now() } as any);
return { revoked: true };
}
// ── Serialisation ────────────────────────────────────────────────────────
private deserialize(row: any, currentUserId: string) {
return {
id: row.id,
name: row.name,
objectApiName: row.object_api_name,
userId: row.user_id,
isOwner: row.user_id === currentUserId,
isShared: Boolean(row.is_shared),
strategy: row.strategy,
filters: typeof row.filters === 'string' ? JSON.parse(row.filters) : (row.filters ?? []),
sort: row.sort
? (typeof row.sort === 'string' ? JSON.parse(row.sort) : row.sort)
: null,
description: row.description,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
}
}

View File

@@ -186,6 +186,8 @@ interface Props {
objectApiName: string; objectApiName: string;
recordId: string; recordId: string;
ownerId?: string; ownerId?: string;
/** Optional base URL override for shares API. Defaults to /runtime/objects/{objectApiName}/records/{recordId}/shares */
basePath?: string;
} }
const props = defineProps<Props>(); const props = defineProps<Props>();
@@ -193,6 +195,11 @@ const props = defineProps<Props>();
const { api } = useApi(); const { api } = useApi();
const { toast } = useToast(); const { toast } = useToast();
/** Computed base path for all share API calls */
const sharesBasePath = computed(() =>
props.basePath || `/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`
);
const loading = ref(true); const loading = ref(true);
const sharing = ref(false); const sharing = ref(false);
const removing = ref<string | null>(null); const removing = ref<string | null>(null);
@@ -236,9 +243,7 @@ const loadShares = async () => {
try { try {
loading.value = true; loading.value = true;
error.value = null; error.value = null;
const response = await api.get( const response = await api.get(sharesBasePath.value);
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`
);
shares.value = response || []; shares.value = response || [];
} catch (e: any) { } catch (e: any) {
console.error('Failed to load shares:', e); console.error('Failed to load shares:', e);
@@ -286,7 +291,7 @@ const createShare = async () => {
console.log('Final payload:', payload); console.log('Final payload:', payload);
await api.post( await api.post(
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares`, sharesBasePath.value,
payload payload
); );
toast.success('Record shared successfully'); toast.success('Record shared successfully');
@@ -313,7 +318,7 @@ const removeShare = async (shareId: string) => {
try { try {
removing.value = shareId; removing.value = shareId;
await api.delete( await api.delete(
`/runtime/objects/${props.objectApiName}/records/${props.recordId}/shares/${shareId}` `${sharesBasePath.value}/${shareId}`
); );
toast.success('Share removed successfully'); toast.success('Share removed successfully');
await loadShares(); await loadShares();

View File

@@ -0,0 +1,234 @@
<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetDescription,
} from '@/components/ui/sheet'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Pencil, Trash2, Users, Check, X, ChevronLeft } from 'lucide-vue-next'
import type { SavedView, UpdateSavedViewPayload } from '@/composables/useSavedViews'
interface Props {
open: boolean
views: SavedView[]
objectLabel: string
activeViewId?: string | null
}
const props = withDefaults(defineProps<Props>(), {
activeViewId: null,
})
const emit = defineEmits<{
'update:open': [value: boolean]
'apply-view': [view: SavedView]
'update-view': [id: string, payload: UpdateSavedViewPayload]
'delete-view': [view: SavedView]
}>()
const editingId = ref<string | null>(null)
const editName = ref('')
const deletingId = ref<string | null>(null)
// Sharing sub-view: when set, renders RecordSharing for this view
const sharingView = ref<SavedView | null>(null)
const ownViews = computed(() => props.views.filter(v => v.isOwner))
const sharedViews = computed(() => props.views.filter(v => !v.isOwner))
function startEdit(view: SavedView) {
editingId.value = view.id
editName.value = view.name
}
function cancelEdit() {
editingId.value = null
editName.value = ''
}
function commitEdit(view: SavedView) {
const name = editName.value.trim()
if (name && name !== view.name) {
emit('update-view', view.id, { name })
}
cancelEdit()
}
function openSharing(view: SavedView) {
sharingView.value = view
}
function closeSharing() {
sharingView.value = null
}
function confirmDelete(view: SavedView) {
deletingId.value = view.id
}
function cancelDelete() {
deletingId.value = null
}
function executeDelete(view: SavedView) {
emit('delete-view', view)
deletingId.value = null
}
</script>
<template>
<Sheet :open="open" @update:open="emit('update:open', $event)">
<SheetContent class="w-[420px] sm:w-[520px] overflow-y-auto">
<!-- Sharing sub-view -->
<template v-if="sharingView">
<SheetHeader class="mb-4">
<div class="flex items-center gap-2">
<Button size="icon" variant="ghost" class="h-7 w-7 -ml-1" @click="closeSharing">
<ChevronLeft class="h-4 w-4" />
</Button>
<div>
<SheetTitle>Share "{{ sharingView.name }}"</SheetTitle>
<SheetDescription>
Grant access to specific users for this saved view.
</SheetDescription>
</div>
</div>
</SheetHeader>
<RecordSharing
object-api-name="SavedListView"
:record-id="sharingView.id"
:owner-id="sharingView.userId"
:base-path="`/saved-views/${sharingView.id}/shares`"
/>
</template>
<!-- Main view list -->
<template v-else>
<SheetHeader class="mb-4">
<SheetTitle>{{ objectLabel }} Saved Views</SheetTitle>
<SheetDescription>
Manage your saved searches. Share views with specific users from your workspace.
</SheetDescription>
</SheetHeader>
<!-- Own Views -->
<section>
<p class="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
My Views
</p>
<div v-if="ownViews.length === 0" class="text-sm text-muted-foreground py-3">
You have no saved views yet. Run a search and click <strong>Save view</strong>.
</div>
<ul class="space-y-1">
<li
v-for="view in ownViews"
:key="view.id"
class="group rounded-md border bg-card px-3 py-2"
>
<!-- Confirm delete row -->
<div v-if="deletingId === view.id" class="flex items-center gap-2">
<span class="flex-1 text-sm text-destructive">Delete "{{ view.name }}"?</span>
<Button size="sm" variant="destructive" @click="executeDelete(view)">Delete</Button>
<Button size="sm" variant="outline" @click="cancelDelete">Cancel</Button>
</div>
<!-- Edit name row -->
<div v-else-if="editingId === view.id" class="flex items-center gap-2">
<Input
v-model="editName"
class="h-7 flex-1 text-sm"
@keyup.enter="commitEdit(view)"
@keyup.escape="cancelEdit"
autofocus
/>
<Button size="icon" variant="ghost" class="h-7 w-7" @click="commitEdit(view)">
<Check class="h-3.5 w-3.5" />
</Button>
<Button size="icon" variant="ghost" class="h-7 w-7" @click="cancelEdit">
<X class="h-3.5 w-3.5" />
</Button>
</div>
<!-- Normal row -->
<div v-else class="flex items-center gap-2 min-h-[28px]">
<!-- View name (click to apply) -->
<button
class="flex-1 text-left text-sm truncate hover:text-primary transition-colors"
:class="{ 'font-medium text-primary': activeViewId === view.id }"
@click="emit('apply-view', view); emit('update:open', false)"
>
{{ view.name }}
</button>
<!-- Actions (visible on hover) -->
<div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<Button size="icon" variant="ghost" class="h-6 w-6" title="Rename" @click="startEdit(view)">
<Pencil class="h-3 w-3" />
</Button>
<Button
size="icon"
variant="ghost"
class="h-6 w-6"
title="Share"
@click="openSharing(view)"
>
<Users class="h-3 w-3" />
</Button>
<Button size="icon" variant="ghost" class="h-6 w-6 text-destructive hover:text-destructive" title="Delete" @click="confirmDelete(view)">
<Trash2 class="h-3 w-3" />
</Button>
</div>
</div>
<!-- Description -->
<p
v-if="view.description && editingId !== view.id && deletingId !== view.id"
class="text-xs text-muted-foreground mt-1 truncate"
>
{{ view.description }}
</p>
</li>
</ul>
</section>
<!-- Shared views by others -->
<template v-if="sharedViews.length > 0">
<Separator class="my-4" />
<section>
<p class="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
Shared with me
</p>
<ul class="space-y-1">
<li
v-for="view in sharedViews"
:key="view.id"
class="rounded-md border bg-card px-3 py-2"
>
<button
class="w-full text-left text-sm truncate hover:text-primary transition-colors"
:class="{ 'font-medium text-primary': activeViewId === view.id }"
@click="emit('apply-view', view); emit('update:open', false)"
>
{{ view.name }}
</button>
<p v-if="view.description" class="text-xs text-muted-foreground mt-1 truncate">
{{ view.description }}
</p>
</li>
</ul>
</section>
</template>
</template>
</SheetContent>
</Sheet>
</template>

View File

@@ -249,6 +249,51 @@ const handleRelationTypeUpdate = (value: string | null) => {
</SelectContent> </SelectContent>
</Select> </Select>
<!-- Multi-Select -->
<div v-else-if="field.type === FieldType.MULTI_SELECT" class="space-y-2">
<div class="flex flex-wrap gap-1 min-h-[36px] rounded-md border border-input bg-background px-3 py-2">
<Badge
v-for="selectedVal in (Array.isArray(value) ? value : [])"
:key="String(selectedVal)"
variant="secondary"
class="gap-1 cursor-pointer"
@click="value = (value || []).filter((v: any) => v !== selectedVal)"
>
{{ field.options?.find(o => o.value === selectedVal)?.label || selectedVal }}
<span class="text-xs ml-1">&times;</span>
</Badge>
<span v-if="!value || (Array.isArray(value) && value.length === 0)" class="text-sm text-muted-foreground">
{{ field.placeholder || 'Select options...' }}
</span>
</div>
<div class="space-y-1">
<div
v-for="option in field.options"
:key="String(option.value)"
class="flex items-center gap-2"
>
<Checkbox
:id="`${field.id}-${option.value}`"
:checked="Array.isArray(value) && value.includes(option.value)"
@update:checked="(checked: boolean) => {
const current = Array.isArray(value) ? [...value] : []
if (checked) {
current.push(option.value)
} else {
const idx = current.indexOf(option.value)
if (idx > -1) current.splice(idx, 1)
}
value = current
}"
:disabled="field.isReadOnly"
/>
<Label :for="`${field.id}-${option.value}`" class="text-sm font-normal cursor-pointer">
{{ option.label }}
</Label>
</div>
</div>
</div>
<!-- Boolean - Checkbox --> <!-- Boolean - Checkbox -->
<div v-else-if="field.type === FieldType.BOOLEAN" class="flex items-center gap-2"> <div v-else-if="field.type === FieldType.BOOLEAN" class="flex items-center gap-2">
<Checkbox :id="field.id" v-model:checked="value" :disabled="field.isReadOnly" /> <Checkbox :id="field.id" v-model:checked="value" :disabled="field.isReadOnly" />

View File

@@ -0,0 +1,16 @@
<script setup lang="ts">
import { DropdownMenuSeparator, type DropdownMenuSeparatorProps, useForwardProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuSeparatorProps & { class?: HTMLAttributes['class'] }>()
const forwarded = useForwardProps(props)
</script>
<template>
<DropdownMenuSeparator
v-bind="forwarded"
:class="cn('-mx-1 my-1 h-px bg-muted', props.class)"
/>
</template>

View File

@@ -2,3 +2,4 @@ export { default as DropdownMenu } from './DropdownMenu.vue'
export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue' export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue'
export { default as DropdownMenuContent } from './DropdownMenuContent.vue' export { default as DropdownMenuContent } from './DropdownMenuContent.vue'
export { default as DropdownMenuItem } from './DropdownMenuItem.vue' export { default as DropdownMenuItem } from './DropdownMenuItem.vue'
export { default as DropdownMenuSeparator } from './DropdownMenuSeparator.vue'

View File

@@ -17,9 +17,17 @@ import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox' import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import FieldRenderer from '@/components/fields/FieldRenderer.vue' import FieldRenderer from '@/components/fields/FieldRenderer.vue'
import { ListViewConfig, ViewMode, FieldType, FieldConfig } from '@/types/field-types' import { ListViewConfig, ViewMode, FieldType, FieldConfig } from '@/types/field-types'
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit } from 'lucide-vue-next' import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit, Bookmark, BookmarkPlus, Settings2 } from 'lucide-vue-next'
import type { SavedView } from '@/composables/useSavedViews'
interface Props { interface Props {
config: ListViewConfig config: ListViewConfig
@@ -32,6 +40,11 @@ interface Props {
draftEdits?: Record<string, Record<string, any>> draftEdits?: Record<string, Record<string, any>>
cellErrors?: Record<string, Record<string, string | boolean>> cellErrors?: Record<string, Record<string, string | boolean>>
savingDrafts?: boolean savingDrafts?: boolean
// Saved views
savedViews?: SavedView[]
activeViewId?: string | null
currentSearchPlan?: { strategy: string; filters: any[]; sort: any; explanation: string } | null
savingView?: boolean
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
@@ -43,6 +56,10 @@ const props = withDefaults(defineProps<Props>(), {
draftEdits: () => ({}), draftEdits: () => ({}),
cellErrors: () => ({}), cellErrors: () => ({}),
savingDrafts: false, savingDrafts: false,
savedViews: () => [],
activeViewId: null,
currentSearchPlan: null,
savingView: false,
}) })
const emit = defineEmits<{ const emit = defineEmits<{
@@ -61,6 +78,10 @@ const emit = defineEmits<{
'cell-edit': [payload: { row: any; field: FieldConfig; newValue: any; oldValue: any }] 'cell-edit': [payload: { row: any; field: FieldConfig; newValue: any; oldValue: any }]
'save-drafts': [] 'save-drafts': []
'discard-drafts': [] 'discard-drafts': []
// Saved views
'apply-view': [view: SavedView]
'save-view': []
'open-view-manager': []
}>() }>()
// State // State
@@ -399,6 +420,66 @@ watch(
</div> </div>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<!-- Saved Views dropdown + cog -->
<div class="flex items-center gap-1">
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button variant="outline" size="sm" class="gap-2">
<Bookmark class="h-4 w-4" />
<span class="max-w-[120px] truncate">
{{ savedViews.find(v => v.id === activeViewId)?.name || 'Views' }}
</span>
<ChevronDown class="h-3 w-3 opacity-60" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" class="w-56">
<DropdownMenuItem
v-if="savedViews.length === 0"
disabled
class="text-muted-foreground"
>
No saved views yet
</DropdownMenuItem>
<DropdownMenuItem
v-for="view in savedViews"
:key="view.id"
:class="{ 'font-medium': view.id === activeViewId }"
@click="emit('apply-view', view)"
>
<span class="flex-1 truncate">{{ view.name }}</span>
<Badge v-if="view.isShared" variant="secondary" class="ml-2 text-[10px] px-1.5 py-0">Shared</Badge>
</DropdownMenuItem>
<DropdownMenuSeparator v-if="savedViews.length > 0" />
<DropdownMenuItem @click="emit('open-view-manager')">
Manage views
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="ghost"
size="icon"
class="h-8 w-8"
title="Manage saved views"
@click="emit('open-view-manager')"
>
<Settings2 class="h-4 w-4" />
</Button>
</div>
<!-- Save current search as a view (only for query strategy) -->
<Button
v-if="currentSearchPlan?.strategy === 'query'"
variant="outline"
size="sm"
:disabled="savingView"
class="gap-2"
@click="emit('save-view')"
>
<BookmarkPlus class="h-4 w-4" />
Save view
</Button>
<Select v-model="viewMode"> <Select v-model="viewMode">
<SelectTrigger class="h-8 w-[180px]"> <SelectTrigger class="h-8 w-[180px]">
<SelectValue placeholder="Select view" /> <SelectValue placeholder="Select view" />

View 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,
}
}

View File

@@ -4,9 +4,12 @@ import { useRoute, useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi' import { useApi } from '@/composables/useApi'
import { useFields, useViewState } from '@/composables/useFieldViews' import { useFields, useViewState } from '@/composables/useFieldViews'
import { usePageLayouts } from '@/composables/usePageLayouts' import { usePageLayouts } from '@/composables/usePageLayouts'
import { useSavedViews } from '@/composables/useSavedViews'
import type { SavedView } from '@/composables/useSavedViews'
import ListView from '@/components/views/ListView.vue' import ListView from '@/components/views/ListView.vue'
import DetailView from '@/components/views/DetailViewEnhanced.vue' import DetailView from '@/components/views/DetailViewEnhanced.vue'
import EditView from '@/components/views/EditViewEnhanced.vue' import EditView from '@/components/views/EditViewEnhanced.vue'
import SavedViewPanel from '@/components/SavedViewPanel.vue'
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -15,12 +18,23 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog' } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const { api } = useApi() const { api } = useApi()
const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields() const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields()
const { getDefaultPageLayout } = usePageLayouts() const { getDefaultPageLayout } = usePageLayouts()
const {
savedViews,
fetchSavedViews,
createSavedView,
updateSavedView,
deleteSavedView,
suggestViewName,
} = useSavedViews()
// Use breadcrumbs composable // Use breadcrumbs composable
const { setBreadcrumbs } = useBreadcrumbs() const { setBreadcrumbs } = useBreadcrumbs()
@@ -177,6 +191,16 @@ const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
const pendingDeleteCount = computed(() => pendingDeleteRows.value.length) const pendingDeleteCount = computed(() => pendingDeleteRows.value.length)
const deniedDeleteCount = computed(() => deleteSummary.value?.deniedIds.length ?? 0) const deniedDeleteCount = computed(() => deleteSummary.value?.deniedIds.length ?? 0)
// ── Saved views state ──────────────────────────────────────────────────────
const activeViewId = ref<string | null>(null)
const currentSearchPlan = ref<{
strategy: string; filters: any[]; sort: any; explanation: string
} | null>(null)
const viewPanelOpen = ref(false)
const saveViewDialogOpen = ref(false)
const saveViewName = ref('')
const savingView = ref(false)
// Fetch object definition // Fetch object definition
const fetchObjectDefinition = async () => { const fetchObjectDefinition = async () => {
try { try {
@@ -323,6 +347,19 @@ const searchListRecords = async (
records.value = options?.append ? [...records.value, ...data] : data records.value = options?.append ? [...records.value, ...data] : data
totalCount.value = total totalCount.value = total
searchSummary.value = response?.explanation || '' searchSummary.value = response?.explanation || ''
// Capture the plan for the "Save view" feature (only when strategy is query)
if (response?.strategy === 'query') {
currentSearchPlan.value = {
strategy: response.strategy,
filters: response.filters || [],
sort: response.sort || null,
explanation: response.explanation || '',
}
} else {
currentSearchPlan.value = null
}
return response return response
} catch (e: any) { } catch (e: any) {
error.value = e.message || 'Failed to search records' error.value = e.message || 'Failed to search records'
@@ -383,6 +420,8 @@ const handleSearch = async (query: string) => {
searchQuery.value = trimmed searchQuery.value = trimmed
if (!trimmed) { if (!trimmed) {
searchSummary.value = '' searchSummary.value = ''
currentSearchPlan.value = null
activeViewId.value = null
await initializeListRecords() await initializeListRecords()
return return
} }
@@ -499,6 +538,103 @@ const handleDiscardDrafts = () => {
cellErrors.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( watch(
() => records.value.map(record => normalizeRecordId(record.id)), () => records.value.map(record => normalizeRecordId(record.id)),
(ids) => { (ids) => {
@@ -547,6 +683,8 @@ onMounted(async () => {
if (view.value === 'list') { if (view.value === 'list') {
await initializeListRecords() await initializeListRecords()
// Load saved views for this object
fetchSavedViews(objectApiName.value).catch(() => {})
} else if (recordId.value && recordId.value !== 'new') { } else if (recordId.value && recordId.value !== 'new') {
await fetchRecord(recordId.value) await fetchRecord(recordId.value)
} }
@@ -598,6 +736,10 @@ onMounted(async () => {
:draft-edits="draftEdits" :draft-edits="draftEdits"
:cell-errors="cellErrors" :cell-errors="cellErrors"
:saving-drafts="savingDrafts" :saving-drafts="savingDrafts"
:saved-views="savedViews"
:active-view-id="activeViewId"
:current-search-plan="currentSearchPlan"
:saving-view="savingView"
selectable selectable
@row-click="handleRowClick" @row-click="handleRowClick"
@create="handleCreate" @create="handleCreate"
@@ -610,6 +752,9 @@ onMounted(async () => {
@cell-edit="handleCellEdit" @cell-edit="handleCellEdit"
@save-drafts="handleSaveDrafts" @save-drafts="handleSaveDrafts"
@discard-drafts="handleDiscardDrafts" @discard-drafts="handleDiscardDrafts"
@apply-view="handleApplyView"
@save-view="handleSaveView"
@open-view-manager="handleOpenViewManager"
/> />
<!-- Detail View --> <!-- Detail View -->
@@ -681,6 +826,46 @@ onMounted(async () => {
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<!-- Save view dialog -->
<Dialog v-model:open="saveViewDialogOpen">
<DialogContent class="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>Save view</DialogTitle>
<DialogDescription>
Give this search a name so you can reuse it later.
</DialogDescription>
</DialogHeader>
<div class="space-y-2 py-2">
<Label for="view-name">View name</Label>
<Input
id="view-name"
v-model="saveViewName"
placeholder="e.g. Cocker Spaniels"
@keyup.enter="confirmSaveView"
/>
</div>
<DialogFooter>
<Button variant="outline" @click="saveViewDialogOpen = false" :disabled="savingView">
Cancel
</Button>
<Button @click="confirmSaveView" :disabled="savingView || !saveViewName.trim()">
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<!-- Saved views slide-over panel -->
<SavedViewPanel
v-model:open="viewPanelOpen"
:views="savedViews"
:object-label="objectDefinition?.pluralLabel || objectDefinition?.label || objectApiName"
:active-view-id="activeViewId"
@apply-view="handleApplyView"
@update-view="handleUpdateView"
@delete-view="handleDeleteView"
/>
</NuxtLayout> </NuxtLayout>
</template> </template>

View File

@@ -33,6 +33,10 @@
<Label class="text-muted-foreground">Email</Label> <Label class="text-muted-foreground">Email</Label>
<p class="font-medium">{{ user?.email }}</p> <p class="font-medium">{{ user?.email }}</p>
</div> </div>
<div>
<Label class="text-muted-foreground">Alias</Label>
<p class="font-medium">{{ user?.alias || 'N/A' }}</p>
</div>
<div> <div>
<Label class="text-muted-foreground">First Name</Label> <Label class="text-muted-foreground">First Name</Label>
<p class="font-medium">{{ user?.firstName || 'N/A' }}</p> <p class="font-medium">{{ user?.firstName || 'N/A' }}</p>
@@ -210,6 +214,9 @@ const removeRole = async (roleId: string) => {
const getUserName = (user: any) => { const getUserName = (user: any) => {
if (!user) return 'User'; if (!user) return 'User';
if (user.alias) {
return user.alias;
}
if (user.firstName || user.lastName) { if (user.firstName || user.lastName) {
return [user.firstName, user.lastName].filter(Boolean).join(' '); return [user.firstName, user.lastName].filter(Boolean).join(' ');
} }

View File

@@ -95,6 +95,10 @@
<Label for="lastName">Last Name (Optional)</Label> <Label for="lastName">Last Name (Optional)</Label>
<Input id="lastName" v-model="newUser.lastName" placeholder="Doe" /> <Input id="lastName" v-model="newUser.lastName" placeholder="Doe" />
</div> </div>
<div class="space-y-2">
<Label for="alias">Alias (Optional)</Label>
<Input id="alias" v-model="newUser.alias" placeholder="Display name" />
</div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" @click="showCreateDialog = false">Cancel</Button> <Button variant="outline" @click="showCreateDialog = false">Cancel</Button>
@@ -131,6 +135,10 @@
<Label for="edit-lastName">Last Name</Label> <Label for="edit-lastName">Last Name</Label>
<Input id="edit-lastName" v-model="editUser.lastName" placeholder="Doe" /> <Input id="edit-lastName" v-model="editUser.lastName" placeholder="Doe" />
</div> </div>
<div class="space-y-2">
<Label for="edit-alias">Alias</Label>
<Input id="edit-alias" v-model="editUser.alias" placeholder="Display name" />
</div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" @click="showEditDialog = false">Cancel</Button> <Button variant="outline" @click="showEditDialog = false">Cancel</Button>
@@ -187,6 +195,7 @@ const newUser = ref({
password: '', password: '',
firstName: '', firstName: '',
lastName: '', lastName: '',
alias: '',
}); });
const editUser = ref({ const editUser = ref({
id: '', id: '',
@@ -194,6 +203,7 @@ const editUser = ref({
password: '', password: '',
firstName: '', firstName: '',
lastName: '', lastName: '',
alias: '',
}); });
const userToDelete = ref<any>(null); const userToDelete = ref<any>(null);
@@ -215,7 +225,7 @@ const createUser = async () => {
await api.post('/setup/users', newUser.value); await api.post('/setup/users', newUser.value);
toast.success('User created successfully'); toast.success('User created successfully');
showCreateDialog.value = false; showCreateDialog.value = false;
newUser.value = { email: '', password: '', firstName: '', lastName: '' }; newUser.value = { email: '', password: '', firstName: '', lastName: '', alias: '' };
await loadUsers(); await loadUsers();
} catch (error: any) { } catch (error: any) {
console.error('Failed to create user:', error); console.error('Failed to create user:', error);
@@ -230,6 +240,7 @@ const openEditDialog = (user: any) => {
password: '', password: '',
firstName: user.firstName || '', firstName: user.firstName || '',
lastName: user.lastName || '', lastName: user.lastName || '',
alias: user.alias || '',
}; };
showEditDialog.value = true; showEditDialog.value = true;
}; };
@@ -240,6 +251,7 @@ const updateUser = async () => {
email: editUser.value.email, email: editUser.value.email,
firstName: editUser.value.firstName, firstName: editUser.value.firstName,
lastName: editUser.value.lastName, lastName: editUser.value.lastName,
alias: editUser.value.alias,
}; };
if (editUser.value.password) { if (editUser.value.password) {
payload.password = editUser.value.password; payload.password = editUser.value.password;
@@ -273,6 +285,9 @@ const deleteUser = async () => {
}; };
const getUserName = (user: any) => { const getUserName = (user: any) => {
if (user.alias) {
return user.alias;
}
if (user.firstName || user.lastName) { if (user.firstName || user.lastName) {
return [user.firstName, user.lastName].filter(Boolean).join(' '); return [user.firstName, user.lastName].filter(Boolean).join(' ');
} }