WIP - saving list views
This commit is contained in:
@@ -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');
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -688,6 +688,8 @@ export class AiAssistantService {
|
||||
totalCount: meiliResults.total ?? records.totalCount ?? 0,
|
||||
strategy: plan.strategy,
|
||||
explanation: plan.explanation,
|
||||
filters: [],
|
||||
sort: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -702,6 +704,8 @@ export class AiAssistantService {
|
||||
...fallback,
|
||||
strategy: plan.strategy,
|
||||
explanation: plan.explanation,
|
||||
filters: [],
|
||||
sort: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -730,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
|
||||
// ============================================
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
57
backend/src/saved-list-view/dto/saved-list-view.dto.ts
Normal file
57
backend/src/saved-list-view/dto/saved-list-view.dto.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { IsString, IsNotEmpty, IsArray, IsOptional, IsBoolean } 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()
|
||||
@IsBoolean()
|
||||
isShared?: boolean;
|
||||
|
||||
@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;
|
||||
}
|
||||
58
backend/src/saved-list-view/saved-list-view.controller.ts
Normal file
58
backend/src/saved-list-view/saved-list-view.controller.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Patch,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { TenantId } from '../tenant/tenant.decorator';
|
||||
import { SavedListViewService } from './saved-list-view.service';
|
||||
import { CreateSavedViewDto, UpdateSavedViewDto } from './dto/saved-list-view.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);
|
||||
}
|
||||
}
|
||||
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 {}
|
||||
107
backend/src/saved-list-view/saved-list-view.service.ts
Normal file
107
backend/src/saved-list-view/saved-list-view.service.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
|
||||
import { TenantDatabaseService } from '../tenant/tenant-database.service';
|
||||
import { CreateSavedViewDto, UpdateSavedViewDto } from './dto/saved-list-view.dto';
|
||||
|
||||
@Injectable()
|
||||
export class SavedListViewService {
|
||||
constructor(private readonly tenantDbService: TenantDatabaseService) {}
|
||||
|
||||
/**
|
||||
* Returns all saved views visible to the user for a given object:
|
||||
* - Views owned by the user (private or shared)
|
||||
* - Views owned by other users that are shared with the tenant
|
||||
*/
|
||||
async findByObject(tenantId: string, userId: string, objectApiName: string) {
|
||||
const resolvedTenantId = await this.tenantDbService.resolveTenantId(tenantId);
|
||||
const knex = await this.tenantDbService.getTenantKnexById(resolvedTenantId);
|
||||
|
||||
const rows = await knex('saved_list_views')
|
||||
.where({ object_api_name: objectApiName })
|
||||
.andWhere(function () {
|
||||
this.where({ user_id: userId }).orWhere({ is_shared: true });
|
||||
})
|
||||
.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);
|
||||
|
||||
// MySQL Knex returns [0] for UUID PKs (not auto-increment), so generate the
|
||||
// UUID in application code and use it directly for the subsequent fetch.
|
||||
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.isShared !== undefined) updates.is_shared = dto.isShared;
|
||||
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');
|
||||
}
|
||||
|
||||
await knex('saved_list_views').where({ id }).delete();
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
206
frontend/components/SavedViewPanel.vue
Normal file
206
frontend/components/SavedViewPanel.vue
Normal file
@@ -0,0 +1,206 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } 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 { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Pencil, Trash2, Users, Check, X } 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)
|
||||
|
||||
const ownViews = computed(() => props.views.filter(v => v.isOwner))
|
||||
const sharedViews = computed(() => props.views.filter(v => !v.isOwner && v.isShared))
|
||||
|
||||
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 toggleShare(view: SavedView) {
|
||||
emit('update-view', view.id, { isShared: !view.isShared })
|
||||
}
|
||||
|
||||
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-[480px] overflow-y-auto">
|
||||
<SheetHeader class="mb-4">
|
||||
<SheetTitle>{{ objectLabel }} — Saved Views</SheetTitle>
|
||||
<SheetDescription>
|
||||
Manage your saved searches. Shared views are visible to all users in 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>
|
||||
|
||||
<!-- Shared badge -->
|
||||
<Badge v-if="view.isShared" variant="secondary" class="text-[10px] px-1.5 py-0">
|
||||
<Users class="h-3 w-3 mr-1" />Shared
|
||||
</Badge>
|
||||
|
||||
<!-- 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="view.isShared ? 'Unshare' : 'Share with team'"
|
||||
@click="toggleShare(view)"
|
||||
>
|
||||
<Users class="h-3 w-3" :class="{ 'text-primary': view.isShared }" />
|
||||
</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 tooltip -->
|
||||
<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>
|
||||
</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" />
|
||||
|
||||
108
frontend/composables/useSavedViews.ts
Normal file
108
frontend/composables/useSavedViews.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
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
|
||||
isShared?: boolean
|
||||
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