model-load-balancing-entry-modal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import type { FC } from 'react'
  2. import {
  3. memo,
  4. useCallback,
  5. useEffect,
  6. useMemo,
  7. useState,
  8. } from 'react'
  9. import { useTranslation } from 'react-i18next'
  10. import type {
  11. CredentialFormSchema,
  12. CredentialFormSchemaRadio,
  13. CredentialFormSchemaSelect,
  14. CredentialFormSchemaTextInput,
  15. CustomConfigurationModelFixedFields,
  16. FormValue,
  17. ModelLoadBalancingConfigEntry,
  18. ModelProvider,
  19. } from '../declarations'
  20. import {
  21. ConfigurationMethodEnum,
  22. FormTypeEnum,
  23. } from '../declarations'
  24. import {
  25. useLanguage,
  26. } from '../hooks'
  27. import { useValidate } from '../../key-validator/hooks'
  28. import { ValidatedStatus } from '../../key-validator/declarations'
  29. import { validateLoadBalancingCredentials } from '../utils'
  30. import Form from './Form'
  31. import Button from '@/app/components/base/button'
  32. import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
  33. import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'
  34. import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  35. import {
  36. PortalToFollowElem,
  37. PortalToFollowElemContent,
  38. } from '@/app/components/base/portal-to-follow-elem'
  39. import { useToastContext } from '@/app/components/base/toast'
  40. import ConfirmCommon from '@/app/components/base/confirm/common'
  41. type ModelModalProps = {
  42. provider: ModelProvider
  43. configurationMethod: ConfigurationMethodEnum
  44. currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields
  45. entry?: ModelLoadBalancingConfigEntry
  46. onCancel: () => void
  47. onSave: (entry: ModelLoadBalancingConfigEntry) => void
  48. onRemove: () => void
  49. }
  50. const ModelLoadBalancingEntryModal: FC<ModelModalProps> = ({
  51. provider,
  52. configurationMethod,
  53. currentCustomConfigurationModelFixedFields,
  54. entry,
  55. onCancel,
  56. onSave,
  57. onRemove,
  58. }) => {
  59. const providerFormSchemaPredefined = configurationMethod === ConfigurationMethodEnum.predefinedModel
  60. // const { credentials: formSchemasValue } = useProviderCredentialsAndLoadBalancing(
  61. // provider.provider,
  62. // configurationMethod,
  63. // providerFormSchemaPredefined && provider.custom_configuration.status === CustomConfigurationStatusEnum.active,
  64. // currentCustomConfigurationModelFixedFields,
  65. // )
  66. const isEditMode = !!entry
  67. const { t } = useTranslation()
  68. const { notify } = useToastContext()
  69. const language = useLanguage()
  70. const [loading, setLoading] = useState(false)
  71. const [showConfirm, setShowConfirm] = useState(false)
  72. const formSchemas = useMemo(() => {
  73. return [
  74. {
  75. type: FormTypeEnum.textInput,
  76. label: {
  77. en_US: 'Config Name',
  78. zh_Hans: '配置名称',
  79. },
  80. variable: 'name',
  81. required: true,
  82. show_on: [],
  83. placeholder: {
  84. en_US: 'Enter your Config Name here',
  85. zh_Hans: '输入配置名称',
  86. },
  87. } as CredentialFormSchemaTextInput,
  88. ...(
  89. providerFormSchemaPredefined
  90. ? provider.provider_credential_schema.credential_form_schemas
  91. : provider.model_credential_schema.credential_form_schemas
  92. ),
  93. ]
  94. }, [
  95. providerFormSchemaPredefined,
  96. provider.provider_credential_schema?.credential_form_schemas,
  97. provider.model_credential_schema?.credential_form_schemas,
  98. ])
  99. const [
  100. requiredFormSchemas,
  101. secretFormSchemas,
  102. defaultFormSchemaValue,
  103. showOnVariableMap,
  104. ] = useMemo(() => {
  105. const requiredFormSchemas: CredentialFormSchema[] = []
  106. const secretFormSchemas: CredentialFormSchema[] = []
  107. const defaultFormSchemaValue: Record<string, string | number> = {}
  108. const showOnVariableMap: Record<string, string[]> = {}
  109. formSchemas.forEach((formSchema) => {
  110. if (formSchema.required)
  111. requiredFormSchemas.push(formSchema)
  112. if (formSchema.type === FormTypeEnum.secretInput)
  113. secretFormSchemas.push(formSchema)
  114. if (formSchema.default)
  115. defaultFormSchemaValue[formSchema.variable] = formSchema.default
  116. if (formSchema.show_on.length) {
  117. formSchema.show_on.forEach((showOnItem) => {
  118. if (!showOnVariableMap[showOnItem.variable])
  119. showOnVariableMap[showOnItem.variable] = []
  120. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  121. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  122. })
  123. }
  124. if (formSchema.type === FormTypeEnum.select || formSchema.type === FormTypeEnum.radio) {
  125. (formSchema as (CredentialFormSchemaRadio | CredentialFormSchemaSelect)).options.forEach((option) => {
  126. if (option.show_on.length) {
  127. option.show_on.forEach((showOnItem) => {
  128. if (!showOnVariableMap[showOnItem.variable])
  129. showOnVariableMap[showOnItem.variable] = []
  130. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  131. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  132. })
  133. }
  134. })
  135. }
  136. })
  137. return [
  138. requiredFormSchemas,
  139. secretFormSchemas,
  140. defaultFormSchemaValue,
  141. showOnVariableMap,
  142. ]
  143. }, [formSchemas])
  144. const [initialValue, setInitialValue] = useState<ModelLoadBalancingConfigEntry['credentials']>()
  145. useEffect(() => {
  146. if (entry && !initialValue) {
  147. setInitialValue({
  148. ...defaultFormSchemaValue,
  149. ...entry.credentials,
  150. id: entry.id,
  151. name: entry.name,
  152. } as Record<string, string | undefined | boolean>)
  153. }
  154. }, [entry, defaultFormSchemaValue, initialValue])
  155. const formSchemasValue = useMemo(() => ({
  156. ...currentCustomConfigurationModelFixedFields,
  157. ...initialValue,
  158. }), [currentCustomConfigurationModelFixedFields, initialValue])
  159. const initialFormSchemasValue: Record<string, string | number> = useMemo(() => {
  160. return {
  161. ...defaultFormSchemaValue,
  162. ...formSchemasValue,
  163. } as Record<string, string | number>
  164. }, [formSchemasValue, defaultFormSchemaValue])
  165. const [value, setValue] = useState(initialFormSchemasValue)
  166. useEffect(() => {
  167. setValue(initialFormSchemasValue)
  168. }, [initialFormSchemasValue])
  169. const [_, validating, validatedStatusState] = useValidate(value)
  170. const filteredRequiredFormSchemas = requiredFormSchemas.filter((requiredFormSchema) => {
  171. if (requiredFormSchema.show_on.length && requiredFormSchema.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value))
  172. return true
  173. if (!requiredFormSchema.show_on.length)
  174. return true
  175. return false
  176. })
  177. const getSecretValues = useCallback((v: FormValue) => {
  178. return secretFormSchemas.reduce((prev, next) => {
  179. if (v[next.variable] === initialFormSchemasValue[next.variable])
  180. prev[next.variable] = '[__HIDDEN__]'
  181. return prev
  182. }, {} as Record<string, string>)
  183. }, [initialFormSchemasValue, secretFormSchemas])
  184. // const handleValueChange = ({ __model_type, __model_name, ...v }: FormValue) => {
  185. const handleValueChange = (v: FormValue) => {
  186. setValue(v)
  187. }
  188. const handleSave = async () => {
  189. try {
  190. setLoading(true)
  191. const res = await validateLoadBalancingCredentials(
  192. providerFormSchemaPredefined,
  193. provider.provider,
  194. {
  195. ...value,
  196. ...getSecretValues(value),
  197. },
  198. )
  199. if (res.status === ValidatedStatus.Success) {
  200. // notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  201. const { __model_type, __model_name, name, ...credentials } = value
  202. onSave({
  203. ...(entry || {}),
  204. name: name as string,
  205. credentials: credentials as Record<string, string | boolean | undefined>,
  206. })
  207. // onCancel()
  208. }
  209. else {
  210. notify({ type: 'error', message: res.message || '' })
  211. }
  212. }
  213. finally {
  214. setLoading(false)
  215. }
  216. }
  217. const handleRemove = () => {
  218. onRemove?.()
  219. }
  220. return (
  221. <PortalToFollowElem open>
  222. <PortalToFollowElemContent className='w-full h-full z-[60]'>
  223. <div className='fixed inset-0 flex items-center justify-center bg-black/[.25]'>
  224. <div className='mx-2 w-[640px] max-h-[calc(100vh-120px)] bg-white shadow-xl rounded-2xl overflow-y-auto'>
  225. <div className='px-8 pt-8'>
  226. <div className='flex justify-between items-center mb-2'>
  227. <div className='text-xl font-semibold text-gray-900'>{t(isEditMode ? 'common.modelProvider.editConfig' : 'common.modelProvider.addConfig')}</div>
  228. </div>
  229. <Form
  230. value={value}
  231. onChange={handleValueChange}
  232. formSchemas={formSchemas}
  233. validating={validating}
  234. validatedSuccess={validatedStatusState.status === ValidatedStatus.Success}
  235. showOnVariableMap={showOnVariableMap}
  236. isEditMode={isEditMode}
  237. />
  238. <div className='sticky bottom-0 flex justify-between items-center py-6 flex-wrap gap-y-2 bg-white'>
  239. {
  240. (provider.help && (provider.help.title || provider.help.url))
  241. ? (
  242. <a
  243. href={provider.help?.url[language] || provider.help?.url.en_US}
  244. target='_blank' rel='noopener noreferrer'
  245. className='inline-flex items-center text-xs text-primary-600'
  246. onClick={e => !provider.help.url && e.preventDefault()}
  247. >
  248. {provider.help.title?.[language] || provider.help.url[language] || provider.help.title?.en_US || provider.help.url.en_US}
  249. <LinkExternal02 className='ml-1 w-3 h-3' />
  250. </a>
  251. )
  252. : <div />
  253. }
  254. <div>
  255. {
  256. isEditMode && (
  257. <Button
  258. className='mr-2 h-9 text-sm font-medium text-[#D92D20]'
  259. onClick={() => setShowConfirm(true)}
  260. >
  261. {t('common.operation.remove')}
  262. </Button>
  263. )
  264. }
  265. <Button
  266. className='mr-2 h-9 text-sm font-medium text-gray-700'
  267. onClick={onCancel}
  268. >
  269. {t('common.operation.cancel')}
  270. </Button>
  271. <Button
  272. className='h-9 text-sm font-medium'
  273. variant='primary'
  274. onClick={handleSave}
  275. disabled={loading || filteredRequiredFormSchemas.some(item => value[item.variable] === undefined)}
  276. >
  277. {t('common.operation.save')}
  278. </Button>
  279. </div>
  280. </div>
  281. </div>
  282. <div className='border-t-[0.5px] border-t-black/5'>
  283. {
  284. (validatedStatusState.status === ValidatedStatus.Error && validatedStatusState.message)
  285. ? (
  286. <div className='flex px-[10px] py-3 bg-[#FEF3F2] text-xs text-[#D92D20]'>
  287. <AlertCircle className='mt-[1px] mr-2 w-[14px] h-[14px]' />
  288. {validatedStatusState.message}
  289. </div>
  290. )
  291. : (
  292. <div className='flex justify-center items-center py-3 bg-gray-50 text-xs text-gray-500'>
  293. <Lock01 className='mr-1 w-3 h-3 text-gray-500' />
  294. {t('common.modelProvider.encrypted.front')}
  295. <a
  296. className='text-primary-600 mx-1'
  297. target='_blank' rel='noopener noreferrer'
  298. href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
  299. >
  300. PKCS1_OAEP
  301. </a>
  302. {t('common.modelProvider.encrypted.back')}
  303. </div>
  304. )
  305. }
  306. </div>
  307. </div>
  308. {
  309. showConfirm && (
  310. <ConfirmCommon
  311. title={t('common.modelProvider.confirmDelete')}
  312. isShow={showConfirm}
  313. onCancel={() => setShowConfirm(false)}
  314. onConfirm={handleRemove}
  315. confirmWrapperClassName='z-[70]'
  316. />
  317. )
  318. }
  319. </div>
  320. </PortalToFollowElemContent>
  321. </PortalToFollowElem>
  322. )
  323. }
  324. export default memo(ModelLoadBalancingEntryModal)