From cf19bb8bf942c50cb41dfa06586ad0d7558fdb69 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Tue, 17 Nov 2026 10:36:22 +0200 Subject: [PATCH] feat: AI assistant for reporting: Configure with AI in the report template list and page with PDF/CSV badges on template cards, labels, action details and review fields for the report template, scheduled report and report tools, records linking to Reports and Scheduling, welcome examples on the Scheduling and Reports pages, generated files download on click, and the report tables reload after the assistant's changes --- .../ai/ai-action-detail.component.html | 2 +- .../components/ai/ai-action-detail.models.ts | 178 ++++++++++++- .../components/ai/ai-action-line.component.ts | 5 +- .../home/components/ai/ai-action.models.ts | 26 +- .../ai/ai-approval-card.component.html | 2 +- .../ai/ai-approval-card.component.ts | 7 +- .../ai/ai-chat-messages.component.ts | 33 ++- .../home/components/ai/ai-chat.component.ts | 21 +- .../home/components/ai/ai-file.models.ts | 16 +- .../components/ai/ai-record-card.component.ts | 3 + .../components/ai/ai-record-loader.service.ts | 24 ++ .../home/components/ai/ai-record.component.ts | 5 + .../home/components/ai/ai-record.models.ts | 1 + .../components/ai/ai-records.component.ts | 2 +- .../components/ai/ai-run-summary.component.ts | 4 +- .../home/components/ai/ai-welcome.models.ts | 6 +- .../report-template-page.component.ts | 81 +++++- .../report-templates-table-config.resolver.ts | 45 +++- .../src/app/shared/models/ai-chat.models.ts | 7 + .../assets/locale/locale.constant-en_US.json | 248 ++++++++++++++++++ ui-ngx/src/theme/ai-theme.scss | 67 ++++- 21 files changed, 742 insertions(+), 41 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html index 6ccc83afcf..415aaa3157 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -12,7 +12,7 @@ @case ('hub') {
@for (rec of shown(hub(), 'hub'); track rec.key) { - } @if (hub().length > LIST_SHOWN) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts index bb4d2b1ac2..1f1f94e23a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -545,6 +545,78 @@ function aliasFilter(filter: unknown, names: AiDetailNames): AiDetailFact[] { return rows; } +function reportTemplateOverview(result: Values): AiDetailBlock[] { + const blocks: AiDetailBlock[] = []; + const settings = isObject(result.settings) ? result.settings : {}; + const page = isObject(settings.page) ? settings.page : null; + const rows: AiDetailFact[] = [{label: K + 'fact.format', value: [str(result.format), result.templateType === 'SUB_REPORT' ? text('sub-report') : null].filter(Boolean).join(' · ')}]; + if (page) { + rows.push({label: K + 'fact.page', value: [page.size, aiHumanize(String(page.orientation ?? ''))].filter(Boolean).join(' · ')}); + } + if (str(settings.fileName)) { + rows.push({label: K + 'fact.file-name', value: settings.fileName, mono: true}); + } + const sections = ['header', 'footer'].filter(section => isObject(settings[section]) && settings[section].enabled); + if (page) { + rows.push({label: K + 'fact.header-footer', value: sections.length ? sections.map(section => aiHumanize(section)).join(', ') : '—'}); + } + blocks.push({type: 'facts', rows}); + const components = isObject(result.components) ? Object.entries(result.components) : []; + blocks.push({ + type: 'list', label: text('report-components'), + rows: components.length ? components.slice(0, MAX_ROWS).map(([path, line]) => { + const item = isObject(line) ? line : {}; + return [path, aiHumanize(String(item.type ?? '')), str(item.is), str(item.alias)].filter(Boolean).join(' · '); + }) : ['—'] + }); + const aliases = (Array.isArray(result.entityAliases) ? result.entityAliases : []).filter(isObject); + if (aliases.length) { + blocks.push({type: 'list', label: text('aliases'), rows: aliases.map(alias => [str(alias.name) ?? alias.id, alias.filter?.type ? aiHumanize(alias.filter.type) : null].filter(Boolean).join(' · '))}); + } + const filters = (Array.isArray(result.filters) ? result.filters : []).filter(isObject); + if (filters.length) { + blocks.push({type: 'list', label: text('filters'), rows: filters.map(item => String(item.name ?? item.id))}); + } + const problems = (Array.isArray(result.problems) ? result.problems : []).map(String); + if (problems.length) { + blocks.push({type: 'list', label: text('report-problems'), rows: problems}); + } + return blocks; +} + +function reportComponentFacts(component: Values): AiDetailFact[] { + const rows: AiDetailFact[] = [{label: K + 'fact.component', value: aiHumanize(String(component.type ?? ''))}]; + rows.push({label: K + 'fact.path', value: String(component.path ?? '—'), mono: true}); + const config = isObject(component.config) ? component.config : {}; + const title = str(config.title) ?? str(config.text); + if (title) { + rows.push({label: K + 'fact.title', value: title}); + } + if (str(component.entityAlias) || str(component.entityAliasId)) { + rows.push(str(component.entityAlias) ? {label: K + 'fact.alias', value: component.entityAlias} + : {label: K + 'fact.alias', value: component.entityAliasId, mono: true}); + } + const entries = [config.keys, config.columns, config.series, config.latestColumns].filter(Array.isArray).flat(); + const keys = entries.map((item: any) => typeof item === 'string' ? item : item?.key).filter(Boolean); + if (str(config.key)) { + keys.push(config.key); + } + if (keys.length) { + rows.push({label: K + 'fact.keys', value: [...new Set(keys)].join(', '), mono: true}); + } + const history = isObject(config.timewindow) && isObject(config.timewindow.history) ? config.timewindow.history : null; + if (history) { + const window = history.interval ?? history.last ?? (isObject(history.range) ? `${history.range.from} – ${history.range.to}` : null); + const aggregation = isObject(config.timewindow.aggregation) && config.timewindow.aggregation.type && config.timewindow.aggregation.type !== 'NONE' + ? `${config.timewindow.aggregation.type}${config.timewindow.aggregation.grouping ? ' per ' + config.timewindow.aggregation.grouping : ''}` : null; + rows.push({label: K + 'fact.time-window', value: [window ? aiHumanize(String(window)) : null, aggregation].filter(Boolean).join(' · ')}); + } + if (typeof config.height === 'number') { + rows.push({label: K + 'fact.height', value: `${config.height} px`}); + } + return rows; +} + function widgetFacts(widget: Values, names: AiDetailNames): AiDetailFact[] { const rows: AiDetailFact[] = []; if (str(widget.title)) { @@ -1304,7 +1376,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail blocks.push({type: 'list', label: text('mobile-bundle-menu', {name: str(bundle.title) ?? '—'}), rows: pages}); } if (isObject(result.qrCode)) { - blocks.push(...json('QR code', result.qrCode)); + blocks.push(...json('qr-code', result.qrCode)); } return {hood: text('read-mobile-center'), blocks}; } @@ -1340,7 +1412,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail return {hood: text('read-scheduler-event', {name: str(result.name) ?? '—'}), blocks: json('event', result)}; } case 'read_mail_server': - return {hood: text('read-mail-server'), blocks: json('mail server', result)}; + return {hood: text('read-mail-server'), blocks: json('mail-server', result)}; case 'save_mail_server': { const rows = facts(values); return {hood: text('save-mail-server'), blocks: rows.length ? [{type: 'facts', rows}] : []}; @@ -1367,6 +1439,108 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail const rows = facts(values); return {hood: text('save-two-factor-settings'), blocks: rows.length ? [{type: 'facts', rows}] : []}; } + case 'create_report_template': + case 'update_report_template': { + const rows = facts(values, ['templateId']); + return {hood: tool === 'create_report_template' ? text('create-report-template', {name: str(values.name) ?? '—'}) : text('update-report-template'), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_report_template': { + if (!isObject(result)) { + return {hood: text(str(values.path) ? 'read-report-component' : 'read-report-template', {path: str(values.path) ?? '—', name: '—'}), blocks: generic(result, 'result')}; + } + if (str(values.path)) { + return {hood: text('read-report-component', {path: str(result.path) ?? str(values.path), name: str(result.template) ?? '—'}), + blocks: [{type: 'facts', rows: reportComponentFacts(result)}]}; + } + return {hood: text('read-report-template', {name: str(result.name) ?? '—'}), blocks: reportTemplateOverview(result)}; + } + case 'add_report_components': { + const rows = (Array.isArray(values.components) ? values.components.filter(isObject) : []).slice(0, MAX_ROWS).map(component => { + const config = isObject(component.config) ? component.config : {}; + const title = str(config.title) ?? str(config.text); + return [str(component.in), aiHumanize(String(component.type)), title].filter(Boolean).join(' · '); + }); + return {hood: text('add-report-components'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + case 'update_report_component': { + const rows = facts(isObject(values.config) ? values.config as Values : {}); + return {hood: text('update-report-component', {path: str(values.path) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'move_report_component': + return {hood: text('move-report-component', {path: str(values.path) ?? '—', target: str(values.in) ?? '—'}), blocks: []}; + case 'save_report_entity_alias': + case 'save_report_filter': { + const rows = facts(values, ['templateId', 'aliasId', 'filterId']); + return {hood: text(tool === 'save_report_filter' ? 'save-report-filter' : 'save-report-alias', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'test_report_template': { + if (!isObject(result)) { + return {hood: text('test-report-template'), blocks: generic(result, 'result')}; + } + const errors = (Array.isArray(result.errors) ? result.errors.filter(isObject) : []) + .map(error => [error.page !== undefined ? `p. ${error.page}` : error.row !== undefined ? `row ${error.row}` : undefined, str(error.message)] + .filter(Boolean).join(' · ')); + const pdf = result.pages !== undefined; + const count = Number(pdf ? result.pages : result.rows ?? 0); + const size = text((pdf ? 'report-pages' : 'report-rows') + (errors.length ? '' : '-clean'), {count}); + return {hood: text('test-report-template'), + blocks: [{type: 'note', text: size}, + ...(errors.length ? [{type: 'list' as const, label: text('report-errors'), rows: errors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'read_reports': { + if (!isObject(result)) { + return {hood: text('read-reports'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.templates)) { + const rows = result.templates.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.format, item.templateType === 'SUB_REPORT' ? 'Sub-report' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-report-templates'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-report-templates')}]}; + } + if (Array.isArray(result.scheduledReports)) { + const rows = result.scheduledReports.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.template, item.schedule, item.enabled === false ? '⏸' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scheduled-reports'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scheduled-reports')}]}; + } + if (Array.isArray(result.reports)) { + const rows = result.reports.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.file, item.template, item.generated].filter(Boolean).join(' · ')); + return {hood: text('read-generated-reports'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-generated-reports')}]}; + } + if (isObject(result.file)) { + return {hood: text('attach-report', {name: str(result.file.name) ?? '—'}), blocks: []}; + } + const rows = facts(result, ['eventId', 'templateId', 'rawSchedule', 'recipients', 'notificationTemplate', 'name']); + const recipients = Array.isArray(result.recipients) ? result.recipients.filter(isObject).map(item => str(item.name)).filter(Boolean) : []; + if (recipients.length) { + rows.push({label: aiHumanize('recipients'), raw: true, value: recipients.join(', ')}); + } + return {hood: text('read-scheduled-report', {name: str(result.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_scheduled_report': { + const rows = facts(values, ['eventId', 'templateId', 'userId', 'recipientIds', 'notificationTemplateId']); + return {hood: str(values.eventId) ? text('save-scheduled-report') : text('create-scheduled-report', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'generate_report': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + if (!isObject(raw)) { + return {hood: text('generate-report'), blocks: generic(raw, 'result')}; + } + const name = isObject(raw.file) ? str(raw.file.name) : str(raw.file); + const rows: AiDetailFact[] = []; + if (name) { + rows.push({label: aiHumanize('file'), raw: true, value: name}); + } + if (str(raw.sentTo)) { + rows.push({label: aiHumanize('sent to'), raw: true, value: str(raw.sentTo)}); + } + return {hood: text('generate-report'), blocks: rows.length ? [{type: 'facts', rows}] : [{type: 'note', text: text('report-still-running')}]}; + } case 'save_scheduler_event': { const rows = facts(values, ['eventId']); return {hood: str(values.eventId) ? text('save-scheduler-event') : text('create-scheduler-event', {name: str(values.name) ?? '—'}), diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts index 5e6347ebdb..7cdac1a95d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -75,16 +75,17 @@ export class AiActionLineComponent { ? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) ?? affected[0] : affected[0]; const text = this.outcome(); - const match = entity && this.action().status === 'SUCCESS' ? /'([^']{1,120})'/.exec(text) : null; + const match = entity && this.action().status === 'SUCCESS' ? /(?:^|\s)'(.{1,120}?)'(?=$|[\s.,:;!?)])/.exec(text) : null; if (!match) { return null; } + const start = match.index + match[0].indexOf('\''); const alarmRule = entity.entityType === EntityType.CALCULATED_FIELD && this.isAlarmRule(); const kind = aiEntityKind(entity.entityType, alarmRule); const base = alarmRule ? '/alarms/alarm-rules' : baseDetailsPageByEntityType.get(entity.entityType as EntityType); const groupUrl = entity.entityType === EntityType.ENTITY_GROUP ? this.groupView()?.url : undefined; return { - before: text.slice(0, match.index), + before: text.slice(0, start), name: match[1], after: text.slice(match.index + match[0].length), icon: kind.icon, diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index 58b75bc64f..a25217e0bb 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -82,6 +82,17 @@ const TOOL_WORDS: Record = { save_mobile_qr_code: 'save-mobile-qr-code', read_scheduler_events: 'read-scheduler-events', save_scheduler_event: 'save-scheduler-event', + create_report_template: 'create-report-template', + update_report_template: 'update-report-template', + add_report_components: 'add-report-components', + update_report_component: 'update-report-component', + move_report_component: 'move-report-component', + save_report_entity_alias: 'save-report-alias', + save_report_filter: 'save-report-filter', + test_report_template: 'test-report-template', + read_reports: 'read-reports', + save_scheduled_report: 'save-scheduled-report', + generate_report: 'generate-report', save_two_factor_settings: 'save-two-factor-settings', save_oauth2_domain: 'save-oauth2-domain', read_my_account: 'read-my-account', @@ -169,7 +180,12 @@ const DELETED_TARGETS: Record = { CUSTOM_MENU: 'delete-custom-menu', MOBILE_APP: 'delete-mobile-app', MOBILE_BUNDLE: 'delete-mobile-bundle', - SCHEDULER_EVENT: 'delete-scheduler-event' + SCHEDULER_EVENT: 'delete-scheduler-event', + REPORT_TEMPLATE: 'delete-report-template', + REPORT_COMPONENT: 'delete-report-component', + REPORT_ENTITY_ALIAS: 'delete-report-alias', + REPORT_FILTER: 'delete-report-filter', + REPORT: 'delete-report' }; const ACTION_PREFIX = 'ai-assistant.action.'; @@ -346,6 +362,8 @@ export function aiActionWords(tool: string, args: unknown): AiActionWords { switch (tool) { case 'add_dashboard_widgets': return {key: ACTION_PREFIX + (Array.isArray(values.widgets) && values.widgets.length === 1 ? 'add-widget' : 'add-widgets'), kind: 'think'}; + case 'read_report_template': + return {key: ACTION_PREFIX + (typeof values.path === 'string' && values.path ? 'read-report-component' : 'read-report-template'), kind: 'think'}; case 'search_entities': return {key: ACTION_PREFIX + searchedWords(values), kind: 'think'}; case 'update_alarms': @@ -488,6 +506,12 @@ const ENTITY_KINDS: Record = { MOBILE_BUNDLE: {icon: 'phonelink_setup', palette: 'device'}, MOBILE_QR_CODE: {icon: 'qr_code_2', palette: 'device'}, SCHEDULER_EVENT: {icon: 'schedule', palette: 'rule'}, + REPORT_TEMPLATE: {icon: 'description', palette: 'view'}, + REPORT_COMPONENT: {icon: 'view_agenda', palette: 'view'}, + REPORT_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + REPORT_FILTER: {icon: 'filter_list', palette: 'view'}, + SCHEDULED_REPORT: {icon: 'event_repeat', palette: 'rule'}, + REPORT: {icon: 'summarize', palette: 'view'}, TWO_FACTOR_SETTINGS: {icon: 'phonelink_lock', palette: 'people'}, DOMAIN: {icon: 'language', palette: 'people'}, MY_PROFILE: {icon: 'account_circle', palette: 'people'}, diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index fdedffcd95..36eedd50bb 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -35,7 +35,7 @@ } @if (changes.length) { - +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index 7be0a742ce..4f43876bbc 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -52,7 +52,8 @@ const VALUE_TOKENS: Record = { const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); -const OWN_TYPE_LABELS = new Set(['DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER', 'NOTIFICATION', 'NOTIFICATION_SETTINGS', 'NOTIFICATION_PREFERENCES', 'IMAGE', 'PLATFORM_SETTINGS', 'RELATION', 'VERSION', 'WHITE_LABELING', 'MAIL_TEMPLATE', 'CUSTOM_TRANSLATION', 'CUSTOM_MENU', 'MOBILE_APP', 'MOBILE_BUNDLE', 'MOBILE_QR_CODE', 'TWO_FACTOR_SETTINGS', 'MY_PROFILE', 'MY_TWO_FACTOR', 'MAIL_SERVER']); +const STACK_AT = 24; +const OWN_TYPE_LABELS = new Set(['DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER', 'NOTIFICATION', 'NOTIFICATION_SETTINGS', 'NOTIFICATION_PREFERENCES', 'IMAGE', 'PLATFORM_SETTINGS', 'RELATION', 'VERSION', 'WHITE_LABELING', 'MAIL_TEMPLATE', 'CUSTOM_TRANSLATION', 'CUSTOM_MENU', 'MOBILE_APP', 'MOBILE_BUNDLE', 'MOBILE_QR_CODE', 'TWO_FACTOR_SETTINGS', 'MY_PROFILE', 'MY_TWO_FACTOR', 'MAIL_SERVER', 'REPORT_COMPONENT', 'REPORT_ENTITY_ALIAS', 'REPORT_FILTER', 'SCHEDULED_REPORT']); const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); @@ -234,6 +235,10 @@ export class AiApprovalCardComponent implements OnChanges { ]; } + get stackedDiff(): boolean { + return this.changes.some(change => (change.current?.length ?? 0) > STACK_AT || (change.value?.length ?? 0) > STACK_AT); + } + get changes(): AiReviewRow[] { return this.rows('CHANGE'); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index 88b07b7092..f790429c94 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts @@ -37,7 +37,7 @@ import { AiPlanRun } from '@home/components/ai/ai-plan.component'; import { aiRecordKey, AiShownRecords, aiShownRecordsOf, SHOW_RECORDS_TOOL } from '@home/components/ai/ai-record.models'; import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; import { decorateSections } from '@home/components/ai/ai-disclosure.component'; -import { AiFile, aiFileMark, aiFileName, aiFileOf, AiMadeFile, aiMadeFileOf, CREATE_FILE_TOOL, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models'; +import { AiFile, aiFileMark, aiFileName, aiFileOf, AiMadeFile, aiMadeFileOf, FILE_MAKING_TOOLS, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models'; import { MatDialog } from '@angular/material/dialog'; import { AiResourceService } from '@core/http/ai-resource.service'; import { @@ -133,6 +133,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { streaming = false; files: Record = {}; madeFiles: Record = {}; + private handledMadeFiles = new Set(); quotes: Record = {}; sources: Record = {}; @@ -183,26 +184,23 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { maxWidth: '92vw', data: {resource: file.resource} }); - } else if (file.preview === 'pdf') { - const tab = window.open('', '_blank'); - this.aiResourceService.getUrl(file.resource.id).subscribe({ - next: url => { - if (tab) { - tab.location.href = url; - } else { - window.open(url, '_blank'); - } - }, - error: error => { - tab?.close(); - this.resourceError.emit(error); - } - }); } else { this.downloadMadeFile(file); } } + private downloadRequestedFiles(): void { + for (const file of Object.values(this.madeFiles)) { + if (this.handledMadeFiles.has(file.executionId)) { + continue; + } + this.handledMadeFiles.add(file.executionId); + if (file.download && this.loading) { + this.downloadMadeFile(file); + } + } + } + downloadMadeFile(file: AiMadeFile): void { this.aiResourceService.download(file.resource).subscribe({ error: error => this.resourceError.emit(error) @@ -400,6 +398,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { this.files = this.findFiles(); this.latestFiles = new Map(Object.values(this.files).map(file => [file.name, file])); this.madeFiles = this.findMadeFiles(); + this.downloadRequestedFiles(); this.quotes = this.findQuotes(); this.sources = this.findSources(); this.records = this.findRecords(); @@ -780,7 +779,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { private findMadeFiles(): Record { const files: Record = {}; this.messages.forEach((message, index) => { - if (message.from === 'ACTION' && message.data.tool === CREATE_FILE_TOOL && message.data.status === 'SUCCESS') { + if (message.from === 'ACTION' && FILE_MAKING_TOOLS.has(message.data.tool) && message.data.status === 'SUCCESS') { const file = aiMadeFileOf(message.data.executionId, message.data.result); if (file) { files[index] = file; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 3478451950..eff5b7f212 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -69,11 +69,14 @@ import { ClipboardService } from 'ngx-clipboard'; import { AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component'; import { EntityId } from '@shared/models/id/entity-id'; import { EntityType } from '@shared/models/entity-type.models'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; export type AiChatVariant = 'page' | 'panel'; +const LIVE_EDITED_TYPES = new Set([EntityType.DASHBOARD, EntityType.REPORT_TEMPLATE]); + @Component({ selector: 'tb-ai-chat', templateUrl: './ai-chat.component.html', @@ -968,6 +971,7 @@ export class AiChatComponent implements OnInit, OnDestroy { && message.data.executionId === event.data.executionId); if (call?.from === 'APPROVAL' || call?.from === 'ACTION') { this.applySideEffects(event.data.executionId, call.data.tool, call.data.arguments); + this.openCreatedReportTemplate(call.data.tool, event.data.affectedEntities); } } if (event.data.affectedEntities?.length) { @@ -1051,10 +1055,21 @@ export class AiChatComponent implements OnInit, OnDestroy { this.messages.update(list => [...list, {from: 'ACTION', data: action}]); } + private openCreatedReportTemplate(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.REPORT_TEMPLATE); + if (tool !== 'create_report_template' || !created || !chatId + || this.panelService.clientContext()?.view?.type !== AiAssistantViewType.REPORT_TEMPLATE_LIST) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/reporting/templates', created.id]); + } + private emitDashboards(entities: EntityId[]): void { - const dashboards = entities.filter(entity => entity.entityType === EntityType.DASHBOARD); - if (dashboards.length) { - this.panelService.emitUpdatedData(dashboards); + const edited = entities.filter(entity => LIVE_EDITED_TYPES.has(entity.entityType as EntityType)); + if (edited.length) { + this.panelService.emitUpdatedData(edited); } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts index c60fb1d11c..b5cda81c83 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts @@ -5,6 +5,7 @@ import { AiResourceInfo } from '@shared/models/ai-chat.models'; export const WRITE_FILE_TOOL = 'write_file'; export const CREATE_FILE_TOOL = 'create_file'; +export const FILE_MAKING_TOOLS = new Set([CREATE_FILE_TOOL, 'test_report_template', 'generate_report', 'read_reports']); export interface AiMadeFile { executionId: string; @@ -12,12 +13,14 @@ export interface AiMadeFile { label: string; icon: string; size: string; - preview: 'image' | 'pdf' | null; + preview: 'image' | null; + download: boolean; } -const MADE_KINDS: Record = { +const MADE_KINDS: Record = { 'image/png': {label: 'PNG', icon: 'image', preview: 'image'}, - 'application/pdf': {label: 'PDF', icon: 'picture_as_pdf', preview: 'pdf'}, + 'application/pdf': {label: 'PDF', icon: 'picture_as_pdf', preview: null}, + 'text/csv': {label: 'CSV', icon: 'table_chart', preview: null}, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {label: 'Word', icon: 'description', preview: null}, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {label: 'Excel', icon: 'table_chart', preview: null} }; @@ -25,13 +28,15 @@ const MADE_KINDS: Record})?.file; + const download = (parsed as {download?: unknown})?.download === true; if (!file || typeof file.id !== 'string' || typeof file.name !== 'string' || typeof file.mediaType !== 'string') { return null; } @@ -43,7 +48,8 @@ export function aiMadeFileOf(executionId: string, result: unknown): AiMadeFile | label: kind.label, icon: kind.icon, size: formatSize(bytes), - preview: kind.preview + preview: kind.preview, + download }; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts index 010c8617ff..5c2820c97d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -56,6 +56,9 @@ export function aiDashboardThumb(cards: number): string { } @else { {{ rec.name }} } + @if (rec.badge) { + {{ rec.badge }} + } @if (rec.hub; as listing) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts index 9f2787941c..1222b4d257 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +import { ReportTemplateService } from '@core/http/report-template.service'; +import { ReportTemplateType } from '@shared/models/report.models'; import { inject, Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { forkJoin, Observable, of } from 'rxjs'; @@ -65,6 +67,7 @@ export class AiRecordLoaderService { private iotHubApi = inject(IotHubApiService); private translate = inject(TranslateService); private http = inject(HttpClient); + private reportTemplateService = inject(ReportTemplateService); loadAll(refs: AiRecordRef[], options: AiRecordLoadOptions = {}): Observable { if (!refs.length) { @@ -174,6 +177,27 @@ export class AiRecordLoaderService { case EntityType.NOTIFICATION_TEMPLATE: return this.notificationService.getNotificationTemplateById(entity.id, CONFIG) .pipe(map(template => this.simple(key, entityType, template.name, NOTIFICATION_PAGES[entityType]))); + case EntityType.REPORT_TEMPLATE: + return this.reportTemplateService.getReportTemplateInfo(entity.id, CONFIG).pipe(map(template => ({ + key, entityType, alarmRule: false, name: template.name, url: `/reporting/templates/${entity.id}`, + badge: template.format, + meta: this.translate.instant(template.type === ReportTemplateType.SUB_REPORT ? 'ai-assistant.record.sub-report' : 'ai-assistant.record.report') + }))); + case EntityType.REPORT: + return this.http.get<{name: string; format?: string; templateInfo?: {name?: string}}>(`/api/v2/report/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(report => ({ + key, entityType, alarmRule: false, name: report.name, url: '/reporting/reports', badge: report.format, + meta: report.templateInfo?.name + }))); + case EntityType.SCHEDULER_EVENT: + return this.http.get<{name: string; type?: string}>(`/api/schedulerEvent/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(event => { + const report = event.type === 'generateReport' || event.type === 'generateDashboardReport'; + return { + key, entityType, alarmRule: false, name: event.name, url: report ? '/reporting/scheduling' : url, + meta: report ? this.translate.instant('ai-assistant.record.scheduled-report') : undefined + }; + })); default: return this.entityService.getEntity(entityType, entity.id, CONFIG).pipe(map(found => { const view = this.simple(key, entityType, found?.name ?? (found as {title?: string})?.title, NOTIFICATION_PAGES[entityType] ?? url); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts index dc600c3c8f..2cf61962a7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts @@ -15,6 +15,9 @@ export { AiRecordState } from '@home/components/ai/ai-record.models'; } @else { {{ name() }} } + @if (badge(); as label) { + {{ label }} + } @if (hub(); as listing) { @@ -52,6 +55,8 @@ export class AiRecordComponent { meta = input(); + badge = input(); + url = input(); state = input(); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts index 7dc77d91b7..b714aef730 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts @@ -36,6 +36,7 @@ export interface AiRecordView { alarmRule: boolean; name: string; meta: string; + badge?: string; url?: string; state?: AiRecordState; alarm?: AiAlarmState; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts index 8163f5b5ca..4107ed8a6a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts @@ -33,7 +33,7 @@ const TARGETED_HUB_TYPES = new Set([ItemType.CALCULATED_FIELD, ItemType.
@for (rec of shownViews(); track rec.key) { } @if (views().length > LIST_SHOWN) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts index ec2a7eeda5..77d4a6d1e1 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts @@ -27,7 +27,7 @@ import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.serv
@for (row of shownRows(); track row.key) { + [meta]="row.meta" [badge]="row.badge" [url]="row.url" [state]="row.state" [alarm]="row.alarm"> } @if (rest().length > LIST_SHOWN) {