refactor(ai): extract assistant into an official module (#749)

* feat(modules): expose host data boundaries

* feat(modules): add frontend extension surfaces

* refactor(ai): remove assistant from core

* chore(ai): prepare the module extraction

* fix(modules): load extension styles after the host bundle

* chore(modules): lock SDK 3.3.0
This commit is contained in:
Darko Gjorgjijoski
2026-08-05 22:10:21 +02:00
committed by GitHub
parent 99ae7def75
commit 0b9ae9ea00
111 changed files with 1137 additions and 8952 deletions
+27 -7
View File
@@ -3,18 +3,37 @@ import type { App } from 'vue'
import type { Router } from 'vue-router'
import App_ from './App.vue'
import router from './router'
import { createAppI18n, setI18nLanguage } from './plugins/i18n'
import { createAppI18n, mergeMessageObjects, setI18nLanguage } from './plugins/i18n'
import type { AppI18n } from './plugins/i18n'
import { createAppPinia } from './plugins/pinia'
import { installTooltipDirective } from './plugins/tooltip'
import { defineGlobalComponents } from './global-components'
import { createExtensionApi } from './extensions/runtime'
import type { InvoiceShelfExtensionApi } from './extensions/types'
export type {
BootstrapCompletedEvent,
CompanyChangeEvent,
ComponentExtensionContribution,
ExtensionContribution,
ExtensionVisibilityPredicate,
InvoiceShelfExtensionApi,
InvoiceShelfExtensionEvents,
RichEditorContext,
SettingsNavigationContribution,
SettingsPageContribution,
} from './extensions/types'
/**
* Callback signature for the `booting` hook.
* Receives the Vue app instance and the router so that modules /
* plugins can register additional routes, components, or providers.
*/
type BootCallback = (app: App, router: Router) => void
export type BootCallback = (
app: App,
router: Router,
extensions: InvoiceShelfExtensionApi,
) => void
/**
* Bootstrap class for InvoiceShelf.
@@ -31,9 +50,12 @@ export default class InvoiceShelf {
private messages: Record<string, Record<string, unknown>> = {}
private i18n: AppI18n | null = null
private app: App
private readonly extensions: InvoiceShelfExtensionApi
constructor() {
this.app = createApp(App_)
this.extensions = createExtensionApi(router)
window.addEventListener('pagehide', () => this.extensions.reset(), { once: true })
}
/**
@@ -47,11 +69,9 @@ export default class InvoiceShelf {
* Merge additional i18n message bundles (typically from modules).
*/
addMessages(moduleMessages: Record<string, Record<string, unknown>>): void {
this.extensions.addMessages(moduleMessages)
for (const [locale, msgs] of Object.entries(moduleMessages)) {
this.messages[locale] = {
...this.messages[locale],
...msgs,
}
this.messages[locale] = mergeMessageObjects(this.messages[locale] ?? {}, msgs)
}
}
@@ -106,7 +126,7 @@ export default class InvoiceShelf {
private executeCallbacks(): void {
for (const callback of this.bootingCallbacks) {
callback(this.app, router)
callback(this.app, router, this.extensions)
}
}
-19
View File
@@ -116,25 +116,6 @@ export const API = {
COMPANY_MAIL_CONFIG: '/api/v1/company/mail/company-config',
COMPANY_MAIL_TEST: '/api/v1/company/mail/company-test',
// AI Configuration (global)
AI_DRIVERS: '/api/v1/ai/drivers',
AI_CONFIG: '/api/v1/ai/config',
AI_TEST: '/api/v1/ai/test',
// Company AI Configuration
COMPANY_AI_CONFIG: '/api/v1/company/ai/config',
COMPANY_AI_TEST: '/api/v1/company/ai/test',
// Installer AI Configuration
INSTALLATION_AI_CONFIG: '/api/v1/installation/ai/config',
// AI Chat (Phase 2)
AI_CHAT: '/api/v1/ai/chat',
AI_CONVERSATIONS: '/api/v1/ai/conversations',
// AI Text Generation (Phase 3)
AI_GENERATE: '/api/v1/ai/generate',
// PDF Configuration
PDF_DRIVERS: '/api/v1/pdf/drivers',
PDF_CONFIG: '/api/v1/pdf/config',
@@ -1,96 +0,0 @@
import { client } from '../client'
import { API } from '../endpoints'
import type {
AiChatSendResponse,
AiConfig,
AiConversationDetail,
AiConversationSummary,
AiDriversResponse,
AiGenerateRequest,
AiGenerateResponse,
AiTestPayload,
AiTestResponse,
CompanyAiConfig,
} from '@/scripts/types/ai-config'
export const aiService = {
// Driver catalog — same shape across admin, company, installer contexts.
async getDrivers(): Promise<AiDriversResponse> {
const { data } = await client.get(API.AI_DRIVERS)
return data
},
// --- Global (admin) ---
async getGlobalConfig(): Promise<AiConfig> {
const { data } = await client.get(API.AI_CONFIG)
return data
},
async saveGlobalConfig(payload: AiConfig): Promise<{ success?: string; error?: string }> {
const { data } = await client.post(API.AI_CONFIG, payload)
return data
},
async testGlobalConnection(payload: AiTestPayload): Promise<AiTestResponse> {
const { data } = await client.post(API.AI_TEST, payload)
return data
},
// --- Per-company ---
async getCompanyConfig(): Promise<CompanyAiConfig> {
const { data } = await client.get(API.COMPANY_AI_CONFIG)
return data
},
async saveCompanyConfig(payload: CompanyAiConfig): Promise<{ success?: boolean; error?: string }> {
const { data } = await client.post(API.COMPANY_AI_CONFIG, payload)
return data
},
async testCompanyConnection(payload: AiTestPayload): Promise<AiTestResponse> {
const { data } = await client.post(API.COMPANY_AI_TEST, payload)
return data
},
// --- Phase 2: chat ---
async sendChatMessage(
conversationId: number | null,
message: string,
): Promise<AiChatSendResponse> {
const { data } = await client.post(API.AI_CHAT, {
conversation_id: conversationId,
message,
})
return data
},
async listConversations(): Promise<{ conversations: AiConversationSummary[] }> {
const { data } = await client.get(API.AI_CONVERSATIONS)
return data
},
async getConversation(id: number): Promise<AiConversationDetail> {
const { data } = await client.get(`${API.AI_CONVERSATIONS}/${id}`)
return data
},
async renameConversation(id: number, title: string): Promise<{ success: boolean }> {
const { data } = await client.patch(`${API.AI_CONVERSATIONS}/${id}`, { title })
return data
},
async deleteConversation(id: number): Promise<{ success: boolean }> {
const { data } = await client.delete(`${API.AI_CONVERSATIONS}/${id}`)
return data
},
// --- Phase 3: text generation ---
async generateText(payload: AiGenerateRequest): Promise<AiGenerateResponse> {
const { data } = await client.post(API.AI_GENERATE, payload)
return data
},
}
@@ -29,11 +29,6 @@ export interface BootstrapResponse {
config: Record<string, unknown>
global_settings: Record<string, string>
modules: string[]
ai?: {
enabled: boolean
chat_enabled: boolean
text_generation_enabled: boolean
}
user_menu?: Array<{ title: string; link: string; icon: string; priority: number; name: string }>
admin_mode?: boolean
pending_invitations?: Array<{
@@ -37,6 +37,10 @@
{{ button.text }}
</span>
</button>
<ExtensionSlot
name="rich-editor-toolbar-actions"
:context="editorContext"
/>
</div>
</BaseDropdown>
</div>
@@ -58,6 +62,10 @@
{{ button.text }}
</span>
</button>
<ExtensionSlot
name="rich-editor-toolbar-actions"
:context="editorContext"
/>
</div>
</div>
<editor-content
@@ -94,11 +102,10 @@ import {
Bars3BottomRightIcon,
Bars3Icon,
LinkIcon,
SparklesIcon,
} from '@heroicons/vue/24/solid'
import { ContentPlaceholder, ContentPlaceholderBox } from '../layout'
import { useGlobalStore } from '@/scripts/stores/global.store'
import { useModalStore } from '@/scripts/stores/modal.store'
import ExtensionSlot from '@/scripts/extensions/ExtensionSlot.vue'
import type { RichEditorContext } from '@/scripts/extensions/types'
interface EditorButton {
name: string
@@ -170,39 +177,21 @@ const editorButtons = ref<EditorButton[]>([
},
])
// AI text-generation button — shown only when the feature is enabled
// for the current company. The flag is set once at bootstrap time so a
// one-shot push is fine; no reactivity needed.
const globalStore = useGlobalStore()
const modalStore = useModalStore()
if (globalStore.ai?.enabled && globalStore.ai?.text_generation_enabled) {
editorButtons.value.push({
name: 'aiGenerate',
icon: markRaw(SparklesIcon) as Component,
action: () => {
modalStore.openModal({
componentName: 'AiTextGenerationModal',
title: 'AI Text Generation',
size: 'md',
data: {
currentContent: editor.value?.getHTML() ?? '',
onInsert: (text: string) => {
editor.value?.chain().focus().insertContent(text).run()
},
onReplace: (text: string) => {
editor.value?.chain().focus().selectAll().deleteSelection().insertContent(text).run()
},
},
})
},
})
const editorContext: RichEditorContext = {
getHtml: () => editor.value?.getHTML() ?? '',
insertContent: (content: string) => {
editor.value?.chain().focus().insertContent(content).run()
},
replaceContent: (content: string) => {
editor.value?.chain().focus().selectAll().deleteSelection().insertContent(content).run()
},
}
watch(
() => props.modelValue,
(newValue: string) => {
if (editor.value && newValue !== editor.value.getHTML()) {
editor.value.commands.setContent(newValue, false)
editor.value.commands.setContent(newValue, { emitUpdate: false })
}
}
)
@@ -0,0 +1,35 @@
<script setup lang="ts">
import { computed } from 'vue'
import { extensionRegistry, extensionItems } from './runtime'
import type { RichEditorContext } from './types'
const props = defineProps<{
name: 'header-actions' | 'company-layout-overlays' | 'rich-editor-toolbar-actions'
context?: RichEditorContext
}>()
const contributions = computed(() => {
const items = {
'header-actions': extensionRegistry.headerActions.value,
'company-layout-overlays': extensionRegistry.companyLayoutOverlays.value,
'rich-editor-toolbar-actions': extensionRegistry.richEditorToolbarActions.value,
}[props.name]
return extensionItems(items)
})
function componentProps(props_: Record<string, unknown> | undefined): Record<string, unknown> {
return props.context === undefined
? (props_ ?? {})
: { ...props_, context: props.context }
}
</script>
<template>
<component
:is="contribution.component"
v-for="contribution in contributions"
:key="contribution.id"
v-bind="componentProps(contribution.props)"
/>
</template>
+265
View File
@@ -0,0 +1,265 @@
import { markRaw, shallowRef } from 'vue'
import type { ShallowRef } from 'vue'
import type { Router } from 'vue-router'
import { client } from '@/scripts/api/client'
import { useNotificationStore } from '@/scripts/stores/notification.store'
import { registerAdditionalMessages } from '@/scripts/plugins/i18n'
import type {
BootstrapCompletedEvent,
CompanyChangeEvent,
ComponentExtensionContribution,
InvoiceShelfExtensionApi,
InvoiceShelfExtensionEvents,
SettingsNavigationContribution,
SettingsPageContribution,
} from './types'
type ComponentSlot =
| 'headerActions'
| 'companyLayoutOverlays'
| 'richEditorToolbarActions'
interface RegisteredComponentContribution extends ComponentExtensionContribution {
component: ComponentExtensionContribution['component']
}
function comparePriority<T extends { priority?: number; id: string }>(a: T, b: T): number {
return (a.priority ?? 100) - (b.priority ?? 100) || a.id.localeCompare(b.id)
}
function assertContributionId(id: string): void {
if (!id.trim()) {
throw new Error('InvoiceShelf extension contributions require a stable id.')
}
}
/**
* Host-owned reactive registry. Modules only receive the public API below,
* never the host's Pinia stores or layout implementation.
*/
export class ExtensionRegistry {
readonly headerActions = shallowRef<RegisteredComponentContribution[]>([])
readonly companyLayoutOverlays = shallowRef<RegisteredComponentContribution[]>([])
readonly richEditorToolbarActions = shallowRef<RegisteredComponentContribution[]>([])
readonly companySettingsNavigation = shallowRef<SettingsNavigationContribution[]>([])
readonly adminSettingsNavigation = shallowRef<SettingsNavigationContribution[]>([])
private readonly teardowns = new Set<() => void>()
registerComponent(
slot: ComponentSlot,
contribution: ComponentExtensionContribution,
): () => void {
assertContributionId(contribution.id)
const target = this[slot] as ShallowRef<RegisteredComponentContribution[]>
const entry: RegisteredComponentContribution = {
...contribution,
component: markRaw(contribution.component),
}
return this.track(() => {
target.value = [...target.value.filter((item) => item.id !== entry.id), entry]
.sort(comparePriority)
return () => {
target.value = target.value.filter((item) => item !== entry)
}
})
}
registerNavigation(
slot: 'companySettingsNavigation' | 'adminSettingsNavigation',
contribution: SettingsNavigationContribution,
): () => void {
assertContributionId(contribution.id)
const target = this[slot] as ShallowRef<SettingsNavigationContribution[]>
const entry = { ...contribution }
return this.track(() => {
target.value = [...target.value.filter((item) => item.id !== entry.id), entry]
.sort(comparePriority)
return () => {
target.value = target.value.filter((item) => item !== entry)
}
})
}
reset(): void {
for (const teardown of [...this.teardowns]) {
teardown()
}
}
trackTeardown(unregister: () => void): () => void {
return this.track(() => unregister)
}
private track(register: () => () => void): () => void {
const unregister = register()
let active = true
const teardown = () => {
if (!active) return
active = false
unregister()
this.teardowns.delete(teardown)
}
this.teardowns.add(teardown)
return teardown
}
}
export const extensionRegistry = new ExtensionRegistry()
class ExtensionApi implements InvoiceShelfExtensionApi {
private readonly listeners = new Map<
keyof InvoiceShelfExtensionEvents,
Set<(payload: unknown) => void>
>()
private readonly settingsPageTeardowns = new Map<string, () => void>()
constructor(readonly router: Router) {}
readonly client = client
registerHeaderAction(contribution: ComponentExtensionContribution): () => void {
return extensionRegistry.registerComponent('headerActions', contribution)
}
registerCompanyLayoutOverlay(contribution: ComponentExtensionContribution): () => void {
return extensionRegistry.registerComponent('companyLayoutOverlays', contribution)
}
registerRichEditorToolbarAction(contribution: ComponentExtensionContribution): () => void {
return extensionRegistry.registerComponent('richEditorToolbarActions', contribution)
}
registerCompanySettingsNavigation(contribution: SettingsNavigationContribution): () => void {
return extensionRegistry.registerNavigation('companySettingsNavigation', contribution)
}
registerAdminSettingsNavigation(contribution: SettingsNavigationContribution): () => void {
return extensionRegistry.registerNavigation('adminSettingsNavigation', contribution)
}
registerCompanySettingsPage(contribution: SettingsPageContribution): () => void {
return this.registerSettingsPage('settings', 'companySettingsNavigation', contribution)
}
registerAdminSettingsPage(contribution: SettingsPageContribution): () => void {
return this.registerSettingsPage('admin.settings', 'adminSettingsNavigation', contribution)
}
addMessages(messages: Record<string, Record<string, unknown>>): void {
registerAdditionalMessages(messages)
}
notify(type: 'success' | 'error' | 'warning' | 'info', message: string): void {
useNotificationStore().showNotification({ type, message })
}
on<EventName extends keyof InvoiceShelfExtensionEvents>(
event: EventName,
listener: (payload: InvoiceShelfExtensionEvents[EventName]) => void,
): () => void {
const listeners = this.listeners.get(event) ?? new Set<(payload: unknown) => void>()
this.listeners.set(event, listeners)
listeners.add(listener as (payload: unknown) => void)
return () => listeners.delete(listener as (payload: unknown) => void)
}
emit<EventName extends keyof InvoiceShelfExtensionEvents>(
event: EventName,
payload: InvoiceShelfExtensionEvents[EventName],
): void {
for (const listener of this.listeners.get(event) ?? []) {
listener(payload)
}
}
reset(): void {
extensionRegistry.reset()
this.settingsPageTeardowns.clear()
for (const listeners of this.listeners.values()) {
listeners.clear()
}
}
private registerSettingsPage(
parentName: string,
navigationSlot: 'companySettingsNavigation' | 'adminSettingsNavigation',
contribution: SettingsPageContribution,
): () => void {
assertContributionId(contribution.id)
if (!contribution.path || contribution.path.startsWith('/')) {
throw new Error('InvoiceShelf extension settings paths must be relative.')
}
const routeName = `extension.${parentName}.${contribution.id}`
const pageKey = `${parentName}:${contribution.id}`
this.settingsPageTeardowns.get(pageKey)?.()
const removeRoute = this.router.addRoute(parentName, {
path: contribution.path,
name: routeName,
component: markRaw(contribution.component),
meta: contribution.meta,
})
const removeNavigation = extensionRegistry.registerNavigation(navigationSlot, {
id: contribution.id,
priority: contribution.priority,
visible: contribution.visible,
title: contribution.title,
icon: contribution.icon,
to: { name: routeName },
})
let active = true
const teardown = () => {
if (!active) return
active = false
removeNavigation()
removeRoute()
this.settingsPageTeardowns.delete(pageKey)
}
const trackedTeardown = extensionRegistry.trackTeardown(teardown)
this.settingsPageTeardowns.set(pageKey, trackedTeardown)
return trackedTeardown
}
}
let extensionApi: ExtensionApi | null = null
export function createExtensionApi(router: Router): InvoiceShelfExtensionApi {
extensionApi ??= new ExtensionApi(router)
return extensionApi
}
export function emitBootstrapCompleted(payload: BootstrapCompletedEvent): void {
extensionApi?.emit('bootstrap:completed', payload)
}
export function emitCompanyChanging(payload: CompanyChangeEvent): void {
extensionApi?.emit('company:changing', payload)
}
export function emitCompanyChanged(payload: CompanyChangeEvent): void {
extensionApi?.emit('company:changed', payload)
}
export function isContributionVisible(contribution: { visible?: () => boolean }): boolean {
try {
return contribution.visible?.() ?? true
} catch (error) {
console.warn('InvoiceShelf extension visibility predicate failed.', error)
return false
}
}
export function extensionItems<T extends { visible?: () => boolean }>(
items: readonly T[],
): T[] {
return items.filter(isContributionVisible)
}
+12
View File
@@ -0,0 +1,12 @@
export type {
BootstrapCompletedEvent,
CompanyChangeEvent,
ComponentExtensionContribution,
ExtensionContribution,
ExtensionVisibilityPredicate,
InvoiceShelfExtensionApi,
InvoiceShelfExtensionEvents,
RichEditorContext,
SettingsNavigationContribution,
SettingsPageContribution,
} from '../../../vendor/invoiceshelf/modules/frontend/index'
@@ -9,7 +9,6 @@ const AdminUsersView = () => import('./views/AdminUsersView.vue')
const AdminUserEditView = () => import('./views/AdminUserEditView.vue')
const AdminSettingsView = () => import('./views/AdminSettingsView.vue')
const AdminMailConfigView = () => import('./views/settings/AdminMailConfigView.vue')
const AdminAiConfigView = () => import('./views/settings/AdminAiConfigView.vue')
const AdminPdfGenerationView = () => import('./views/settings/AdminPdfGenerationView.vue')
const AdminBackupView = () => import('./views/settings/AdminBackupView.vue')
const AdminFileDiskView = () => import('./views/settings/AdminFileDiskView.vue')
@@ -88,14 +87,6 @@ export const adminRoutes: RouteRecordRaw[] = [
},
component: AdminMailConfigView,
},
{
path: 'ai-configuration',
name: 'admin.settings.ai',
meta: {
isSuperAdmin: true,
},
component: AdminAiConfigView,
},
{
path: 'pdf-generation',
name: 'admin.settings.pdf',
@@ -54,6 +54,7 @@
import { ref, computed, watchEffect } from 'vue'
import { useRoute, useRouter, RouterView } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { extensionItems, extensionRegistry } from '@/scripts/extensions/runtime'
interface SettingsMenuItem {
title: string
@@ -73,11 +74,6 @@ const menuItems = computed<SettingsMenuItem[]>(() => [
link: '/admin/administration/settings/mail-configuration',
icon: 'EnvelopeIcon',
},
{
title: t('settings.menu_title.ai_configuration'),
link: '/admin/administration/settings/ai-configuration',
icon: 'SparklesIcon',
},
{
title: t('settings.menu_title.pdf_generation'),
link: '/admin/administration/settings/pdf-generation',
@@ -108,6 +104,11 @@ const menuItems = computed<SettingsMenuItem[]>(() => [
link: '/admin/administration/settings/appearance',
icon: 'PaintBrushIcon',
},
...extensionItems(extensionRegistry.adminSettingsNavigation.value).map((item) => ({
title: t(item.title),
link: router.resolve(item.to).fullPath,
icon: item.icon,
})),
])
watchEffect(() => {
@@ -1,107 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useNotificationStore } from '@/scripts/stores/notification.store'
import { aiService } from '@/scripts/api/services/ai.service'
import type { AiConfig, AiDriverOption, AiTestPayload } from '@/scripts/types/ai-config'
import { getErrorTranslationKey, handleApiError } from '@/scripts/utils/error-handling'
import AiConfigurationForm from '@/scripts/features/company/settings/components/AiConfigurationForm.vue'
const { t } = useI18n()
const notificationStore = useNotificationStore()
const isSaving = ref(false)
const isTesting = ref(false)
const isFetchingInitialData = ref(false)
const configData = ref<AiConfig | null>(null)
const drivers = ref<AiDriverOption[]>([])
loadData()
async function loadData(): Promise<void> {
isFetchingInitialData.value = true
try {
const [driversResponse, configResponse] = await Promise.all([
aiService.getDrivers(),
aiService.getGlobalConfig(),
])
drivers.value = driversResponse.ai_drivers
configData.value = configResponse
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
} finally {
isFetchingInitialData.value = false
}
}
async function saveConfig(value: AiConfig): Promise<void> {
isSaving.value = true
try {
const response = await aiService.saveGlobalConfig(value)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: 'settings.ai.saved',
})
configData.value = { ...value }
}
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
} finally {
isSaving.value = false
}
}
async function testConnection(payload: AiTestPayload): Promise<void> {
isTesting.value = true
try {
const response = await aiService.testGlobalConnection(payload)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: 'settings.ai.test_success',
})
} else if (response.error) {
notificationStore.showNotification({
type: 'error',
message: t('settings.ai.errors.' + response.error, { error: response.message ?? '' }),
})
}
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
} finally {
isTesting.value = false
}
}
</script>
<template>
<BaseSettingCard
:title="$t('settings.ai.title')"
:description="$t('settings.ai.description')"
>
<div v-if="configData" class="mt-14">
<AiConfigurationForm
:config-data="configData"
:drivers="drivers"
:is-saving="isSaving"
:is-testing="isTesting"
:is-fetching-initial-data="isFetchingInitialData"
@submit-data="saveConfig"
@test-connection="testConnection"
/>
</div>
</BaseSettingCard>
</template>
@@ -1,79 +0,0 @@
<script setup lang="ts">
import { useAiChatStore } from '../stores/ai-chat.store'
import type { AiConversationSummary } from '@/scripts/types/ai-config'
const store = useAiChatStore()
async function select(convo: AiConversationSummary): Promise<void> {
await store.loadConversation(convo.id)
}
async function remove(convo: AiConversationSummary, event: MouseEvent): Promise<void> {
event.stopPropagation()
if (!window.confirm('Delete this conversation?')) return
await store.deleteConversation(convo.id)
}
</script>
<template>
<div class="flex flex-col h-full">
<div class="h-12 px-3 border-b border-line-default flex items-center">
<button
type="button"
class="w-full text-center text-xs font-medium rounded px-2 py-1 bg-btn-primary text-white hover:bg-btn-primary-hover"
@click="store.newConversation()"
>
+ {{ $t('ai.chat.new_conversation') }}
</button>
</div>
<div class="flex-1 overflow-y-auto">
<div
v-if="store.isLoadingConversations && store.conversations.length === 0"
class="p-3 text-xs text-muted"
>
{{ $t('general.loading') }}...
</div>
<div
v-else-if="store.conversations.length === 0"
class="p-3 text-xs text-muted"
>
{{ $t('ai.chat.no_conversations') }}
</div>
<ul v-else class="space-y-1 p-2">
<li
v-for="convo in store.conversations"
:key="convo.id"
>
<button
type="button"
class="
w-full text-left flex items-center justify-between
px-3 py-2 rounded text-sm group
hover:bg-hover
"
:class="{
'bg-hover-strong font-semibold': store.currentConversationId === convo.id,
}"
@click="select(convo)"
>
<span class="truncate text-body">
{{ convo.title ?? $t('ai.chat.untitled') }}
</span>
<span
class="
ml-2 text-xs text-muted opacity-0 group-hover:opacity-100
hover:text-alert-error-text
"
@click="remove(convo, $event)"
>
{{ $t('general.delete') }}
</span>
</button>
</li>
</ul>
</div>
</div>
</template>
@@ -1,140 +0,0 @@
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { useAiChatStore } from '../stores/ai-chat.store'
import AiChatMessage from './AiChatMessage.vue'
import AiChatMessageInput from './AiChatMessageInput.vue'
import AiChatConversationList from './AiChatConversationList.vue'
const store = useAiChatStore()
const messagesEl = ref<HTMLDivElement | null>(null)
// Auto-scroll to the bottom whenever the message list grows.
watch(
() => store.messages.length,
async () => {
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
},
)
async function onSend(message: string): Promise<void> {
await store.sendMessage(message)
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
}
</script>
<template>
<!-- Backdrop -->
<Teleport to="body">
<transition name="ai-drawer-fade">
<div
v-if="store.isOpen"
class="fixed inset-0 bg-black/20 z-40"
@click="store.close()"
/>
</transition>
<!-- Drawer panel -->
<transition name="ai-drawer-slide">
<aside
v-if="store.isOpen"
class="
fixed top-0 right-0 bottom-0 z-50
w-full sm:w-[480px] lg:w-[640px]
bg-surface shadow-2xl
flex
"
>
<!-- Conversation list sidebar -->
<div class="hidden sm:block w-48 border-r border-line-default bg-surface-secondary">
<AiChatConversationList />
</div>
<!-- Messages + input -->
<div class="flex-1 flex flex-col">
<div class="h-12 flex items-center justify-between px-3 border-b border-line-default">
<div class="flex items-center gap-2">
<BaseIcon name="SparklesIcon" class="w-5 h-5 text-primary-500" />
<h2 class="text-sm font-semibold text-heading">
{{ $t('ai.chat.title') }}
</h2>
</div>
<button
type="button"
class="text-muted hover:text-heading"
@click="store.close()"
>
<BaseIcon name="XMarkIcon" class="w-5 h-5" />
</button>
</div>
<div
ref="messagesEl"
class="flex-1 overflow-y-auto p-4 space-y-3"
>
<div
v-if="store.messages.length === 0"
class="text-center text-sm text-muted mt-12"
>
<BaseIcon name="SparklesIcon" class="w-10 h-10 mx-auto mb-2 text-subtle" />
<p>{{ $t('ai.chat.empty_state') }}</p>
</div>
<AiChatMessage
v-for="msg in store.messages"
:key="msg.id"
:message="msg"
/>
<div
v-if="store.isSending"
class="flex justify-start"
>
<div class="bg-surface-tertiary rounded-lg px-4 py-2 text-sm text-muted italic">
{{ $t('ai.chat.thinking') }}
</div>
</div>
<div
v-if="store.lastError"
class="p-3 text-xs text-alert-error-text bg-alert-error-bg rounded"
>
{{ store.lastError }}
</div>
</div>
<AiChatMessageInput
:is-sending="store.isSending"
@send="onSend"
/>
</div>
</aside>
</transition>
</Teleport>
</template>
<style scoped>
.ai-drawer-fade-enter-active,
.ai-drawer-fade-leave-active {
transition: opacity 0.2s ease;
}
.ai-drawer-fade-enter-from,
.ai-drawer-fade-leave-to {
opacity: 0;
}
.ai-drawer-slide-enter-active,
.ai-drawer-slide-leave-active {
transition: transform 0.25s ease;
}
.ai-drawer-slide-enter-from,
.ai-drawer-slide-leave-to {
transform: translateX(100%);
}
</style>
@@ -1,42 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { AiChatMessage } from '@/scripts/types/ai-config'
import { renderMarkdown } from '@/scripts/utils/markdown'
const props = defineProps<{
message: AiChatMessage
}>()
const isUser = computed(() => props.message.role === 'user')
// Assistant messages get rendered as markdown → sanitized HTML so GFM
// features (code blocks, lists, tables, inline formatting) display as
// the model intended. User messages stay as plain text because the
// user typed them verbatim and markdown syntax would be surprising.
const renderedHtml = computed(() =>
isUser.value ? '' : renderMarkdown(props.message.content ?? ''),
)
</script>
<template>
<div
class="flex"
:class="isUser ? 'justify-end' : 'justify-start'"
>
<div
class="max-w-[85%] rounded-lg px-4 py-2 text-sm"
:class="
isUser
? 'bg-primary-500 text-white'
: 'bg-surface-tertiary text-body'
"
>
<p v-if="isUser" class="whitespace-pre-wrap break-words">
{{ message.content ?? '' }}
</p>
<!-- Assistant output is sanitized via DOMPurify in renderMarkdown
before it reaches v-html see resources/scripts/utils/markdown.ts. -->
<BaseSanitizedHtml v-else class="prose prose-sm max-w-none break-words" :html="renderedHtml" />
</div>
</div>
</template>
@@ -1,62 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{
isSending?: boolean
}>()
const emit = defineEmits<{
send: [message: string]
}>()
const text = ref<string>('')
function submit(): void {
const trimmed = text.value.trim()
if (!trimmed || props.isSending) return
emit('send', trimmed)
text.value = ''
}
/**
* Shift+Enter → newline, Enter alone → submit (standard chat UX).
*/
function onKeydown(e: KeyboardEvent): void {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
submit()
}
}
</script>
<template>
<form
class="border-t border-line-default p-3 flex items-end gap-2"
@submit.prevent="submit"
>
<textarea
v-model="text"
rows="2"
class="
flex-1 resize-none rounded-md border border-line-default
bg-surface text-body text-sm px-3 py-2
focus:outline-none focus:ring-1 focus:ring-primary-500
"
:placeholder="$t('ai.chat.input_placeholder')"
:disabled="isSending"
@keydown="onKeydown"
/>
<button
type="submit"
class="
rounded-md px-3 py-2 text-sm font-medium
bg-btn-primary text-white hover:bg-btn-primary-hover
disabled:opacity-50 disabled:cursor-not-allowed
"
:disabled="!text.trim() || isSending"
>
{{ isSending ? $t('ai.chat.sending') : $t('ai.chat.send') }}
</button>
</form>
</template>
@@ -1,149 +0,0 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { aiService } from '@/scripts/api/services/ai.service'
import type {
AiChatMessage,
AiConversationSummary,
} from '@/scripts/types/ai-config'
/**
* Chat drawer state + conversation history.
*
* The drawer is a global overlay (not a route), so this store is where its
* open/closed state, current conversation, message list, and loading state all
* live. Message-sending is persisted server-side — we don't keep optimistic
* state across reloads.
*/
export const useAiChatStore = defineStore('ai-chat', () => {
// --- Drawer UI state ---
const isOpen = ref<boolean>(false)
// --- Current conversation ---
const currentConversationId = ref<number | null>(null)
const messages = ref<AiChatMessage[]>([])
const isSending = ref<boolean>(false)
const lastError = ref<string | null>(null)
// --- Conversation list (sidebar inside the drawer) ---
const conversations = ref<AiConversationSummary[]>([])
const isLoadingConversations = ref<boolean>(false)
const hasActiveConversation = computed<boolean>(() => currentConversationId.value !== null)
// --- Actions ---
function open(): void {
isOpen.value = true
// Refresh the sidebar list on open so the user sees any new conversations
// they started in another tab.
void refreshConversations()
}
function close(): void {
isOpen.value = false
}
function toggle(): void {
isOpen.value ? close() : open()
}
function newConversation(): void {
currentConversationId.value = null
messages.value = []
lastError.value = null
}
async function refreshConversations(): Promise<void> {
isLoadingConversations.value = true
try {
const response = await aiService.listConversations()
conversations.value = response.conversations
} catch {
// silent — the drawer stays functional without the sidebar list
} finally {
isLoadingConversations.value = false
}
}
async function loadConversation(id: number): Promise<void> {
lastError.value = null
const response = await aiService.getConversation(id)
currentConversationId.value = response.conversation.id
messages.value = response.messages
}
async function sendMessage(text: string): Promise<void> {
if (!text.trim()) return
if (isSending.value) return
lastError.value = null
isSending.value = true
// Optimistic local append so the user sees their message immediately.
const optimistic: AiChatMessage = {
id: Date.now() * -1,
role: 'user',
content: text,
created_at: new Date().toISOString(),
}
messages.value.push(optimistic)
try {
const response = await aiService.sendChatMessage(currentConversationId.value, text)
// The backend may have started a new conversation for us.
currentConversationId.value = response.conversation.id
messages.value.push(response.message)
// Refresh the sidebar so the new/updated conversation bubbles to the top.
void refreshConversations()
} catch (err) {
// Roll back the optimistic message so the user can retry.
messages.value = messages.value.filter((m) => m.id !== optimistic.id)
const message = err instanceof Error ? err.message : 'Unknown error'
lastError.value = message
} finally {
isSending.value = false
}
}
async function deleteConversation(id: number): Promise<void> {
await aiService.deleteConversation(id)
conversations.value = conversations.value.filter((c) => c.id !== id)
// If the deleted conversation is the one currently shown, start fresh.
if (currentConversationId.value === id) {
newConversation()
}
}
async function renameConversation(id: number, title: string): Promise<void> {
await aiService.renameConversation(id, title)
const existing = conversations.value.find((c) => c.id === id)
if (existing) existing.title = title
}
return {
// state
isOpen,
currentConversationId,
messages,
isSending,
lastError,
conversations,
isLoadingConversations,
// getters
hasActiveConversation,
// actions
open,
close,
toggle,
newConversation,
refreshConversations,
loadConversation,
sendMessage,
deleteConversation,
renameConversation,
}
})
@@ -1,316 +0,0 @@
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import useVuelidate from '@vuelidate/core'
import { helpers, required, requiredIf, url as urlValidator } from '@vuelidate/validators'
import type {
AiConfig,
AiDriverConfigField,
AiDriverOption,
} from '@/scripts/types/ai-config'
const props = withDefaults(
defineProps<{
configData?: Partial<AiConfig>
isSaving?: boolean
isFetchingInitialData?: boolean
drivers?: AiDriverOption[]
isTesting?: boolean
}>(),
{
configData: () => ({}),
isSaving: false,
isFetchingInitialData: false,
drivers: () => [],
isTesting: false,
},
)
const emit = defineEmits<{
'submit-data': [config: AiConfig]
'test-connection': [config: Pick<AiConfig, 'ai_driver' | 'ai_api_key' | 'ai_base_url'>]
}>()
const { t } = useI18n()
const form = reactive<AiConfig>(createDefaults())
const showKey = ref(false)
const selectedDriver = computed<AiDriverOption | undefined>(() =>
props.drivers.find((d) => d.value === form.ai_driver),
)
const suggestedModels = computed(() => selectedDriver.value?.suggested_models ?? [])
const configFields = computed<AiDriverConfigField[]>(() => selectedDriver.value?.config_fields ?? [])
const isAiOn = computed(() => form.ai_enabled === 'YES')
const isChatOn = computed(() => form.ai_chat_enabled === 'YES')
const isTextGenOn = computed(() => form.ai_text_generation_enabled === 'YES')
const driversList = computed(() =>
props.drivers.map((d) => ({ value: d.value, label: t(d.label) })),
)
const modelDatalistId = 'ai-model-suggestions'
const rules = computed(() => ({
ai_driver: {
required: helpers.withMessage(
t('validation.required'),
requiredIf(() => isAiOn.value),
),
},
ai_api_key: {
required: helpers.withMessage(
t('validation.required'),
requiredIf(() => isAiOn.value),
),
},
ai_base_url: {
url: helpers.withMessage(t('validation.invalid_url'), (value: string) => {
if (!value) return true
return urlValidator.$validator(value, {} as never, {} as never)
}),
},
ai_chat_model: {
required: helpers.withMessage(
t('validation.required'),
requiredIf(() => isAiOn.value && isChatOn.value),
),
},
ai_text_generation_model: {
required: helpers.withMessage(
t('validation.required'),
requiredIf(() => isAiOn.value && isTextGenOn.value),
),
},
}))
const v$ = useVuelidate(rules, form)
function createDefaults(): AiConfig {
return {
ai_enabled: 'NO',
ai_driver: 'openrouter',
ai_api_key: '',
ai_base_url: '',
ai_chat_enabled: 'NO',
ai_chat_model: 'anthropic/claude-sonnet-4.6',
ai_text_generation_enabled: 'NO',
ai_text_generation_model: 'anthropic/claude-haiku-4.5',
}
}
function hydrateFromProps() {
if (!props.configData) return
for (const key of Object.keys(form) as Array<keyof AiConfig>) {
if (props.configData[key] !== undefined && props.configData[key] !== null) {
;(form as Record<string, unknown>)[key] = props.configData[key]
}
}
}
watch(() => props.configData, hydrateFromProps, { immediate: true, deep: true })
// When the driver changes, fill in the driver-default base_url if the user hasn't provided one.
watch(
() => form.ai_driver,
(next) => {
const driver = props.drivers.find((d) => d.value === next)
if (driver?.default_base_url && !form.ai_base_url) {
form.ai_base_url = driver.default_base_url
}
},
)
async function onSubmit() {
const valid = await v$.value.$validate()
if (!valid) return
emit('submit-data', { ...form })
}
function onTestConnection() {
emit('test-connection', {
ai_driver: form.ai_driver,
ai_api_key: form.ai_api_key,
ai_base_url: form.ai_base_url,
})
}
</script>
<template>
<form @submit.prevent="onSubmit">
<!-- Global enable -->
<div class="mb-8">
<BaseSwitch
:model-value="isAiOn"
class="flex"
:label-right="$t('settings.ai.enable')"
@update:model-value="form.ai_enabled = $event ? 'YES' : 'NO'"
/>
<p class="mt-2 text-xs text-muted">{{ $t('settings.ai.enable_help') }}</p>
</div>
<div v-if="isAiOn" class="space-y-6">
<!-- Provider selection -->
<BaseInputGroup
:label="$t('settings.ai.driver')"
:content-loading="isFetchingInitialData"
required
:error="v$.ai_driver.$error && v$.ai_driver.$errors[0]?.$message"
>
<BaseMultiselect
v-model="form.ai_driver"
:options="driversList"
:content-loading="isFetchingInitialData"
value-prop="value"
label="label"
track-by="label"
:can-deselect="false"
:invalid="v$.ai_driver.$error"
/>
</BaseInputGroup>
<!-- API key -->
<BaseInputGroup
:label="$t('settings.ai.api_key')"
:content-loading="isFetchingInitialData"
:help-text="$t('settings.ai.api_key_help')"
required
:error="v$.ai_api_key.$error && v$.ai_api_key.$errors[0]?.$message"
>
<div class="flex gap-2">
<BaseInput
v-model="form.ai_api_key"
:content-loading="isFetchingInitialData"
:type="showKey ? 'text' : 'password'"
class="flex-1"
name="ai_api_key"
:invalid="v$.ai_api_key.$error"
/>
<BaseButton
type="button"
variant="primary-outline"
@click="showKey = !showKey"
>
{{ showKey ? $t('general.hide') : $t('general.show') }}
</BaseButton>
</div>
</BaseInputGroup>
<!-- Driver-specific config fields (base_url for OpenRouter, etc.) -->
<BaseInputGroup
v-for="field in configFields"
:key="field.key"
:label="$t(field.label)"
:content-loading="isFetchingInitialData"
>
<BaseInput
v-if="field.type === 'text'"
:model-value="(form as unknown as Record<string, string>)[`ai_${field.key}`] ?? ''"
:placeholder="field.default"
type="text"
:name="`ai_${field.key}`"
@update:model-value="(val: string) => ((form as unknown as Record<string, string>)[`ai_${field.key}`] = val)"
/>
</BaseInputGroup>
<!-- Role: chat -->
<div class="border-t border-line-default pt-6">
<h3 class="text-sm font-semibold text-heading mb-3">{{ $t('settings.ai.roles') }}</h3>
<p class="text-xs text-muted mb-4">{{ $t('settings.ai.roles_help') }}</p>
<div class="mb-6">
<BaseSwitch
:model-value="isChatOn"
class="flex"
:label-right="$t('settings.ai.chat')"
@update:model-value="form.ai_chat_enabled = $event ? 'YES' : 'NO'"
/>
<p class="mt-2 text-xs text-muted">{{ $t('settings.ai.chat_help') }}</p>
<BaseInputGroup
v-if="isChatOn"
class="mt-3"
:label="$t('settings.ai.chat_model')"
required
:error="v$.ai_chat_model.$error && v$.ai_chat_model.$errors[0]?.$message"
>
<BaseInput
v-model="form.ai_chat_model"
type="text"
:list="modelDatalistId"
:invalid="v$.ai_chat_model.$error"
/>
</BaseInputGroup>
</div>
<!-- Role: text generation -->
<div>
<BaseSwitch
:model-value="isTextGenOn"
class="flex"
:label-right="$t('settings.ai.text_generation')"
@update:model-value="form.ai_text_generation_enabled = $event ? 'YES' : 'NO'"
/>
<p class="mt-2 text-xs text-muted">{{ $t('settings.ai.text_generation_help') }}</p>
<BaseInputGroup
v-if="isTextGenOn"
class="mt-3"
:label="$t('settings.ai.text_generation_model')"
required
:error="
v$.ai_text_generation_model.$error &&
v$.ai_text_generation_model.$errors[0]?.$message
"
>
<BaseInput
v-model="form.ai_text_generation_model"
type="text"
:list="modelDatalistId"
:invalid="v$.ai_text_generation_model.$error"
/>
</BaseInputGroup>
</div>
<!-- Datalist with suggested models for both inputs -->
<datalist :id="modelDatalistId">
<option
v-for="model in suggestedModels"
:key="model.value"
:value="model.value"
>
{{ model.label }}
</option>
</datalist>
</div>
</div>
<!-- Actions -->
<div class="flex items-center gap-3 mt-8">
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
>
<template #left="slotProps">
<BaseIcon v-if="!isSaving" name="ArrowDownOnSquareIcon" :class="slotProps.class" />
</template>
{{ $t('general.save') }}
</BaseButton>
<BaseButton
v-if="isAiOn"
:loading="isTesting"
:disabled="isTesting || isSaving"
variant="primary-outline"
type="button"
@click="onTestConnection"
>
{{ $t('settings.ai.test_connection') }}
</BaseButton>
</div>
</form>
</template>
@@ -34,6 +34,7 @@ const settingsRoutes: RouteRecordRaw[] = [
},
{
path: 'settings',
name: 'settings',
component: () => import('./views/SettingsLayoutView.vue'),
children: [
{
@@ -158,15 +159,6 @@ const settingsRoutes: RouteRecordRaw[] = [
},
component: () => import('./views/MailConfigView.vue'),
},
{
path: 'ai-config',
name: 'settings.ai-config',
meta: {
requiresAuth: true,
isOwner: true,
},
component: () => import('./views/AiConfigView.vue'),
},
{
path: 'roles',
name: 'settings.roles',
@@ -1,165 +0,0 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useNotificationStore } from '@/scripts/stores/notification.store'
import { aiService } from '@/scripts/api/services/ai.service'
import type {
AiConfig,
AiDriverOption,
AiTestPayload,
CompanyAiConfig,
} from '@/scripts/types/ai-config'
import { getErrorTranslationKey, handleApiError } from '@/scripts/utils/error-handling'
import AiConfigurationForm from '@/scripts/features/company/settings/components/AiConfigurationForm.vue'
const { t } = useI18n()
const notificationStore = useNotificationStore()
const isSaving = ref(false)
const isTesting = ref(false)
const isFetchingInitialData = ref(false)
const useCustomAiConfig = ref(false)
const configData = ref<CompanyAiConfig | null>(null)
const drivers = ref<AiDriverOption[]>([])
loadData()
async function loadData(): Promise<void> {
isFetchingInitialData.value = true
try {
const [driversResponse, configResponse] = await Promise.all([
aiService.getDrivers(),
aiService.getCompanyConfig(),
])
drivers.value = driversResponse.ai_drivers
configData.value = configResponse
useCustomAiConfig.value = configResponse.use_custom_ai_config === 'YES'
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
} finally {
isFetchingInitialData.value = false
}
}
// Mirror the mail pattern: flipping the toggle OFF auto-saves and discards driver fields.
watch(useCustomAiConfig, async (next, prev) => {
if (prev === undefined) return
if (next) return // ON — wait for explicit save
isSaving.value = true
try {
await aiService.saveCompanyConfig({
use_custom_ai_config: 'NO',
} as CompanyAiConfig)
if (configData.value) {
configData.value.use_custom_ai_config = 'NO'
}
notificationStore.showNotification({
type: 'success',
message: 'settings.ai.saved',
})
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
useCustomAiConfig.value = true // revert the toggle
} finally {
isSaving.value = false
}
})
async function saveConfig(value: AiConfig): Promise<void> {
isSaving.value = true
try {
const payload: CompanyAiConfig = {
...value,
use_custom_ai_config: 'YES',
}
const response = await aiService.saveCompanyConfig(payload)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: 'settings.ai.saved',
})
configData.value = payload
}
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
} finally {
isSaving.value = false
}
}
async function testConnection(payload: AiTestPayload): Promise<void> {
isTesting.value = true
try {
const response = await aiService.testCompanyConnection(payload)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: 'settings.ai.test_success',
})
} else if (response.error) {
notificationStore.showNotification({
type: 'error',
message: t('settings.ai.errors.' + response.error, { error: response.message ?? '' }),
})
}
} catch (error: unknown) {
const normalizedError = handleApiError(error)
notificationStore.showNotification({
type: 'error',
message: getErrorTranslationKey(normalizedError.message) ?? normalizedError.message,
})
} finally {
isTesting.value = false
}
}
</script>
<template>
<BaseSettingCard
:title="$t('settings.ai.title')"
:description="$t('settings.ai.description')"
>
<div class="mt-8">
<BaseSwitchSection
v-model="useCustomAiConfig"
:title="$t('settings.ai.use_custom_ai_config')"
:description="$t('settings.ai.use_custom_ai_config_desc')"
/>
</div>
<div
v-if="!useCustomAiConfig"
class="mt-6 p-4 rounded bg-alert-success-bg text-alert-success-text text-sm"
>
{{ $t('settings.ai.using_global_ai_config') }}
</div>
<div v-if="useCustomAiConfig && configData" class="mt-8">
<AiConfigurationForm
:config-data="configData"
:drivers="drivers"
:is-saving="isSaving"
:is-testing="isTesting"
:is-fetching-initial-data="isFetchingInitialData"
@submit-data="saveConfig"
@test-connection="testConnection"
/>
</div>
</BaseSettingCard>
</template>
@@ -4,6 +4,7 @@ import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useGlobalStore } from '../../../../stores/global.store'
import { useUserStore } from '../../../../stores/user.store'
import { extensionItems, extensionRegistry } from '@/scripts/extensions/runtime'
interface SettingMenuItem {
title: string
@@ -33,6 +34,14 @@ const dropdownMenuItems = computed<DropdownMenuItem[]>(() => {
title: t(item.title),
}))
items.push(
...extensionItems(extensionRegistry.companySettingsNavigation.value).map((item) => ({
title: t(item.title),
link: router.resolve(item.to).fullPath,
icon: item.icon,
})),
)
if (showDangerZone.value) {
items.push({
title: t('settings.company_info.danger_zone'),
@@ -44,6 +53,12 @@ const dropdownMenuItems = computed<DropdownMenuItem[]>(() => {
return items
})
const sidebarMenuItems = computed<DropdownMenuItem[]>(() =>
dropdownMenuItems.value.filter(
(item) => item.link !== '/admin/settings/danger-zone',
),
)
watchEffect(() => {
if (route.path === '/admin/settings') {
// Redirect to first available setting menu item, or account settings as fallback
@@ -95,9 +110,9 @@ function navigateToSetting(setting: DropdownMenuItem): void {
<div class="hidden mt-1 xl:block min-w-[240px] sticky top-20 self-start">
<BaseList>
<BaseListItem
v-for="(menuItem, index) in globalStore.settingMenu"
v-for="(menuItem, index) in sidebarMenuItems"
:key="index"
:title="$t(menuItem.title)"
:title="menuItem.title"
:to="menuItem.link"
:active="hasActiveUrl(menuItem.link)"
:index="index"
@@ -15,10 +15,9 @@ import InstallationLayout from '@/scripts/layouts/InstallationLayout.vue'
* 4. DatabaseView (/installation/database)
* 5. DomainView (/installation/domain)
* 6. MailView (/installation/mail)
* 7. AiView (/installation/ai) — optional, skippable
* 8. AccountView (/installation/account)
* 9. CompanyView (/installation/company)
* 10. PreferencesView (/installation/preferences)
* 7. AccountView (/installation/account)
* 8. CompanyView (/installation/company)
* 9. PreferencesView (/installation/preferences)
*
* Each child view owns its own next() function and calls router.push() to
* the next step by route name. There is no event-based step coordination —
@@ -91,15 +90,6 @@ export const installationRoutes: RouteRecordRaw[] = [
isInstallation: true,
},
},
{
path: 'ai',
name: 'installation.ai',
component: () => import('./views/AiView.vue'),
meta: {
title: 'settings.ai.installer_title',
isInstallation: true,
},
},
{
path: 'account',
name: 'installation.account',
@@ -1,100 +0,0 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { installClient } from '@/scripts/api/install-client'
import type {
AiConfig,
AiDriverOption,
AiDriversResponse,
} from '@/scripts/types/ai-config'
import AiConfigurationForm from '@/scripts/features/company/settings/components/AiConfigurationForm.vue'
import { useInstallationFeedback } from '../use-installation-feedback'
const router = useRouter()
const { isSuccessfulResponse, showRequestError, showResponseError } = useInstallationFeedback()
const isSaving = ref(false)
const isFetchingInitialData = ref(false)
const configData = ref<AiConfig | null>(null)
const drivers = ref<AiDriverOption[]>([])
onMounted(loadData)
async function loadData(): Promise<void> {
isFetchingInitialData.value = true
try {
const { data } = await installClient.get<{
config: AiConfig
drivers: AiDriversResponse['ai_drivers']
}>('/api/v1/installation/ai/config')
configData.value = data.config
drivers.value = data.drivers
} catch (error: unknown) {
showRequestError(error)
} finally {
isFetchingInitialData.value = false
}
}
async function saveAi(value: AiConfig): Promise<void> {
isSaving.value = true
try {
const { data } = await installClient.post('/api/v1/installation/ai/config', value)
if (!isSuccessfulResponse(data)) {
showResponseError(data)
return
}
await router.push({ name: 'installation.account' })
} catch (error: unknown) {
showRequestError(error)
} finally {
isSaving.value = false
}
}
async function skipStep(): Promise<void> {
// Persist the disabled default so bootstrap sees an explicit ai_enabled=NO
// (rather than a missing key that defaults to NO anyway — we want the value
// in storage so tests / repeated installer runs behave predictably).
await saveAi({
ai_enabled: 'NO',
ai_driver: 'openrouter',
ai_api_key: '',
ai_base_url: '',
ai_chat_enabled: 'NO',
ai_chat_model: '',
ai_text_generation_enabled: 'NO',
ai_text_generation_model: '',
})
}
</script>
<template>
<BaseWizardStep
:title="$t('settings.ai.installer_title')"
:description="$t('settings.ai.installer_description')"
>
<div v-if="configData">
<AiConfigurationForm
:config-data="configData"
:drivers="drivers"
:is-saving="isSaving"
:is-fetching-initial-data="isFetchingInitialData"
@submit-data="saveAi"
/>
<div class="mt-6">
<BaseButton
variant="primary-outline"
type="button"
:disabled="isSaving"
@click="skipStep"
>
{{ $t('general.skip') }}
</BaseButton>
</div>
</div>
</BaseWizardStep>
</template>
@@ -51,7 +51,7 @@ async function saveMailConfig(value: MailConfig): Promise<void> {
...value,
}
await router.push({ name: 'installation.ai' })
await router.push({ name: 'installation.account' })
} catch (error: unknown) {
showRequestError(error)
} finally {
@@ -1,194 +0,0 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useModalStore } from '@/scripts/stores/modal.store'
import { useNotificationStore } from '@/scripts/stores/notification.store'
import { aiService } from '@/scripts/api/services/ai.service'
/**
* One-shot text generation popup for WYSIWYG editors.
*
* Usage pattern — a caller opens this modal via modalStore and passes data with:
* - currentContent: string // the editor's current HTML (used as optional context)
* - onInsert: (text: string) => void // invoked when the user accepts "Insert"
* - onReplace: (text: string) => void // invoked when the user accepts "Replace"
*
* See RichEditor.vue for the canonical caller. The modal doesn't know
* anything about tiptap or ProseMirror — it just hands back the text it got
* from the backend and lets the caller decide how to splice it into the editor.
*/
interface ModalData {
currentContent?: string
onInsert?: (text: string) => void
onReplace?: (text: string) => void
}
const { t } = useI18n()
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const modalActive = computed<boolean>(
() => modalStore.active && modalStore.componentName === 'AiTextGenerationModal',
)
const data = computed<ModalData>(() => (modalStore.data as ModalData) ?? {})
const prompt = ref<string>('')
const useContext = ref<boolean>(false)
const generatedText = ref<string>('')
const isGenerating = ref<boolean>(false)
const canInsert = computed<boolean>(() => generatedText.value.trim() !== '')
async function generate(): Promise<void> {
if (!prompt.value.trim() || isGenerating.value) return
isGenerating.value = true
generatedText.value = ''
try {
const response = await aiService.generateText({
prompt: prompt.value,
context: useContext.value ? data.value.currentContent : undefined,
})
if (response.text !== undefined) {
generatedText.value = response.text
} else if (response.error) {
notificationStore.showNotification({
type: 'error',
message: t('settings.ai.errors.' + response.error, { error: response.message ?? '' }),
})
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Unknown error'
notificationStore.showNotification({ type: 'error', message })
} finally {
isGenerating.value = false
}
}
function insert(): void {
data.value.onInsert?.(generatedText.value)
close()
}
function replace(): void {
data.value.onReplace?.(generatedText.value)
close()
}
function close(): void {
modalStore.closeModal()
setTimeout(() => {
prompt.value = ''
generatedText.value = ''
useContext.value = false
}, 200)
}
</script>
<template>
<BaseModal :show="modalActive" @close="close">
<template #header>
<div class="flex items-center justify-between w-full">
<div class="flex items-center gap-2">
<BaseIcon name="SparklesIcon" class="w-5 h-5 text-primary-500" />
<span>{{ $t('ai.generate.title') }}</span>
</div>
<BaseIcon
name="XMarkIcon"
class="w-6 h-6 text-muted cursor-pointer"
@click="close"
/>
</div>
</template>
<div class="p-6 space-y-4">
<BaseInputGroup
:label="$t('ai.generate.prompt_label')"
:content-loading="false"
required
>
<BaseTextarea
v-model="prompt"
rows="3"
:placeholder="$t('ai.generate.prompt_placeholder')"
:disabled="isGenerating"
/>
</BaseInputGroup>
<div v-if="data.currentContent">
<BaseSwitch
v-model="useContext"
class="flex"
:label-right="$t('ai.generate.use_current_as_context')"
/>
<p class="mt-1 text-xs text-muted">
{{ $t('ai.generate.use_context_help') }}
</p>
</div>
<div v-if="generatedText" class="border border-line-default rounded-md p-3 bg-surface-secondary">
<p class="text-xs text-muted mb-2">{{ $t('ai.generate.preview') }}</p>
<p class="text-sm text-body whitespace-pre-wrap">{{ generatedText }}</p>
</div>
</div>
<div class="flex justify-end gap-2 p-4 border-t border-line-default">
<BaseButton
variant="primary-outline"
type="button"
:disabled="isGenerating"
@click="close"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
v-if="canInsert"
variant="primary-outline"
type="button"
:disabled="isGenerating"
@click="replace"
>
{{ $t('ai.generate.replace') }}
</BaseButton>
<BaseButton
v-if="canInsert"
variant="primary-outline"
type="button"
:disabled="isGenerating"
@click="generate"
>
{{ $t('ai.generate.regenerate') }}
</BaseButton>
<BaseButton
v-if="canInsert"
variant="primary"
type="button"
:disabled="isGenerating"
@click="insert"
>
{{ $t('ai.generate.insert') }}
</BaseButton>
<BaseButton
v-else
variant="primary"
type="button"
:loading="isGenerating"
:disabled="!prompt.trim() || isGenerating"
@click="generate"
>
<template #left="slotProps">
<BaseIcon v-if="!isGenerating" name="SparklesIcon" :class="slotProps.class" />
</template>
{{ $t('ai.generate.generate') }}
</BaseButton>
</div>
</BaseModal>
</template>
+2 -7
View File
@@ -23,11 +23,7 @@
</div>
</main>
<!-- AI chat drawer always mounted, visibility driven by the store -->
<AiChatDrawer v-if="globalStore.ai?.enabled && globalStore.ai?.chat_enabled" />
<!-- AI text generation modal triggered from any RichEditor's Sparkles button -->
<AiTextGenerationModal v-if="globalStore.ai?.enabled && globalStore.ai?.text_generation_enabled" />
<ExtensionSlot name="company-layout-overlays" />
</div>
<BaseGlobalLoader v-else />
@@ -45,8 +41,7 @@ import SiteHeader from './partials/SiteHeader.vue'
import SiteSidebar from './partials/SiteSidebar.vue'
import NotificationRoot from '@/scripts/components/notifications/NotificationRoot.vue'
import ImpersonationBanner from './partials/ImpersonationBanner.vue'
import AiChatDrawer from '@/scripts/features/company/ai/components/AiChatDrawer.vue'
import AiTextGenerationModal from '@/scripts/features/shared/ai/AiTextGenerationModal.vue'
import ExtensionSlot from '@/scripts/extensions/ExtensionSlot.vue'
interface RouteMeta {
ability?: string | string[]
@@ -99,27 +99,7 @@
/>
</li>
<!-- AI chat drawer trigger -->
<li
v-if="
!companyStore.isAdminMode &&
globalStore.ai?.enabled &&
globalStore.ai?.chat_enabled
"
class="ml-2"
>
<button
type="button"
class="
flex items-center justify-center w-8 h-8 md:w-9 md:h-9 rounded-lg
bg-white/20 hover:bg-white/30 text-white
"
:title="$t('ai.chat.title')"
@click="aiChatStore.toggle()"
>
<BaseIcon name="SparklesIcon" class="w-5 h-5" />
</button>
</li>
<ExtensionSlot name="header-actions" />
<!-- Company switcher -->
<li>
@@ -204,7 +184,6 @@ import { useAuthStore } from '@/scripts/stores/auth.store'
import { useUserStore } from '@/scripts/stores/user.store'
import { useGlobalStore } from '@/scripts/stores/global.store'
import { useCompanyStore } from '@/scripts/stores/company.store'
import { useAiChatStore } from '@/scripts/features/company/ai/stores/ai-chat.store'
import { useTheme } from '@/scripts/composables/use-theme'
import { ABILITIES } from '@/scripts/config/abilities'
import { THEME } from '@/scripts/config/constants'
@@ -212,6 +191,7 @@ import type { Theme } from '@/scripts/config/constants'
import CompanySwitcher from './CompanySwitcher.vue'
import GlobalSearchBar from './GlobalSearchBar.vue'
import MainLogo from '@/scripts/components/icons/MainLogo.vue'
import ExtensionSlot from '@/scripts/extensions/ExtensionSlot.vue'
interface ThemeOption {
value: Theme
@@ -222,7 +202,6 @@ const authStore = useAuthStore()
const userStore = useUserStore()
const globalStore = useGlobalStore()
const companyStore = useCompanyStore()
const aiChatStore = useAiChatStore()
const router = useRouter()
const { currentTheme, setTheme } = useTheme()
+62 -6
View File
@@ -17,6 +17,48 @@ const loadedLanguages = new Set<string>(['en'])
/** In-memory cache of loaded message objects keyed by locale. */
const languageCache = new Map<string, Record<string, unknown>>()
/** Messages registered by compiled modules. Kept separate from the lazy locale
* cache so a later locale import cannot overwrite module translations. */
const additionalMessages = new Map<string, Record<string, unknown>>()
let activeI18n: AppI18n | null = null
function isMessageObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/** Recursively merge locale trees so one module's `settings.*` keys never
* replace the host's complete `settings` namespace. */
export function mergeMessageObjects(
base: Record<string, unknown>,
incoming: Record<string, unknown>,
): Record<string, unknown> {
const merged = { ...base }
for (const [key, value] of Object.entries(incoming)) {
merged[key] = isMessageObject(value) && isMessageObject(merged[key])
? mergeMessageObjects(merged[key], value)
: value
}
return merged
}
export function registerAdditionalMessages(
messages: Record<string, Record<string, unknown>>,
): void {
for (const [locale, bundle] of Object.entries(messages)) {
additionalMessages.set(
locale,
mergeMessageObjects(additionalMessages.get(locale) ?? {}, bundle),
)
if (activeI18n) {
activeI18n.global.mergeLocaleMessage(locale, bundle)
}
}
}
/**
* Dynamically import a language JSON file for a given locale.
*/
@@ -40,7 +82,10 @@ async function loadLanguageMessages(
const mod: { default: Record<string, unknown> } = await import(
`../../../lang/${fileName}.json`
)
const messages = mod.default ?? mod
const messages = mergeMessageObjects(
mod.default ?? mod,
additionalMessages.get(locale) ?? {},
)
languageCache.set(locale, messages)
loadedLanguages.add(locale)
return messages
@@ -106,18 +151,29 @@ export type AppI18n = I18n<
export function createAppI18n(
extraMessages?: Record<string, Record<string, unknown>>
): AppI18n {
const messages: Record<string, Record<string, unknown>> = {
en: en as unknown as Record<string, unknown>,
...extraMessages,
const messages: Record<string, Record<string, unknown>> = {}
for (const [locale, bundle] of additionalMessages) {
messages[locale] = mergeMessageObjects(messages[locale] ?? {}, bundle)
}
for (const [locale, bundle] of Object.entries(extraMessages ?? {})) {
messages[locale] = mergeMessageObjects(messages[locale] ?? {}, bundle)
}
messages.en = mergeMessageObjects(
en as unknown as Record<string, unknown>,
messages.en ?? {},
)
const options: I18nOptions = {
legacy: false,
locale: 'en',
fallbackLocale: 'en',
globalInjection: true,
messages,
messages: messages as I18nOptions['messages'],
}
return createI18n(options) as AppI18n
activeI18n = createI18n(options) as AppI18n
return activeI18n
}
+21
View File
@@ -12,6 +12,7 @@ import * as localStore from '../utils/local-storage'
import type { Company } from '@/scripts/types/domain/company'
import type { Currency } from '@/scripts/types/domain/currency'
import type { ApiResponse } from '@/scripts/types/api'
import { emitCompanyChanged, emitCompanyChanging } from '@/scripts/extensions/runtime'
export const useCompanyStore = defineStore('company', () => {
// State
@@ -24,6 +25,14 @@ export const useCompanyStore = defineStore('company', () => {
// Actions
function setSelectedCompany(data: Company | null): void {
const previousCompanyId = selectedCompany.value?.id ?? null
const companyId = data?.id ?? null
const hasChanged = previousCompanyId !== companyId
if (hasChanged) {
emitCompanyChanging({ previousCompanyId, companyId })
}
if (data) {
localStore.set('selectedCompany', data.id)
localStore.remove('isAdminMode')
@@ -32,14 +41,26 @@ export const useCompanyStore = defineStore('company', () => {
localStore.remove('selectedCompany')
}
selectedCompany.value = data
if (hasChanged) {
emitCompanyChanged({ previousCompanyId, companyId })
}
}
function setAdminMode(enabled: boolean): void {
const previousCompanyId = selectedCompany.value?.id ?? null
if (enabled && previousCompanyId !== null) {
emitCompanyChanging({ previousCompanyId, companyId: null })
}
isAdminMode.value = enabled
if (enabled) {
localStore.set('isAdminMode', true)
localStore.remove('selectedCompany')
selectedCompany.value = null
if (previousCompanyId !== null) {
emitCompanyChanged({ previousCompanyId, companyId: null })
}
} else {
localStore.remove('isAdminMode')
}
+7 -13
View File
@@ -19,6 +19,7 @@ import { handleApiError } from '../utils/error-handling'
import * as localStore from '../utils/local-storage'
import type { Currency } from '@/scripts/types/domain/currency'
import type { Country } from '@/scripts/types/domain/customer'
import { emitBootstrapCompleted } from '@/scripts/extensions/runtime'
export const useGlobalStore = defineStore('global', () => {
// State
@@ -36,11 +37,6 @@ export const useGlobalStore = defineStore('global', () => {
const mainMenu = ref<MenuItem[]>([])
const settingMenu = ref<MenuItem[]>([])
const userMenu = ref<Array<{ title: string; link: string; icon: string; name: string }>>([])
const ai = ref<{ enabled: boolean; chat_enabled: boolean; text_generation_enabled: boolean }>({
enabled: false,
chat_enabled: false,
text_generation_enabled: false,
})
const isAppLoaded = ref<boolean>(false)
const isSidebarOpen = ref<boolean>(false)
const isSidebarCollapsed = ref<boolean>(localStore.getBoolean('sidebarCollapsed'))
@@ -69,12 +65,6 @@ export const useGlobalStore = defineStore('global', () => {
mainMenu.value = response.main_menu
settingMenu.value = response.setting_menu
userMenu.value = response.user_menu ?? []
ai.value = response.ai ?? {
enabled: false,
chat_enabled: false,
text_generation_enabled: false,
}
config.value = response.config
globalSettings.value = response.global_settings
@@ -123,7 +113,12 @@ export const useGlobalStore = defineStore('global', () => {
(userLang && userLang !== 'default' ? userLang : '') ||
(response.current_company_settings as Record<string, string>)?.language ||
'en'
await (window as Record<string, unknown>).loadLanguage?.(uiLanguage)
await window.loadLanguage?.(uiLanguage)
emitBootstrapCompleted({
adminMode: response.admin_mode === true,
companyId: response.current_company?.id ?? null,
})
return response
} catch (err: unknown) {
@@ -302,7 +297,6 @@ export const useGlobalStore = defineStore('global', () => {
mainMenu,
settingMenu,
userMenu,
ai,
isAppLoaded,
isSidebarOpen,
isSidebarCollapsed,
-96
View File
@@ -1,96 +0,0 @@
export interface AiSuggestedModel {
value: string
label: string
}
export interface AiDriverConfigField {
key: string
type: 'text' | 'select'
label: string
default?: string
options?: Array<{ label: string; value: string }>
visible_when?: Record<string, string>
}
export interface AiDriverOption {
value: string
label: string
website: string
default_base_url: string
supported_roles: string[]
suggested_models: AiSuggestedModel[]
config_fields: AiDriverConfigField[]
}
export interface AiDriversResponse {
ai_drivers: AiDriverOption[]
}
export interface AiConfig {
ai_enabled: 'YES' | 'NO'
ai_driver: string
ai_api_key: string
ai_base_url: string
ai_chat_enabled: 'YES' | 'NO'
ai_chat_model: string
ai_text_generation_enabled: 'YES' | 'NO'
ai_text_generation_model: string
}
export interface CompanyAiConfig extends AiConfig {
use_custom_ai_config: 'YES' | 'NO'
}
export interface AiTestPayload {
ai_driver: string
ai_api_key?: string
ai_base_url?: string
}
export interface AiTestResponse {
success?: boolean
error?: string
message?: string
details?: Record<string, unknown>
}
// --- Phase 2: chat types ---
export interface AiConversationSummary {
id: number
title: string | null
model: string | null
created_at: string
updated_at: string
}
export interface AiChatMessage {
id: number
role: 'user' | 'assistant'
content: string | null
created_at: string
}
export interface AiChatSendResponse {
conversation: AiConversationSummary
message: AiChatMessage
error?: string
}
export interface AiConversationDetail {
conversation: AiConversationSummary
messages: AiChatMessage[]
}
// --- Phase 3: text generation types ---
export interface AiGenerateRequest {
prompt: string
context?: string
}
export interface AiGenerateResponse {
text?: string
error?: string
message?: string
}
-41
View File
@@ -1,46 +1,5 @@
import { marked } from 'marked'
import DOMPurify from 'dompurify'
/**
* Render a markdown string to safe, sanitized HTML.
*
* Used by the AI chat drawer to render assistant responses. Even though
* the AI provider controls the immediate source of the content, the model
* can echo anything it's fed — including user input from earlier in the
* conversation or tool results from the database. We therefore parse
* markdown → HTML via marked and then sanitize the result with DOMPurify
* before handing it to Vue's v-html.
*
* Marked is configured with:
* - gfm: true — GitHub-flavored markdown (tables, fenced code,
* strikethrough, task lists). Matches what users
* already expect from any modern chat UI.
* - breaks: true — newlines become <br> so a single user-typed line
* break renders as a visual break without needing
* two trailing spaces.
* - async: false — force synchronous parsing so the caller doesn't
* have to await; marked defaults to returning a
* Promise when extensions are registered.
*
* DOMPurify is run in its default browser profile which strips <script>,
* event handlers, javascript: URLs, and every other HTML vector. We do
* NOT customize ALLOWED_TAGS because marked's output is already a
* conservative subset of HTML.
*/
export function renderMarkdown(source: string): string {
if (!source) {
return ''
}
const rawHtml = marked.parse(source, {
gfm: true,
breaks: true,
async: false,
}) as string
return DOMPurify.sanitize(rawHtml)
}
/**
* Sanitize a raw HTML string with DOMPurify's default browser profile
* (strips <script>, event handlers, javascript: URLs, and every other HTML