Initial commit

This commit is contained in:
John Wang
2023-05-15 08:51:32 +08:00
commit db896255d6
744 changed files with 56028 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
.google-icon {
background: url(../../assets/google.svg) center center no-repeat;
background-size: 16px 16px;
}
.github-icon {
background: url(../../assets/github.svg) center center no-repeat;
background-size: 16px 16px;
}
.twitter-icon {
background: url(../../assets/twitter.svg) center center no-repeat;
background-size: 16px 16px;
}
.bitbucket-icon {
background: url(../../assets/bitbucket.svg) center center no-repeat;
background-size: 16px 16px;
}
.salesforce-icon {
background: url(../../assets/salesforce.svg) center center no-repeat;
background-size: 24px auto;
}

View File

@@ -0,0 +1,74 @@
'use client'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'
import s from './index.module.css'
import useSWR from 'swr'
import Link from 'next/link'
import { fetchAccountIntegrates } from '@/service/common'
const titleClassName = `
mb-2 text-sm font-medium text-gray-900
`
export default function IntegrationsPage() {
const { t } = useTranslation()
const integrateMap = {
google: {
name: t('common.integrations.google'),
description: t('common.integrations.googleAccount'),
},
github: {
name: t('common.integrations.github'),
description: t('common.integrations.githubAccount'),
},
}
const { data } = useSWR({ url: '/account/integrates' }, fetchAccountIntegrates)
const integrates = data?.data?.length ? data.data : []
return (
<>
<div className='mb-8'>
<div className={titleClassName}>{t('common.integrations.connected')}</div>
{
integrates.map(integrate => (
<div key={integrate.provider} className='mb-2 flex items-center px-3 py-2 bg-gray-50 border-[0.5px] border-gray-200 rounded-lg'>
<div className={classNames('w-8 h-8 mr-3 bg-white rounded-lg border border-gray-100', s[`${integrate.provider}-icon`])} />
<div className='grow'>
<div className='leading-[21px] text-sm font-medium text-gray-800'>{integrateMap[integrate.provider].name}</div>
<div className='leading-[18px] text-xs font-normal text-gray-500'>{integrateMap[integrate.provider].description}</div>
</div>
{
!integrate.is_bound && (
<Link
className='flex items-center h-8 px-[7px] bg-white rounded-lg border border-gray-200 text-xs font-medium text-gray-700 cursor-pointer'
href={integrate.link}
target={'_blank'}>
{t('common.integrations.connect')}
</Link>
)
}
</div>
))
}
</div>
{/* <div className='mb-8'>
<div className={titleClassName}>Add a service </div>
{
services.map(service => (
<div key={service.key} className='mb-2 flex items-center px-3 py-2 bg-gray-50 border-[0.5px] border-gray-200 rounded-lg'>
<div className={classNames('w-8 h-8 mr-3 bg-white rounded-lg border border-gray-100', s[`${service.key}-icon`])} />
<div className='grow'>
<div className='leading-[21px] text-sm font-medium text-gray-800'>{service.name}</div>
<div className='leading-[18px] text-xs font-normal text-gray-500'>{service.description}</div>
</div>
<Button className='text-xs font-medium text-gray-800'>Connect</Button>
</div>
))
}
</div> */}
</>
)
}

View File

@@ -0,0 +1,4 @@
.modal {
padding: 24px 32px !important;
width: 400px !important;
}

View File

@@ -0,0 +1,130 @@
'use client'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'
import { useContext } from 'use-context-selector'
import Collapse from '../collapse'
import type { IItem } from '../collapse'
import s from './index.module.css'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import { updateUserProfile } from '@/service/common'
import { useAppContext } from '@/context/app-context'
import { ToastContext } from '@/app/components/base/toast'
import AppIcon from '@/app/components/base/app-icon'
import Avatar from '@/app/components/base/avatar'
const titleClassName = `
text-sm font-medium text-gray-900
`
const descriptionClassName = `
mt-1 text-xs font-normal text-gray-500
`
const inputClassName = `
mt-2 w-full px-3 py-2 bg-gray-100 rounded
text-sm font-normal text-gray-800
`
export default function AccountPage() {
const { mutateUserProfile, userProfile, apps } = useAppContext()
const { notify } = useContext(ToastContext)
const [editNameModalVisible, setEditNameModalVisible] = useState(false)
const [editName, setEditName] = useState('')
const [editing, setEditing] = useState(false)
const { t } = useTranslation()
const handleEditName = () => {
setEditNameModalVisible(true)
setEditName(userProfile.name)
}
const handleSaveName = async () => {
try {
setEditing(true)
await updateUserProfile({ url: 'account/name', body: { name: editName } })
notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
mutateUserProfile()
setEditNameModalVisible(false)
setEditing(false)
}
catch (e) {
notify({ type: 'error', message: (e as Error).message })
setEditNameModalVisible(false)
setEditing(false)
}
}
const renderAppItem = (item: IItem) => {
return (
<div className='flex px-3 py-1'>
<div className='mr-3'>
<AppIcon size='tiny' />
</div>
<div className='mt-[3px] text-xs font-medium text-gray-700 leading-[18px]'>{item.name}</div>
</div>
)
}
return (
<>
<div className='mb-8'>
<div className={titleClassName}>{t('common.account.avatar')}</div>
<Avatar name={userProfile.name} size={64} className='mt-2' />
</div>
<div className='mb-8'>
<div className={titleClassName}>{t('common.account.name')}</div>
<div className={classNames('flex items-center justify-between mt-2 w-full h-9 px-3 bg-gray-100 rounded text-sm font-normal text-gray-800 cursor-pointer group')}>
{userProfile.name}
<div className='items-center hidden h-6 px-2 text-xs font-normal bg-white border border-gray-200 rounded-md group-hover:flex' onClick={handleEditName}>{t('common.operation.edit')}</div>
</div>
</div>
<div className='mb-8'>
<div className={titleClassName}>{t('common.account.email')}</div>
<div className={classNames(inputClassName, 'cursor-pointer')}>{userProfile.email}</div>
</div>
{
!!apps.length && (
<>
<div className='mb-6 border-[0.5px] border-gray-100' />
<div className='mb-8'>
<div className={titleClassName}>{t('common.account.langGeniusAccount')}</div>
<div className={descriptionClassName}>{t('common.account.langGeniusAccountTip')}</div>
<Collapse
title={`${t('common.account.showAppLength', { length: apps.length })}`}
items={apps.map(app => ({ key: app.id, name: app.name }))}
renderItem={renderAppItem}
wrapperClassName='mt-2'
/>
</div>
</>
)
}
{
editNameModalVisible && (
<Modal
isShow
onClose={() => setEditNameModalVisible(false)}
className={s.modal}
>
<div className='mb-6 text-lg font-medium text-gray-900'>{t('common.account.editName')}</div>
<div className={titleClassName}>{t('common.account.name')}</div>
<input
className={inputClassName}
value={editName}
onChange={e => setEditName(e.target.value)}
/>
<div className='flex justify-end mt-10'>
<Button className='mr-2 text-sm font-medium' onClick={() => setEditNameModalVisible(false)}>{t('common.operation.cancel')}</Button>
<Button
disabled={editing || !editName}
type='primary'
className='text-sm font-medium'
onClick={handleSaveName}
>
{t('common.operation.save')}
</Button>
</div>
</Modal>
)
}
</>
)
}

View File

@@ -0,0 +1,54 @@
import { useState } from 'react'
import { ChevronDownIcon, ChevronRightIcon } from '@heroicons/react/24/outline'
import classNames from 'classnames'
export type IItem = {
key: string
name: string
}
type ICollapse = {
title: string | undefined
items: IItem[]
renderItem: (item: IItem) => React.ReactNode
onSelect?: (item: IItem) => void
wrapperClassName?: string
}
const Collapse = ({
title,
items,
renderItem,
onSelect,
wrapperClassName,
}: ICollapse) => {
const [open, setOpen] = useState(false)
const toggle = () => setOpen(!open)
return (
<div className={classNames('border border-gray-200 bg-gray-50 rounded-lg', wrapperClassName)}>
<div className='flex items-center justify-between leading-[18px] px-3 py-2 text-xs font-medium text-gray-800 cursor-pointer' onClick={toggle}>
{title}
{
open
? <ChevronDownIcon className='w-3 h-3 text-gray-400' />
: <ChevronRightIcon className='w-3 h-3 text-gray-400' />
}
</div>
{
open && (
<div className='py-2 border-t border-t-gray-100'>
{
items.map(item => (
<div key={item.key} onClick={() => onSelect && onSelect(item)}>
{renderItem(item)}
</div>
))
}
</div>
)
}
</div>
)
}
export default Collapse

View File

@@ -0,0 +1,5 @@
.modal {
max-width: 720px !important;
padding: 0 !important;
overflow-y: auto;
}

View File

@@ -0,0 +1,132 @@
'use client'
import { useTranslation } from 'react-i18next'
import { useState } from 'react'
import { AtSymbolIcon, GlobeAltIcon, UserIcon, XMarkIcon, CubeTransparentIcon, UsersIcon } from '@heroicons/react/24/outline'
import { GlobeAltIcon as GlobalAltIconSolid, UserIcon as UserIconSolid, UsersIcon as UsersIconSolid } from '@heroicons/react/24/solid'
import AccountPage from './account-page'
import MembersPage from './members-page'
import IntegrationsPage from './Integrations-page'
import LanguagePage from './language-page'
import ProviderPage from './provider-page'
import s from './index.module.css'
import Modal from '@/app/components/base/modal'
const iconClassName = `
w-[18px] h-[18px] ml-3 mr-2
`
type IAccountSettingProps = {
onCancel: () => void
activeTab?: string
}
export default function AccountSetting({
onCancel,
activeTab = 'account',
}: IAccountSettingProps) {
const [activeMenu, setActiveMenu] = useState(activeTab)
const { t } = useTranslation()
const menuItems = [
{
key: 'account-group',
name: t('common.settings.accountGroup'),
items: [
{
key: 'account',
name: t('common.settings.account'),
icon: <UserIcon className={iconClassName} />,
activeIcon: <UserIconSolid className={iconClassName} />,
},
{
key: 'integrations',
name: t('common.settings.integrations'),
icon: <AtSymbolIcon className={iconClassName} />,
activeIcon: <AtSymbolIcon className={iconClassName} />,
},
{
key: 'language',
name: t('common.settings.language'),
icon: <GlobeAltIcon className={iconClassName} />,
activeIcon: <GlobalAltIconSolid className={iconClassName} />,
},
]
},
{
key: 'workspace-group',
name: t('common.settings.workplaceGroup'),
items: [
{
key: 'members',
name: t('common.settings.members'),
icon: <UsersIcon className={iconClassName} />,
activeIcon: <UsersIconSolid className={iconClassName} />,
},
{
key: 'provider',
name: t('common.settings.provider'),
icon: <CubeTransparentIcon className={iconClassName} />,
activeIcon: <CubeTransparentIcon className={iconClassName} />,
},
]
}
]
return (
<Modal
isShow
onClose={() => { }}
className={s.modal}
>
<div className='flex'>
<div className='w-[200px] p-4 border border-gray-100'>
<div className='mb-8 ml-2 text-base font-medium leading-6 text-gray-900'>{t('common.userProfile.settings')}</div>
<div>
{
menuItems.map(menuItem => (
<div key={menuItem.key} className='mb-4'>
<div className='px-2 mb-[6px] text-xs font-medium text-gray-500'>{menuItem.name}</div>
<div>
{
menuItem.items.map(item => (
<div
key={item.key}
className={`
flex items-center h-[37px] mb-[2px] text-sm cursor-pointer rounded-lg
${activeMenu === item.key ? 'font-semibold text-primary-600 bg-primary-50' : 'font-light text-gray-700'}
`}
onClick={() => setActiveMenu(item.key)}
>
{activeMenu === item.key ? item.activeIcon : item.icon}{item.name}
</div>
))
}
</div>
</div>
))
}
</div>
</div>
<div className='w-[520px] h-[580px] px-6 py-4 overflow-y-auto'>
<div className='flex items-center justify-between h-6 mb-8 text-base font-medium text-gray-900 '>
{[...menuItems[0].items, ...menuItems[1].items].find(item => item.key === activeMenu)?.name}
<XMarkIcon className='w-4 h-4 cursor-pointer' onClick={onCancel} />
</div>
{
activeMenu === 'account' && <AccountPage />
}
{
activeMenu === 'members' && <MembersPage />
}
{
activeMenu === 'integrations' && <IntegrationsPage />
}
{
activeMenu === 'language' && <LanguagePage />
}
{
activeMenu === 'provider' && <ProviderPage />
}
</div>
</div>
</Modal>
)
}

View File

@@ -0,0 +1,24 @@
.google-icon {
background: url(../../assets/google.svg) center center no-repeat;
background-size: 16px 16px;
}
.github-icon {
background: url(../../assets/github.svg) center center no-repeat;
background-size: 16px 16px;
}
.twitter-icon {
background: url(../../assets/twitter.svg) center center no-repeat;
background-size: 16px 16px;
}
.bitbucket-icon {
background: url(../../assets/bitbucket.svg) center center no-repeat;
background-size: 16px 16px;
}
.salesforce-icon {
background: url(../../assets/salesforce.svg) center center no-repeat;
background-size: 24px auto;
}

View File

@@ -0,0 +1,72 @@
'use client'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { useAppContext } from '@/context/app-context'
import { SimpleSelect } from '@/app/components/base/select'
import type { Item } from '@/app/components/base/select'
import { updateUserProfile } from '@/service/common'
import { ToastContext } from '@/app/components/base/toast'
import I18n from '@/context/i18n'
import { timezones } from '@/utils/timezone'
import { languageMaps, languages } from '@/utils/language'
const titleClassName = `
mb-2 text-sm font-medium text-gray-900
`
export default function LanguagePage() {
const { locale, setLocaleOnClient } = useContext(I18n)
const { userProfile, mutateUserProfile } = useAppContext()
const { notify } = useContext(ToastContext)
const [editing, setEditing] = useState(false)
const { t } = useTranslation()
const handleSelect = async (type: string, item: Item) => {
let url = ''
let bodyKey = ''
if (type === 'language') {
url = '/account/interface-language'
bodyKey = 'interface_language'
setLocaleOnClient(item.value === 'en-US' ? 'en' : 'zh-Hans')
}
if (type === 'timezone') {
url = '/account/timezone'
bodyKey = 'timezone'
}
try {
setEditing(true)
await updateUserProfile({ url, body: { [bodyKey]: item.value } })
notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
mutateUserProfile()
setEditing(false)
}
catch (e) {
notify({ type: 'error', message: (e as Error).message })
setEditing(false)
}
}
return (
<>
<div className='mb-8'>
<div className={titleClassName}>{t('common.language.displayLanguage')}</div>
<SimpleSelect
defaultValue={languageMaps[locale] || userProfile.interface_language}
items={languages}
onSelect={item => handleSelect('language', item)}
disabled={editing}
/>
</div>
<div className='mb-8'>
<div className={titleClassName}>{t('common.language.timezone')}</div>
<SimpleSelect
defaultValue={userProfile.timezone}
items={timezones}
onSelect={item => handleSelect('timezone', item)}
disabled={editing}
/>
</div>
</>
)
}

View File

@@ -0,0 +1,9 @@
.logo-icon {
width: 40px;
height: 40px;
background: #ffffff url(../../assets/logo-icon.png) center center no-repeat;
background-size: contain;
box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
border-radius: 8px;
border: 0.5px solid rgba(0, 0, 0, 0.05);
}

View File

@@ -0,0 +1,114 @@
'use client'
import { useState } from 'react'
import s from './index.module.css'
import cn from 'classnames'
import useSWR from 'swr'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
import I18n from '@/context/i18n'
import { useContext } from 'use-context-selector'
import { fetchMembers } from '@/service/common'
import { UserPlusIcon } from '@heroicons/react/24/outline'
import { useTranslation } from 'react-i18next'
import InviteModal from './invite-modal'
import InvitedModal from './invited-modal'
import Operation from './operation'
import { useAppContext } from '@/context/app-context'
import Avatar from '@/app/components/base/avatar'
import { useWorkspacesContext } from '@/context/workspace-context'
dayjs.extend(relativeTime)
const MembersPage = () => {
const { t } = useTranslation()
const RoleMap = {
owner: t('common.members.owner'),
admin: t('common.members.admin'),
normal: t('common.members.normal'),
}
const { locale } = useContext(I18n)
const { userProfile } = useAppContext()
const { data, mutate } = useSWR({ url: '/workspaces/current/members' }, fetchMembers)
const [inviteModalVisible, setInviteModalVisible] = useState(false)
const [invitedModalVisible, setInvitedModalVisible] = useState(false)
const accounts = data?.accounts || []
const owner = accounts.filter(account => account.role === 'owner')?.[0]?.email === userProfile.email
const { workspaces } = useWorkspacesContext()
const currentWrokspace = workspaces.filter(item => item.current)?.[0]
return (
<>
<div>
<div className='flex items-center mb-4 p-3 bg-gray-50 rounded-2xl'>
<div className={cn(s['logo-icon'], 'shrink-0')}></div>
<div className='grow mx-2'>
<div className='text-sm font-medium text-gray-900'>{currentWrokspace.name}</div>
<div className='text-xs text-gray-500'>{t('common.userProfile.workspace')}</div>
</div>
<div className='
shrink-0 flex items-center py-[7px] px-3 border-[0.5px] border-gray-200
text-[13px] font-medium text-primary-600 bg-white
shadow-[0_1px_2px_rgba(16,24,40,0.05)] rounded-lg cursor-pointer
' onClick={() => setInviteModalVisible(true)}>
<UserPlusIcon className='w-4 h-4 mr-2 ' />
{t('common.members.invite')}
</div>
</div>
<div>
<div className='flex items-center py-[7px] border-b border-gray-200'>
<div className='grow px-3 text-xs font-medium text-gray-500'>{t('common.members.name')}</div>
<div className='shrink-0 w-[104px] text-xs font-medium text-gray-500'>{t('common.members.lastActive')}</div>
<div className='shrink-0 w-[96px] px-3 text-xs font-medium text-gray-500'>{t('common.members.role')}</div>
</div>
<div>
{
accounts.map(account => (
<div key={account.id} className='flex border-b border-gray-100'>
<div className='grow flex items-center py-2 px-3'>
<Avatar size={24} className='mr-2' name={account.name} />
<div className=''>
<div className='text-[13px] font-medium text-gray-700 leading-[18px]'>
{account.name}
{account.status === 'pending' && <span className='ml-1 text-xs text-[#DC6803]'>{t('common.members.pending')}</span>}
{userProfile.email === account.email && <span className='text-xs text-gray-500'>{t('common.members.you')}</span>}
</div>
<div className='text-xs text-gray-500 leading-[18px]'>{account.email}</div>
</div>
</div>
<div className='shrink-0 flex items-center w-[104px] py-2 text-[13px] text-gray-700'>{dayjs(Number((account.last_login_at || account.created_at)) * 1000).locale(locale === 'zh-Hans' ? 'zh-cn' : 'en').fromNow()}</div>
<div className='shrink-0 w-[96px] flex items-center'>
{
owner && account.role !== 'owner'
? <Operation member={account} onOperate={() => mutate()} />
: <div className='px-3 text-[13px] text-gray-700'>{RoleMap[account.role] || RoleMap.normal}</div>
}
</div>
</div>
))
}
</div>
</div>
</div>
{
inviteModalVisible && (
<InviteModal
onCancel={() => setInviteModalVisible(false)}
onSend={() => {
setInvitedModalVisible(true)
mutate()
}}
/>
)
}
{
invitedModalVisible && (
<InvitedModal
onCancel={() => setInvitedModalVisible(false)}
/>
)
}
</>
)
}
export default MembersPage

View File

@@ -0,0 +1,4 @@
.modal {
padding: 24px 32px !important;
width: 400px !important;
}

View File

@@ -0,0 +1,74 @@
'use client'
import { useState } from 'react'
import { useContext } from 'use-context-selector'
import { XMarkIcon } from '@heroicons/react/24/outline'
import { useTranslation } from 'react-i18next'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import s from './index.module.css'
import { inviteMember } from '@/service/common'
import { emailRegex } from '@/config'
import { ToastContext } from '@/app/components/base/toast'
interface IInviteModalProps {
onCancel: () => void,
onSend: () => void,
}
const InviteModal = ({
onCancel,
onSend,
}: IInviteModalProps) => {
const { t } = useTranslation()
const [email, setEmail] = useState('')
const { notify } = useContext(ToastContext)
const handleSend = async () => {
if (emailRegex.test(email)) {
try {
const res = await inviteMember({ url: '/workspaces/current/members/invite-email', body: { email, role: 'admin'} })
if (res.result === 'success') {
onCancel()
onSend()
}
} catch (e) {
}
} else {
notify({ type: 'error', message: t('common.members.emailInvalid') })
}
}
return (
<div className={s.wrap}>
<Modal isShow onClose={() => {}} className={s.modal}>
<div className='flex justify-between mb-2'>
<div className='text-xl font-semibold text-gray-900'>{t('common.members.inviteTeamMember')}</div>
<XMarkIcon className='w-4 h-4 cursor-pointer' onClick={onCancel} />
</div>
<div className='mb-7 text-[13px] text-gray-500'>{t('common.members.inviteTeamMemberTip')}</div>
<div>
<div className='mb-2 text-sm font-medium text-gray-900'>{t('common.members.email')}</div>
<input
className='
block w-full py-2 mb-9 px-3 bg-gray-50 outline-none border-none
appearance-none text-sm text-gray-900 rounded-lg
'
value={email}
onChange={e => setEmail(e.target.value)}
placeholder={t('common.members.emailPlaceholder') || ''}
/>
<Button
className='w-full text-sm font-medium'
onClick={handleSend}
type='primary'
>
{t('common.members.sendInvite')}
</Button>
</div>
</Modal>
</div>
)
}
export default InviteModal

View File

@@ -0,0 +1,5 @@
.modal {
padding: 32px !important;
width: 480px !important;
background: linear-gradient(180deg, rgba(3, 152, 85, 0.05) 0%, rgba(3, 152, 85, 0) 22.44%), #F9FAFB !important;
}

View File

@@ -0,0 +1,45 @@
import { CheckCircleIcon } from '@heroicons/react/24/solid'
import { XMarkIcon } from '@heroicons/react/24/outline'
import { useTranslation } from 'react-i18next'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import s from './index.module.css'
interface IInvitedModalProps {
onCancel: () => void,
}
const InvitedModal = ({
onCancel
}: IInvitedModalProps) => {
const { t } = useTranslation()
return (
<div className={s.wrap}>
<Modal isShow onClose={() => {}} className={s.modal}>
<div className='flex justify-between mb-3'>
<div className='
w-12 h-12 flex items-center justify-center rounded-xl
bg-white border-[0.5px] border-gray-100
shadow-[0px_20px_24px_-4px_rgba(16,24,40,0.08),0px_8px_8px_-4px_rgba(16,24,40,0.03)]
'>
<CheckCircleIcon className='w-[22px] h-[22px] text-[#039855]' />
</div>
<XMarkIcon className='w-4 h-4 cursor-pointer' onClick={onCancel} />
</div>
<div className='mb-1 text-xl font-semibold text-gray-900'>{t('common.members.invitationSent')}</div>
<div className='mb-10 text-sm text-gray-500'>{t('common.members.invitationSentTip')}</div>
<div className='flex justify-end'>
<Button
className='w-[96px] text-sm font-medium'
onClick={onCancel}
type='primary'
>
{t('common.members.ok')}
</Button>
</div>
</Modal>
</div>
)
}
export default InvitedModal

View File

@@ -0,0 +1,3 @@
.popup {
box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
}

View File

@@ -0,0 +1,136 @@
'use client'
import { useTranslation } from 'react-i18next'
import { Fragment } from 'react'
import { useContext } from 'use-context-selector'
import { Menu, Transition } from '@headlessui/react'
import type { Member } from '@/models/common'
import { deleteMemberOrCancelInvitation, updateMemberRole } from '@/service/common'
import { ToastContext } from '@/app/components/base/toast'
import s from './index.module.css'
import cn from 'classnames'
import { ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline'
const itemClassName = `
flex px-3 py-2 cursor-pointer hover:bg-gray-50 rounded-lg
`
const itemIconClassName = `
w-4 h-4 mt-[2px] mr-1 text-primary-600
`
const itemTitleClassName = `
leading-[20px] text-sm text-gray-700 whitespace-nowrap
`
const itemDescClassName = `
leading-[18px] text-xs text-gray-500 whitespace-nowrap
`
interface IOperationProps {
member: Member
onOperate: () => void
}
const Operation = ({
member,
onOperate
}: IOperationProps) => {
const { t } = useTranslation()
const RoleMap = {
owner: t('common.members.owner'),
admin: t('common.members.admin'),
normal: t('common.members.normal'),
}
const { notify } = useContext(ToastContext)
const handleDeleteMemberOrCancelInvitation = async () => {
try {
await deleteMemberOrCancelInvitation({ url: `/workspaces/current/members/${member.id}` })
onOperate()
notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
} catch (e) {
}
}
const handleUpdateMemberRole = async (role: string) => {
try {
await updateMemberRole({
url: `/workspaces/current/members/${member.id}/update-role`,
body: { role }
})
onOperate()
notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
} catch (e) {
}
}
return (
<Menu as="div" className="relative w-full h-full">
{
({ open }) => (
<>
<Menu.Button className={cn(
`
group flex items-center justify-between w-full h-full justify-center
hover:bg-gray-100 cursor-pointer ${open && 'bg-gray-100'}
text-[13px] text-gray-700 px-3
`
)}>
{RoleMap[member.role] || RoleMap.normal}
<ChevronDownIcon className={`w-4 h-4 group-hover:block ${open ? 'block' : 'hidden'}`} />
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items
className={cn(
`
absolute right-0 top-[52px] z-10 bg-white border-[0.5px] border-gray-200
divide-y divide-gray-100 origin-top-right rounded-lg
`,
s.popup
)}
>
<div className="px-1 py-1">
{
['admin', 'normal'].map(role => (
<Menu.Item>
<div className={itemClassName} onClick={() => handleUpdateMemberRole(role)}>
{
role === member.role
? <CheckIcon className={itemIconClassName} />
: <div className={itemIconClassName} />
}
<div>
<div className={itemTitleClassName}>{t(`common.members.${role}`)}</div>
<div className={itemDescClassName}>{t(`common.members.${role}Tip`)}</div>
</div>
</div>
</Menu.Item>
))
}
</div>
<Menu.Item>
<div className='px-1 py-1'>
<div className={itemClassName} onClick={handleDeleteMemberOrCancelInvitation}>
<div className={itemIconClassName} />
<div>
<div className={itemTitleClassName}>{t('common.members.removeFromTeam')}</div>
<div className={itemDescClassName}>{t('common.members.removeFromTeamTip')}</div>
</div>
</div>
</div>
</Menu.Item>
</Menu.Items>
</Transition>
</>
)
}
</Menu>
)
}
export default Operation

View File

@@ -0,0 +1,75 @@
import type { Provider, ProviderAzureToken } from '@/models/common'
import { useTranslation } from 'react-i18next'
import Link from 'next/link'
import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'
import ProviderInput, { ProviderValidateTokenInput} from '../provider-input'
import { useState } from 'react'
import { ValidatedStatus } from '../provider-input/useValidateToken'
interface IAzureProviderProps {
provider: Provider
onValidatedStatus: (status?: ValidatedStatus) => void
onTokenChange: (token: ProviderAzureToken) => void
}
const AzureProvider = ({
provider,
onTokenChange,
onValidatedStatus
}: IAzureProviderProps) => {
const { t } = useTranslation()
const [token, setToken] = useState(provider.token as ProviderAzureToken || {})
const handleFocus = () => {
if (token === provider.token) {
token.azure_api_key = ''
setToken({...token})
onTokenChange({...token})
}
}
const handleChange = (type: keyof ProviderAzureToken, v: string) => {
token[type] = v
setToken({...token})
onTokenChange({...token})
}
return (
<div className='px-4 py-3'>
<ProviderInput
className='mb-4'
name={t('common.provider.azure.resourceName')}
placeholder={t('common.provider.azure.resourceNamePlaceholder')}
value={token.azure_api_base}
onChange={(v) => handleChange('azure_api_base', v)}
/>
<ProviderInput
className='mb-4'
name={t('common.provider.azure.deploymentId')}
placeholder={t('common.provider.azure.deploymentIdPlaceholder')}
value={token.azure_api_type}
onChange={v => handleChange('azure_api_type', v)}
/>
<ProviderInput
className='mb-4'
name={t('common.provider.azure.apiVersion')}
placeholder={t('common.provider.azure.apiVersionPlaceholder')}
value={token.azure_api_version}
onChange={v => handleChange('azure_api_version', v)}
/>
<ProviderValidateTokenInput
className='mb-4'
name={t('common.provider.azure.apiKey')}
placeholder={t('common.provider.azure.apiKeyPlaceholder')}
value={token.azure_api_key}
onChange={v => handleChange('azure_api_key', v)}
onFocus={handleFocus}
onValidatedStatus={onValidatedStatus}
providerName={provider.provider_name}
/>
<Link className="flex items-center text-xs cursor-pointer text-primary-600" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
{t('common.provider.azure.helpTip')}
<ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
</Link>
</div>
)
}
export default AzureProvider

View File

@@ -0,0 +1,17 @@
.wrapper .button {
height: 24px;
font-size: 12px;
border-radius: 6px;
}
.gpt-icon {
margin-right: 12px;
width: 20px;
height: 20px;
background: url(../../assets/gpt.svg) center center no-repeat;
background-size: contain;
}
.input {
box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
}

View File

@@ -0,0 +1,112 @@
import { useState } from 'react'
import useSWR from 'swr'
import { fetchProviders } from '@/service/common'
import ProviderItem from './provider-item'
import OpenaiHostedProvider from './openai-hosted-provider'
import type { ProviderHosted } from '@/models/common'
import { LockClosedIcon } from '@heroicons/react/24/solid'
import { useTranslation } from 'react-i18next'
import Link from 'next/link'
import { IS_CE_EDITION } from '@/config'
const providersMap: {[k: string]: any} = {
'openai-custom': {
icon: 'openai',
name: 'OpenAI',
},
'azure_openai-custom': {
icon: 'azure',
name: 'Azure OpenAI Service',
}
}
// const providersList = [
// {
// id: 'openai',
// name: 'OpenAI',
// providerKey: '1',
// status: '',
// child: <OpenaiProvider />
// },
// {
// id: 'azure',
// name: 'Azure OpenAI Service',
// providerKey: '1',
// status: 'error',
// child: <AzureProvider />
// },
// {
// id: 'anthropic',
// name: 'Anthropic',
// providerKey: '',
// status: '',
// child: <div>placeholder</div>
// },
// {
// id: 'hugging-face',
// name: 'Hugging Face Hub',
// providerKey: '',
// comingSoon: true,
// status: '',
// child: <div>placeholder</div>
// }
// ]
const ProviderPage = () => {
const { t } = useTranslation()
const [activeProviderId, setActiveProviderId] = useState('')
const { data, mutate } = useSWR({ url: '/workspaces/current/providers' }, fetchProviders)
const providers = data?.filter(provider => providersMap[`${provider.provider_name}-${provider.provider_type}`])?.map(provider => {
const providerKey = `${provider.provider_name}-${provider.provider_type}`
return {
provider,
icon: providersMap[providerKey].icon,
name: providersMap[providerKey].name,
}
})
const providerHosted = data?.filter(provider => provider.provider_name === 'openai' && provider.provider_type === 'system')?.[0]
return (
<div>
{
providerHosted && !IS_CE_EDITION && (
<>
<div>
<OpenaiHostedProvider provider={providerHosted as ProviderHosted} />
</div>
<div className='my-5 w-full h-0 border-[0.5px] border-gray-100' />
</>
)
}
<div>
{
providers?.map(providerItem => (
<ProviderItem
key={`${providerItem.provider.provider_name}-${providerItem.provider.provider_type}`}
icon={providerItem.icon}
name={providerItem.name}
provider={providerItem.provider}
activeId={activeProviderId}
onActive={aid => setActiveProviderId(aid)}
onSave={() => mutate()}
/>
))
}
</div>
<div className='absolute bottom-0 w-full h-[42px] flex items-center bg-white text-xs text-gray-500'>
<LockClosedIcon className='w-3 h-3 mr-1' />
{t('common.provider.encrypted.front')}
<Link
className='text-primary-600 mx-1'
target={'_blank'}
href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
>
PKCS1_OAEP
</Link>
{t('common.provider.encrypted.back')}
</div>
</div>
)
}
export default ProviderPage

View File

@@ -0,0 +1,24 @@
.icon {
width: 24px;
height: 24px;
margin-right: 12px;
background: url(../../../assets/gpt.svg) center center no-repeat;
background-size: contain;
}
.bar {
background: linear-gradient(90deg, rgba(41, 112, 255, 0.9) 0%, rgba(21, 94, 239, 0.9) 100%);
}
.bar-error {
background: linear-gradient(90deg, rgba(240, 68, 56, 0.72) 0%, rgba(217, 45, 32, 0.9) 100%);
}
.bar-item {
width: 10%;
border-right: 1px solid rgba(255, 255, 255, 0.5);
}
.bar-item:last-of-type {
border-right: 0;
}

View File

@@ -0,0 +1,65 @@
import { useTranslation } from 'react-i18next'
import s from './index.module.css'
import cn from 'classnames'
import type { ProviderHosted } from '@/models/common'
interface IOpenaiHostedProviderProps {
provider: ProviderHosted
}
const OpenaiHostedProvider = ({
provider
}: IOpenaiHostedProviderProps) => {
const { t } = useTranslation()
const exhausted = provider.quota_used > provider.quota_limit
return (
<div className={`
border-[0.5px] border-gray-200 rounded-xl
${exhausted ? 'bg-[#FFFBFA]' : 'bg-gray-50'}
`}>
<div className='pt-4 px-4 pb-3'>
<div className='flex items-center mb-3'>
<div className={s.icon} />
<div className='grow text-sm font-medium text-gray-800'>
{t('common.provider.openaiHosted.openaiHosted')}
</div>
<div className={`
px-2 h-[22px] flex items-center rounded-md border
text-xs font-semibold
${exhausted ? 'border-[#D92D20] text-[#D92D20]' : 'border-primary-600 text-primary-600'}
`}>
{exhausted ? t('common.provider.openaiHosted.exhausted') : t('common.provider.openaiHosted.onTrial')}
</div>
</div>
<div className='text-[13px] text-gray-500'>{t('common.provider.openaiHosted.desc')}</div>
</div>
<div className='flex items-center h-[42px] px-4 border-t-[0.5px] border-t-[rgba(0, 0, 0, 0.05)]'>
<div className='text-[13px] text-gray-700'>{t('common.provider.openaiHosted.callTimes')}</div>
<div className='relative grow h-2 flex bg-gray-200 rounded-md mx-2 overflow-hidden'>
<div
className={cn(s.bar, exhausted && s['bar-error'], 'absolute top-0 left-0 right-0 bottom-0')}
style={{ width: `${(provider.quota_used / provider.quota_limit * 100).toFixed(2)}%` }}
/>
{Array(10).fill(0).map((i, k) => (
<div key={k} className={s['bar-item']} />
))}
</div>
<div className={`
text-[13px] font-medium ${exhausted ? 'text-[#D92D20]' : 'text-gray-700'}
`}>{provider.quota_used}/{provider.quota_limit}</div>
</div>
{
exhausted && (
<div className='
px-4 py-3 leading-[18px] flex items-center text-[13px] text-gray-700 font-medium
bg-[#FFFAEB] border-t border-t-[rgba(0, 0, 0, 0.05)] rounded-b-xl
'>
{t('common.provider.openaiHosted.usedUp')}
</div>
)
}
</div>
)
}
export default OpenaiHostedProvider

View File

@@ -0,0 +1,223 @@
import { ChangeEvent, useEffect, useRef, useState } from 'react'
import { useContext } from 'use-context-selector'
import { useTranslation } from 'react-i18next'
import { debounce } from 'lodash-es'
import Link from 'next/link'
import useSWR from 'swr'
import { ArrowTopRightOnSquareIcon, PencilIcon } from '@heroicons/react/24/outline'
import { CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/24/solid'
import Button from '@/app/components/base/button'
import s from './index.module.css'
import classNames from 'classnames'
import { fetchTenantInfo, validateProviderKey, updateProviderAIKey } from '@/service/common'
import { ToastContext } from '@/app/components/base/toast'
import Indicator from '../../../indicator'
import I18n from '@/context/i18n'
type IStatusType = 'normal' | 'verified' | 'error' | 'error-api-key-exceed-bill'
type TInputWithStatusProps = {
value: string
onChange: (v: string) => void
onValidating: (validating: boolean) => void
verifiedStatus: IStatusType
onVerified: (verified: IStatusType) => void
}
const InputWithStatus = ({
value,
onChange,
onValidating,
verifiedStatus,
onVerified
}: TInputWithStatusProps) => {
const { t } = useTranslation()
const validateKey = useRef(debounce(async (token: string) => {
if (!token) return
onValidating(true)
try {
const res = await validateProviderKey({ url: '/workspaces/current/providers/openai/token-validate', body: { token } })
onVerified(res.result === 'success' ? 'verified' : 'error')
} catch (e: any) {
if (e.status === 400) {
e.json().then(({ code }: any) => {
if (code === 'provider_request_failed') {
onVerified('error-api-key-exceed-bill')
}
})
} else {
onVerified('error')
}
} finally {
onValidating(false)
}
}, 500))
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const inputValue = e.target.value
onChange(inputValue)
if (!inputValue) {
onVerified('normal')
}
validateKey.current(inputValue)
}
return (
<div className={classNames('flex items-center h-9 px-3 bg-white border border-gray-300 rounded-lg', s.input)}>
<input
value={value}
placeholder={t('common.provider.enterYourKey') || ''}
className='w-full h-9 mr-2 appearance-none outline-none bg-transparent text-xs'
onChange={handleChange}
/>
{
verifiedStatus === 'error' && <ExclamationCircleIcon className='w-4 h-4 text-[#D92D20]' />
}
{
verifiedStatus === 'verified' && <CheckCircleIcon className='w-4 h-4 text-[#039855]' />
}
</div>
)
}
const OpenaiProvider = () => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const { data: userInfo, mutate } = useSWR({ url: '/info' }, fetchTenantInfo)
const [inputValue, setInputValue] = useState<string>('')
const [validating, setValidating] = useState(false)
const [editStatus, setEditStatus] = useState<IStatusType>('normal')
const [loading, setLoading] = useState(false)
const [editing, setEditing] = useState(false)
const [invalidStatus, setInvalidStatus] = useState(false)
const { notify } = useContext(ToastContext)
const provider = userInfo?.providers?.find(({ provider }) => provider === 'openai')
const handleReset = () => {
setInputValue('')
setValidating(false)
setEditStatus('normal')
setLoading(false)
setEditing(false)
}
const handleSave = async () => {
if (editStatus === 'verified') {
try {
setLoading(true)
await updateProviderAIKey({ url: '/workspaces/current/providers/openai/token', body: { token: inputValue ?? '' } })
notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
} catch (e) {
notify({ type: 'error', message: t('common.provider.saveFailed') })
} finally {
setLoading(false)
handleReset()
mutate()
}
}
}
useEffect(() => {
if (provider && !provider.token_is_valid && provider.token_is_set) {
setInvalidStatus(true)
}
}, [userInfo])
const showInvalidStatus = invalidStatus && !editing
const renderErrorMessage = () => {
if (validating) {
return (
<div className={`mt-2 text-primary-600 text-xs font-normal`}>
{t('common.provider.validating')}
</div>
)
}
if (editStatus === 'error-api-key-exceed-bill') {
return (
<div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
{t('common.provider.apiKeyExceedBill')}&nbsp;
<Link
className='underline'
href="https://platform.openai.com/account/api-keys"
target={'_blank'}>
{locale === 'en' ? 'this link' : '这篇文档'}
</Link>
</div>
)
}
if (showInvalidStatus || editStatus === 'error') {
return (
<div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
{t('common.provider.invalidKey')}
</div>
)
}
return null
}
return (
<div className='px-4 pt-3 pb-4'>
<div className='flex items-center mb-2 h-6'>
<div className='grow text-[13px] text-gray-800 font-medium'>
{t('common.provider.apiKey')}
</div>
{
provider && !editing && (
<div
className='
flex items-center h-6 px-2 rounded-md border border-gray-200
text-xs font-medium text-gray-700 cursor-pointer
'
onClick={() => setEditing(true)}
>
<PencilIcon className='mr-1 w-3 h-3 text-gray-500' />
{t('common.operation.edit')}
</div>
)
}
{
(inputValue || editing) && (
<>
<Button
className={classNames('mr-1', s.button)}
loading={loading}
onClick={handleReset}
>
{t('common.operation.cancel')}
</Button>
<Button
type='primary'
className={classNames(s.button)}
loading={loading}
onClick={handleSave}>
{t('common.operation.save')}
</Button>
</>
)
}
</div>
{
(!provider || (provider && editing)) && (
<InputWithStatus
value={inputValue}
onChange={v => setInputValue(v)}
verifiedStatus={editStatus}
onVerified={v => setEditStatus(v)}
onValidating={v => setValidating(v)}
/>
)
}
{
(provider && !editing) && (
<div className={classNames('flex justify-between items-center bg-white px-3 h-9 rounded-lg text-gray-800 text-xs font-medium', s.input)}>
sk-0C...skuA
<Indicator color={(provider.token_is_set && provider.token_is_valid) ? 'green' : 'orange'} />
</div>
)
}
{renderErrorMessage()}
<Link className="inline-flex items-center mt-3 text-xs font-normal cursor-pointer text-primary-600 w-fit" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
{t('appOverview.welcome.getKeyTip')}
<ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
</Link>
</div>
)
}
export default OpenaiProvider

View File

@@ -0,0 +1,52 @@
import type { Provider } from '@/models/common'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ProviderValidateTokenInput } from '../provider-input'
import Link from 'next/link'
import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'
import { ValidatedStatus } from '../provider-input/useValidateToken'
interface IOpenaiProviderProps {
provider: Provider
onValidatedStatus: (status?: ValidatedStatus) => void
onTokenChange: (token: string) => void
}
const OpenaiProvider = ({
provider,
onValidatedStatus,
onTokenChange
}: IOpenaiProviderProps) => {
const { t } = useTranslation()
const [token, setToken] = useState(provider.token as string || '')
const handleFocus = () => {
if (token === provider.token) {
setToken('')
onTokenChange('')
}
}
const handleChange = (v: string) => {
setToken(v)
onTokenChange(v)
}
return (
<div className='px-4 pt-3 pb-4'>
<ProviderValidateTokenInput
value={token}
name={t('common.provider.apiKey')}
placeholder={t('common.provider.enterYourKey')}
onChange={handleChange}
onFocus={handleFocus}
onValidatedStatus={onValidatedStatus}
providerName={provider.provider_name}
/>
<Link className="inline-flex items-center mt-3 text-xs font-normal cursor-pointer text-primary-600 w-fit" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
{t('appOverview.welcome.getKeyTip')}
<ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
</Link>
</div>
)
}
export default OpenaiProvider

View File

@@ -0,0 +1,143 @@
import { ChangeEvent, useEffect } from 'react'
import Link from 'next/link'
import { CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/24/solid'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import I18n from '@/context/i18n'
import useValidateToken, { ValidatedStatus } from './useValidateToken'
interface IProviderInputProps {
value?: string
name: string
placeholder: string
className?: string
onChange: (v: string) => void
onFocus?: () => void
}
const ProviderInput = ({
value,
name,
placeholder,
className,
onChange,
onFocus,
}: IProviderInputProps) => {
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const inputValue = e.target.value
onChange(inputValue)
}
return (
<div className={className}>
<div className="mb-2 text-[13px] font-medium text-gray-800">{name}</div>
<div className='
flex items-center px-3 bg-white rounded-lg
shadow-[0_1px_2px_rgba(16,24,40,0.05)]
'>
<input
className='
w-full py-[9px]
text-xs font-medium text-gray-700 leading-[18px]
appearance-none outline-none bg-transparent
'
value={value}
placeholder={placeholder}
onChange={handleChange}
onFocus={onFocus}
/>
</div>
</div>
)
}
type TproviderInputProps = IProviderInputProps
& {
onValidatedStatus?: (status?: ValidatedStatus) => void
providerName: string
}
export const ProviderValidateTokenInput = ({
value,
name,
placeholder,
className,
onChange,
onFocus,
onValidatedStatus,
providerName
}: TproviderInputProps) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const [ validating, validatedStatus, validate ] = useValidateToken(providerName)
useEffect(() => {
if (typeof onValidatedStatus === 'function') {
onValidatedStatus(validatedStatus)
}
}, [validatedStatus])
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const inputValue = e.target.value
onChange(inputValue)
validate(inputValue)
}
return (
<div className={className}>
<div className="mb-2 text-[13px] font-medium text-gray-800">{name}</div>
<div className='
flex items-center px-3 bg-white rounded-lg
shadow-[0_1px_2px_rgba(16,24,40,0.05)]
'>
<input
className='
w-full py-[9px]
text-xs font-medium text-gray-700 leading-[18px]
appearance-none outline-none bg-transparent
'
value={value}
placeholder={placeholder}
onChange={handleChange}
onFocus={onFocus}
/>
{
validatedStatus === ValidatedStatus.Error && <ExclamationCircleIcon className='w-4 h-4 text-[#D92D20]' />
}
{
validatedStatus === ValidatedStatus.Success && <CheckCircleIcon className='w-4 h-4 text-[#039855]' />
}
</div>
{
validating && (
<div className={`mt-2 text-primary-600 text-xs font-normal`}>
{t('common.provider.validating')}
</div>
)
}
{
validatedStatus === ValidatedStatus.Exceed && !validating && (
<div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
{t('common.provider.apiKeyExceedBill')}&nbsp;
<Link
className='underline'
href="https://platform.openai.com/account/api-keys"
target={'_blank'}>
{locale === 'en' ? 'this link' : '这篇文档'}
</Link>
</div>
)
}
{
validatedStatus === ValidatedStatus.Error && !validating && (
<div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
{t('common.provider.invalidKey')}
</div>
)
}
</div>
)
}
export default ProviderInput

View File

@@ -0,0 +1,46 @@
import { useState, useCallback } from 'react'
import debounce from 'lodash/debounce'
import { DebouncedFunc } from 'lodash'
import { validateProviderKey } from '@/service/common'
export enum ValidatedStatus {
Success = 'success',
Error = 'error',
Exceed = 'exceed'
}
const useValidateToken = (providerName: string): [boolean, ValidatedStatus | undefined, DebouncedFunc<(token: string) => Promise<void>>] => {
const [validating, setValidating] = useState(false)
const [validatedStatus, setValidatedStatus] = useState<ValidatedStatus | undefined>()
const validate = useCallback(debounce(async (token: string) => {
if (!token) {
setValidatedStatus(undefined)
return
}
setValidating(true)
try {
const res = await validateProviderKey({ url: `/workspaces/current/providers/${providerName}/token-validate`, body: { token } })
setValidatedStatus(res.result === 'success' ? ValidatedStatus.Success : ValidatedStatus.Error)
} catch (e: any) {
if (e.status === 400) {
e.json().then(({ code }: any) => {
if (code === 'provider_request_failed') {
setValidatedStatus(ValidatedStatus.Exceed)
}
})
} else {
setValidatedStatus(ValidatedStatus.Error)
}
} finally {
setValidating(false)
}
}, 500), [])
return [
validating,
validatedStatus,
validate,
]
}
export default useValidateToken

View File

@@ -0,0 +1,19 @@
.icon-openai {
background: url(../../../assets/gpt.svg) center center no-repeat;
background-size: contain;
}
.icon-azure {
background: url(../../../assets/azure.svg) center center no-repeat;
background-size: contain;
}
.icon-anthropic {
background: url(../../../assets/anthropic.svg) center center no-repeat;
background-size: contain;
}
.icon-hugging-face {
background: url(../../../assets/hugging-face.svg) center center no-repeat;
background-size: contain;
}

View File

@@ -0,0 +1,138 @@
import { useState } from 'react'
import cn from 'classnames'
import s from './index.module.css'
import { useContext } from 'use-context-selector'
import Indicator from '../../../indicator'
import { useTranslation } from 'react-i18next'
import type { Provider, ProviderAzureToken } from '@/models/common'
import OpenaiProvider from '../openai-provider/provider'
import AzureProvider from '../azure-provider'
import { ValidatedStatus } from '../provider-input/useValidateToken'
import { updateProviderAIKey } from '@/service/common'
import { ToastContext } from '@/app/components/base/toast'
interface IProviderItemProps {
icon: string
name: string
provider: Provider
activeId: string
onActive: (v: string) => void
onSave: () => void
}
const ProviderItem = ({
activeId,
icon,
name,
provider,
onActive,
onSave
}: IProviderItemProps) => {
const { t } = useTranslation()
const [validatedStatus, setValidatedStatus] = useState<ValidatedStatus>()
const [loading, setLoading] = useState(false)
const { notify } = useContext(ToastContext)
const [token, setToken] = useState<ProviderAzureToken | string>(
provider.provider_name === 'azure_openai'
? { azure_api_base: '', azure_api_type: '', azure_api_version: '', azure_api_key: '' }
: ''
)
const id = `${provider.provider_name}-${provider.provider_type}`
const isOpen = id === activeId
const providerKey = provider.provider_name === 'azure_openai' ? (provider.token as ProviderAzureToken)?.azure_api_key : provider.token
const comingSoon = false
const isValid = provider.is_valid
const handleUpdateToken = async () => {
if (loading) return
if (validatedStatus === ValidatedStatus.Success || !token) {
try {
setLoading(true)
await updateProviderAIKey({ url: `/workspaces/current/providers/${provider.provider_name}/token`, body: { token } })
notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
onActive('')
} catch (e) {
notify({ type: 'error', message: t('common.provider.saveFailed') })
} finally {
setLoading(false)
onSave()
}
}
}
return (
<div className='mb-2 border-[0.5px] border-gray-200 bg-gray-50 rounded-md'>
<div className='flex items-center px-4 h-[52px] cursor-pointer border-b-[0.5px] border-b-gray-200'>
<div className={cn(s[`icon-${icon}`], 'mr-3 w-6 h-6 rounded-md')} />
<div className='grow text-sm font-medium text-gray-800'>{name}</div>
{
providerKey && !comingSoon && !isOpen && (
<div className='flex items-center mr-4'>
{!isValid && <div className='text-xs text-[#D92D20]'>{t('common.provider.invalidApiKey')}</div>}
<Indicator color={!isValid ? 'red' : 'green'} className='ml-2' />
</div>
)
}
{
!comingSoon && !isOpen && (
<div className='
px-3 h-[28px] bg-white border border-gray-200 rounded-md cursor-pointer
text-xs font-medium text-gray-700 flex items-center
' onClick={() => onActive(id)}>
{providerKey ? t('common.provider.editKey') : t('common.provider.addKey')}
</div>
)
}
{
comingSoon && !isOpen && (
<div className='
flex items-center px-2 h-[22px] border border-[#444CE7] rounded-md
text-xs font-medium text-[#444CE7]
'>
{t('common.provider.comingSoon')}
</div>
)
}
{
isOpen && (
<div className='flex items-center'>
<div className='
flex items-center
mr-[5px] px-3 h-7 rounded-md cursor-pointer
text-xs font-medium text-gray-700
' onClick={() => onActive('')} >
{t('common.operation.cancel')}
</div>
<div className='
flex items-center
px-3 h-7 rounded-md cursor-pointer bg-primary-700
text-xs font-medium text-white
' onClick={handleUpdateToken}>
{t('common.operation.save')}
</div>
</div>
)
}
</div>
{
provider.provider_name === 'openai' && isOpen && (
<OpenaiProvider
provider={provider}
onValidatedStatus={v => setValidatedStatus(v)}
onTokenChange={v => setToken(v)}
/>
)
}
{
provider.provider_name === 'azure_openai' && isOpen && (
<AzureProvider
provider={provider}
onValidatedStatus={v => setValidatedStatus(v)}
onTokenChange={v => setToken(v)}
/>
)
}
</div>
)
}
export default ProviderItem