import type { FC } from 'react' import { memo, useCallback, useEffect, useMemo, useState, } from 'react' import { useTranslation } from 'react-i18next' import { RiErrorWarningFill, } from '@remixicon/react' import type { CredentialFormSchema, CredentialFormSchemaRadio, CredentialFormSchemaSelect, CredentialFormSchemaTextInput, CustomConfigurationModelFixedFields, FormValue, ModelLoadBalancingConfigEntry, ModelProvider, } from '../declarations' import { ConfigurationMethodEnum, FormTypeEnum, } from '../declarations' import { useLanguage, } from '../hooks' import { useValidate } from '../../key-validator/hooks' import { ValidatedStatus } from '../../key-validator/declarations' import { validateLoadBalancingCredentials } from '../utils' 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 { PortalToFollowElem, PortalToFollowElemContent, } from '@/app/components/base/portal-to-follow-elem' import { useToastContext } from '@/app/components/base/toast' import Confirm from '@/app/components/base/confirm' type ModelModalProps = { provider: ModelProvider configurationMethod: ConfigurationMethodEnum currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields entry?: ModelLoadBalancingConfigEntry onCancel: () => void onSave: (entry: ModelLoadBalancingConfigEntry) => void onRemove: () => void } const ModelLoadBalancingEntryModal: FC = ({ provider, configurationMethod, currentCustomConfigurationModelFixedFields, entry, onCancel, onSave, onRemove, }) => { const providerFormSchemaPredefined = configurationMethod === ConfigurationMethodEnum.predefinedModel // const { credentials: formSchemasValue } = useProviderCredentialsAndLoadBalancing( // provider.provider, // configurationMethod, // providerFormSchemaPredefined && provider.custom_configuration.status === CustomConfigurationStatusEnum.active, // currentCustomConfigurationModelFixedFields, // ) const isEditMode = !!entry const { t } = useTranslation() const { notify } = useToastContext() const language = useLanguage() const [loading, setLoading] = useState(false) const [showConfirm, setShowConfirm] = useState(false) const formSchemas = useMemo(() => { return [ { type: FormTypeEnum.textInput, label: { en_US: 'Config Name', zh_Hans: '配置名称', }, variable: 'name', required: true, show_on: [], placeholder: { en_US: 'Enter your Config Name here', zh_Hans: '输入配置名称', }, } as CredentialFormSchemaTextInput, ...( providerFormSchemaPredefined ? provider.provider_credential_schema.credential_form_schemas : provider.model_credential_schema.credential_form_schemas ), ] }, [ providerFormSchemaPredefined, provider.provider_credential_schema?.credential_form_schemas, provider.model_credential_schema?.credential_form_schemas, ]) 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 [initialValue, setInitialValue] = useState() useEffect(() => { if (entry && !initialValue) { setInitialValue({ ...defaultFormSchemaValue, ...entry.credentials, id: entry.id, name: entry.name, } as Record) } }, [entry, defaultFormSchemaValue, initialValue]) const formSchemasValue = useMemo(() => ({ ...currentCustomConfigurationModelFixedFields, ...initialValue, }), [currentCustomConfigurationModelFixedFields, initialValue]) const initialFormSchemasValue: Record = useMemo(() => { return { ...defaultFormSchemaValue, ...formSchemasValue, } as Record }, [formSchemasValue, defaultFormSchemaValue]) const [value, setValue] = useState(initialFormSchemasValue) useEffect(() => { setValue(initialFormSchemasValue) }, [initialFormSchemasValue]) const [_, 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 (isEditMode && v[next.variable] && v[next.variable] === initialFormSchemasValue[next.variable]) prev[next.variable] = '[__HIDDEN__]' return prev }, {} as Record) }, [initialFormSchemasValue, isEditMode, secretFormSchemas]) // const handleValueChange = ({ __model_type, __model_name, ...v }: FormValue) => { const handleValueChange = (v: FormValue) => { setValue(v) } const handleSave = async () => { try { setLoading(true) const res = await validateLoadBalancingCredentials( providerFormSchemaPredefined, provider.provider, { ...value, ...getSecretValues(value), }, entry?.id, ) if (res.status === ValidatedStatus.Success) { // notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') }) const { __model_type, __model_name, name, ...credentials } = value onSave({ ...(entry || {}), name: name as string, credentials: credentials as Record, }) // onCancel() } else { notify({ type: 'error', message: res.message || '' }) } } finally { setLoading(false) } } const handleRemove = () => { onRemove?.() } return (
{t(isEditMode ? 'common.modelProvider.editConfig' : 'common.modelProvider.addConfig')}
{ (provider.help && (provider.help.title || provider.help.url)) ? ( !provider.help.url && e.preventDefault()} > {provider.help.title?.[language] || provider.help.url[language] || provider.help.title?.en_US || provider.help.url.en_US} ) :
}
{ 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} /> ) }
) } export default memo(ModelLoadBalancingEntryModal)