import type { FC } from 'react' import { memo, useCallback, useEffect, useMemo, useState, } from 'react' import { useTranslation } from 'react-i18next' import type { CredentialFormSchema, CredentialFormSchemaRadio, CredentialFormSchemaSelect, CustomConfigrationModelFixedFields, FormValue, ModelProvider, } from '../declarations' import { ConfigurateMethodEnum, CustomConfigurationStatusEnum, FormTypeEnum, } from '../declarations' import { genModelNameFormSchema, genModelTypeFormSchema, removeCredentials, saveCredentials, } from '../utils' import { useLanguage, useProviderCrenditialsFormSchemasValue, } from '../hooks' import ProviderIcon from '../provider-icon' import { useValidate } from '../../key-validator/hooks' import { ValidatedStatus } from '../../key-validator/declarations' import Form from './Form' import Button from '@/app/components/base/button' import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security' import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general' import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback' import { PortalToFollowElem, PortalToFollowElemContent, } from '@/app/components/base/portal-to-follow-elem' import { useToastContext } from '@/app/components/base/toast' import ConfirmCommon from '@/app/components/base/confirm/common' type ModelModalProps = { provider: ModelProvider configurateMethod: ConfigurateMethodEnum currentCustomConfigrationModelFixedFields?: CustomConfigrationModelFixedFields onCancel: () => void onSave: () => void } const ModelModal: FC = ({ provider, configurateMethod, currentCustomConfigrationModelFixedFields, onCancel, onSave, }) => { const providerFormSchemaPredefined = configurateMethod === ConfigurateMethodEnum.predefinedModel const formSchemasValue = useProviderCrenditialsFormSchemasValue( provider.provider, configurateMethod, providerFormSchemaPredefined && provider.custom_configuration.status === CustomConfigurationStatusEnum.active, currentCustomConfigrationModelFixedFields, ) const isEditMode = !!formSchemasValue const { t } = useTranslation() const { notify } = useToastContext() const language = useLanguage() const [loading, setLoading] = useState(false) const [showConfirm, setShowConfirm] = useState(false) const formSchemas = useMemo(() => { return providerFormSchemaPredefined ? provider.provider_credential_schema.credential_form_schemas : [ genModelTypeFormSchema(provider.supported_model_types), genModelNameFormSchema(provider.model_credential_schema?.model), ...provider.model_credential_schema.credential_form_schemas, ] }, [ providerFormSchemaPredefined, provider.provider_credential_schema?.credential_form_schemas, provider.supported_model_types, provider.model_credential_schema?.credential_form_schemas, provider.model_credential_schema?.model, ]) const [ requiredFormSchemas, secretFormSchemas, defaultFormSchemaValue, showOnVariableMap, ] = useMemo(() => { const requiredFormSchemas: CredentialFormSchema[] = [] const secretFormSchemas: CredentialFormSchema[] = [] const defaultFormSchemaValue: Record = {} const showOnVariableMap: Record = {} formSchemas.forEach((formSchema) => { if (formSchema.required) requiredFormSchemas.push(formSchema) if (formSchema.type === FormTypeEnum.secretInput) secretFormSchemas.push(formSchema) if (formSchema.default) defaultFormSchemaValue[formSchema.variable] = formSchema.default if (formSchema.show_on.length) { formSchema.show_on.forEach((showOnItem) => { if (!showOnVariableMap[showOnItem.variable]) showOnVariableMap[showOnItem.variable] = [] if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable)) showOnVariableMap[showOnItem.variable].push(formSchema.variable) }) } if (formSchema.type === FormTypeEnum.select || formSchema.type === FormTypeEnum.radio) { (formSchema as (CredentialFormSchemaRadio | CredentialFormSchemaSelect)).options.forEach((option) => { if (option.show_on.length) { option.show_on.forEach((showOnItem) => { if (!showOnVariableMap[showOnItem.variable]) showOnVariableMap[showOnItem.variable] = [] if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable)) showOnVariableMap[showOnItem.variable].push(formSchema.variable) }) } }) } }) return [ requiredFormSchemas, secretFormSchemas, defaultFormSchemaValue, showOnVariableMap, ] }, [formSchemas]) const initialFormSchemasValue = useMemo(() => { return { ...defaultFormSchemaValue, ...formSchemasValue, } }, [formSchemasValue, defaultFormSchemaValue]) const [value, setValue] = useState(initialFormSchemasValue) useEffect(() => { setValue(initialFormSchemasValue) }, [initialFormSchemasValue]) const [validate, validating, validatedStatusState] = useValidate(value) const filteredRequiredFormSchemas = requiredFormSchemas.filter((requiredFormSchema) => { if (requiredFormSchema.show_on.length && requiredFormSchema.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value)) return true if (!requiredFormSchema.show_on.length) return true return false }) const getSecretValues = useCallback((v: FormValue) => { return secretFormSchemas.reduce((prev, next) => { if (v[next.variable] === initialFormSchemasValue[next.variable]) prev[next.variable] = '[__HIDDEN__]' return prev }, {} as Record) }, [initialFormSchemasValue, secretFormSchemas]) const handleValueChange = (v: FormValue) => { setValue(v) } const handleSave = async () => { try { setLoading(true) const res = await saveCredentials( providerFormSchemaPredefined, provider.provider, { ...value, ...getSecretValues(value), }, ) if (res.result === 'success') { notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') }) onSave() onCancel() } } finally { setLoading(false) } } const handleRemove = async () => { try { setLoading(true) const res = await removeCredentials( providerFormSchemaPredefined, provider.provider, value, ) if (res.result === 'success') { notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') }) onSave() onCancel() } } finally { setLoading(false) } } const renderTitlePrefix = () => { const prefix = configurateMethod === ConfigurateMethodEnum.customizableModel ? t('common.operation.add') : t('common.operation.setup') return `${prefix} ${provider.label[language]}` } return (
{renderTitlePrefix()}
{ (provider.help && (provider.help.title || provider.help.url)) ? ( !provider.help.url && e.preventDefault()} > {provider.help.title?.[language] || provider.help.url[language]} ) :
}
{ isEditMode && ( ) }
{ (validatedStatusState.status === ValidatedStatus.Error && validatedStatusState.message) ? (
{validatedStatusState.message}
) : (
{t('common.modelProvider.encrypted.front')} PKCS1_OAEP {t('common.modelProvider.encrypted.back')}
) }
{ showConfirm && ( setShowConfirm(false)} onConfirm={handleRemove} confirmWrapperClassName='z-[70]' /> ) }
) } export default memo(ModelModal)