mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-07-16 22:05:20 +00:00
feat(ai): Phase 1 — provider configuration, installer step, admin + company settings
Foundation for the AI chatbot + text generation feature. Phase 1 is infrastructure only: driver plumbing, configuration storage with encrypted API keys, global vs per-company resolution, admin + company UI pages, and an optional installer wizard step. The chat assistant and text-generation WYSIWYG integration come in later phases.
**Driver plumbing (app/Support/Ai/)** — AiDriver abstract, AiDriverFactory, AiException, AiChatResponse DTO, OpenRouterDriver concrete implementation. OpenRouter is the OpenAI-compatible aggregator that unlocks hundreds of models behind one API key and one request shape — ideal as the default v1 driver. Drivers are extensible the same way exchange rate drivers are: the module Registry's generic registerDriver('ai', ...) machinery plus a typed Registry::registerAiDriver() convenience wrapper (shipped in the upstream invoiceshelf/modules package in a paired commit).
**AiConfigurationService** — mirrors MailConfigurationService shape but with one deliberate deviation: API keys are encrypted at the service layer via Crypt::encryptString before persistence. OpenRouter bearer tokens have much bigger blast radius than SMTP passwords. Same settings / company_settings tables, same global-vs-per-company pattern, same use_custom_ai_config override toggle. Resolution order: global ai_enabled must be YES, then the company either overrides via use_custom_ai_config=YES (and can opt out with ai_enabled=NO inside the override) or inherits the global config.
**Controllers** — Admin/Settings/AiConfigurationController (global CRUD + driver list + test connection), Company/Settings/CompanyAiConfigurationController (per-company override + test), Setup/AiConfigurationController (installer wizard step, skippable with explicit ai_enabled=NO). API key is always masked as '********' in GET responses — the frontend submits the placeholder back on save and the backend preserves the stored value.
**Installer wizard** — new optional step 7 'AI' between Mail and Account. Default OFF with a Skip button. MailView.vue now routes to installation.ai instead of installation.account; installation.ai then routes to installation.account. Step order comment updated in routes.ts.
**Admin + Company settings pages** — AdminAiConfigView (no toggle, always global) and AiConfigView (with use_custom_ai_config BaseSwitchSection that auto-saves OFF). Both share AiConfigurationForm which renders the driver selector, API key input with show/hide, driver-specific config_fields (base_url for OpenRouter), and per-role enable toggles with free-text model inputs backed by a datalist of suggested models from driver metadata.
**Bootstrap endpoint** — adds an ai block to the response: { enabled, chat_enabled, text_generation_enabled }. All three are booleans resolved through AiConfigurationService::resolveForCompany(). Never leaks the API key. Frontend feature flags read from bootstrapData.ai to decide whether to show Phase 2/3 UI.
**Bouncer ability** 'manage ai config' added to SettingsPolicy, gated on isSuperAdmin() (same pattern as manage email config, manage pdf config).
**Tests** (22 new) — Unit: AiDriverFactory resolves built-in + Registry-contributed drivers, rejects unknown, merges availableDrivers. AiConfigurationService: encryption round-trip, resolution order (3 cases: global off, inherit global, override with company key, override with opt-out), makeDriver null/instance cases, listDrivers metadata. Feature: admin save + read with api key masking, preserve-on-placeholder behavior, company toggle ON/OFF semantics, bootstrap ai flags reflect resolution, company opt-out path.
372 tests pass (was 350, +22). Pint clean. npm run build clean. Phase 2 (chat assistant + tool calling) and Phase 3 (WYSIWYG text generation popup) are separate follow-up commits — this one is the foundation only.
This commit is contained in:
@@ -115,6 +115,18 @@ 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',
|
||||
|
||||
// PDF Configuration
|
||||
PDF_DRIVERS: '/api/v1/pdf/drivers',
|
||||
PDF_CONFIG: '/api/v1/pdf/config',
|
||||
|
||||
51
resources/scripts/api/services/ai.service.ts
Normal file
51
resources/scripts/api/services/ai.service.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { client } from '../client'
|
||||
import { API } from '../endpoints'
|
||||
import type {
|
||||
AiConfig,
|
||||
AiDriversResponse,
|
||||
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
|
||||
},
|
||||
}
|
||||
@@ -29,6 +29,11 @@ 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<{
|
||||
|
||||
@@ -9,6 +9,7 @@ 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')
|
||||
@@ -87,6 +88,14 @@ 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',
|
||||
|
||||
@@ -73,6 +73,11 @@ 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',
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<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>
|
||||
@@ -0,0 +1,316 @@
|
||||
<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: 'openai/gpt-4o',
|
||||
ai_text_generation_enabled: 'NO',
|
||||
ai_text_generation_model: 'openai/gpt-4o-mini',
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -158,6 +158,15 @@ 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',
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
<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>
|
||||
@@ -15,9 +15,10 @@ import InstallationLayout from '@/scripts/layouts/InstallationLayout.vue'
|
||||
* 4. DatabaseView (/installation/database)
|
||||
* 5. DomainView (/installation/domain)
|
||||
* 6. MailView (/installation/mail)
|
||||
* 7. AccountView (/installation/account)
|
||||
* 8. CompanyView (/installation/company)
|
||||
* 9. PreferencesView (/installation/preferences)
|
||||
* 7. AiView (/installation/ai) — optional, skippable
|
||||
* 8. AccountView (/installation/account)
|
||||
* 9. CompanyView (/installation/company)
|
||||
* 10. 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 —
|
||||
@@ -90,6 +91,15 @@ 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',
|
||||
|
||||
100
resources/scripts/features/installation/views/AiView.vue
Normal file
100
resources/scripts/features/installation/views/AiView.vue
Normal file
@@ -0,0 +1,100 @@
|
||||
<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.account' })
|
||||
await router.push({ name: 'installation.ai' })
|
||||
} catch (error: unknown) {
|
||||
showRequestError(error)
|
||||
} finally {
|
||||
|
||||
55
resources/scripts/types/ai-config.ts
Normal file
55
resources/scripts/types/ai-config.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
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>
|
||||
}
|
||||
Reference in New Issue
Block a user