浏览代码

模板相关

CzRger 6 月之前
父节点
当前提交
5e678b321c

+ 2 - 1
web/app/components/base/features/types.ts

@@ -39,7 +39,8 @@ export type FileUpload = {
   allowed_file_extensions?: string[]
   allowed_file_upload_methods?: TransferMethod[]
   number_limits?: number
-  fileUploadConfig?: FileUploadConfigResponse
+  fileUploadConfig?: FileUploadConfigResponse,
+  noUpload: boolean
 } & EnabledOrDisabled
 
 export type AnnotationReplyConfig = {

+ 15 - 13
web/app/components/base/file-uploader/hooks.ts

@@ -282,19 +282,21 @@ export const useFile = (fileConfig: FileUpload) => {
           base64Url: isImage ? reader.result as string : '',
         }
         handleAddFile(uploadingFile)
-        fileUpload({
-          file: uploadingFile.originalFile,
-          onProgressCallback: (progress) => {
-            handleUpdateFile({ ...uploadingFile, progress })
-          },
-          onSuccessCallback: (res) => {
-            handleUpdateFile({ ...uploadingFile, uploadedId: res.id, progress: 100 })
-          },
-          onErrorCallback: () => {
-            notify({ type: 'error', message: t('common.fileUploader.uploadFromComputerUploadError') })
-            handleUpdateFile({ ...uploadingFile, progress: -1 })
-          },
-        }, !!params.token)
+        if (!fileConfig.noUpload) {
+          fileUpload({
+            file: uploadingFile.originalFile,
+            onProgressCallback: (progress) => {
+              handleUpdateFile({ ...uploadingFile, progress })
+            },
+            onSuccessCallback: (res) => {
+              handleUpdateFile({ ...uploadingFile, uploadedId: res.id, progress: 100 })
+            },
+            onErrorCallback: () => {
+              notify({ type: 'error', message: t('common.fileUploader.uploadFromComputerUploadError') })
+              handleUpdateFile({ ...uploadingFile, progress: -1 })
+            },
+          }, !!params.token)
+        }
       },
       false,
     )

+ 1 - 0
web/app/components/base/file-uploader/utils.ts

@@ -184,6 +184,7 @@ export const fileIsUploaded = (file: FileEntity) => {
 }
 
 export const downloadFile = (url: string, filename: string) => {
+  console.log('下载文件', url, filename)
   const anchor = document.createElement('a')
   anchor.href = url
   anchor.download = filename

+ 11 - 7
web/app/components/datasets/documents/index.tsx

@@ -31,6 +31,7 @@ import DatasetMetadataDrawer from '../metadata/metadata-dataset/dataset-metadata
 import StatusWithAction from '../common/document-status-with-action/status-with-action'
 import { SimpleSelect } from '@/app/components/base/select'
 import DetailModal from './mould/index'
+import { useAppContext } from '@/context/app-context'
 
 const FolderPlusIcon = ({ className }: React.SVGProps<SVGElement>) => {
   return <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
@@ -85,6 +86,7 @@ export const fetcher = (url: string) => get(url, {}, {})
 const DEFAULT_LIMIT = 10
 
 const Documents: FC<IDocumentsProps> = ({ datasetId }) => {
+  const appContext = useAppContext()
   const { t } = useTranslation()
   const { plan } = useProviderContext()
   const isFreePlan = plan.type === 'sandbox'
@@ -304,13 +306,15 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {
               />
             </div>
             <div className='flex !h-8 items-center justify-center gap-2'>
-              <Button variant='primary' onClick={() => {
-                setTransfer({ mode: 'manage' })
-                setMouldModalVisible(true)
-              }} className='shrink-0'>
-                <BookOpenIcon className={cn('mr-2 h-4 w-4 stroke-current')} />
-                模板管理
-              </Button>
+              {
+                ['owner', 'admin'].includes(appContext.currentWorkspace.role) && (<Button variant='primary' onClick={() => {
+                  setTransfer({ mode: 'manage' })
+                  setMouldModalVisible(true)
+                }} className='shrink-0'>
+                  <BookOpenIcon className={cn('mr-2 h-4 w-4 stroke-current')} />
+                  模板管理
+                </Button>)
+              }
               <Button variant='primary' onClick={() => {
                 setTransfer({ mode: 'download' })
                 setMouldModalVisible(true)

+ 1 - 1
web/app/components/datasets/documents/list.tsx

@@ -718,7 +718,7 @@ const DocumentList: FC<IDocumentListProps> = ({
                   {
                     true && (
                       ['owner', 'admin'].includes(appContext.currentWorkspace.role)
-                        ? <div className="cursor text-[#155aef]" onClick={(e) => {
+                        ? <div className="cursor-pointer text-[#155aef]" onClick={(e) => {
                           e.stopPropagation()
                           setRow(doc)
                           setConfirmExamineHandleTitle(`${doc.enabled ? '下线' : '上线'}审核`)

+ 35 - 23
web/app/components/datasets/documents/mould/index.tsx

@@ -60,6 +60,7 @@ const DetailModel = ({
       audio_file_size_limit: 50,
       workflow_file_upload_limit: 10,
     },
+    noUpload: true,
   }
   const files = useStore(s => s.files)
   const {
@@ -68,40 +69,40 @@ const DetailModel = ({
   } = useFile(fileConfig)
   const { data, mutate }: any = useSWR(
     {
-      url: '/workspaces/123123',
-      params: {},
+      url: `/datasets/${datasetId}/templates`,
+      params: {
+        page: 1,
+        limit: 1000,
+      },
     },
     fetchMoulds,
   )
   const fileList = data?.data || []
   const handleAdd = useCallback(async () => {
     try {
-      const { result }: any = await addMouldFile({
-        url: '/workspaces/123123',
-        body: { id: files[0].id, fileName: files[0].name },
+      const formData: any = new FormData()
+      formData.set('file', files[0].originalFile)
+      await addMouldFile({
+        url: `/datasets/${datasetId}/templates`,
+        body: formData,
       })
       handleRemoveFile(files[0].id)
-      if (result === 'success')
-        mutate()
+      mutate()
     }
     catch (e) { }
   }, [files, handleRemoveFile])
   const { run: getFiles } = useDebounceFn(() => {
-    if (files.length > 0) {
-      console.log(5555)
-      console.log(files)
+    if (files.length > 0)
       handleAdd()
-    }
   }, { wait: 500 })
   getFiles()
   const handleDel = useCallback(async () => {
     try {
-      const { result }: any = await delMouldFile({
-        url: '/workspaces/123123',
-        body: { id: delId },
+      await delMouldFile({
+        url: `/datasets/template/${delId}`,
       })
-      if (result === 'success')
-        mutate()
+      setShowConfirmDelete(false)
+      mutate()
     }
     catch (e) { }
   }, [delId])
@@ -136,32 +137,43 @@ const DetailModel = ({
                 <div key={file.id} className='flex w-full items-center rounded border border-[#E0E3E8] bg-[#F3F4F8] px-4 py-3'>
                   <div>
                     {
-                      (file.fileName.includes('.xls') || file.fileName.includes('.xlsx')) && (
+                      (file.name.includes('.xls') || file.name.includes('.xlsx')) && (
                         <img src="/imgs/excel.png"/>
                       )
                     }
                     {
-                      (file.fileName.includes('.doc') || file.fileName.includes('.docx')) && (
+                      (file.name.includes('.doc') || file.name.includes('.docx')) && (
                         <img src="/imgs/word.png"/>
                       )
                     }
                     {
-                      (file.fileName.includes('.ppt') || file.fileName.includes('.pptx')) && (
+                      (file.name.includes('.ppt') || file.name.includes('.pptx')) && (
                         <img src="/imgs/ppt.png"/>
                       )
                     }
+                    {
+                      (file.name.includes('.pdf')) && (
+                        <img src="/imgs/pdf.png"/>
+                      )
+                    }
+                    {
+                      (file.name.includes('.csv')) && (
+                        <img src="/imgs/csv.png"/>
+                      )
+                    }
                   </div>
-                  <div className="ml-2">{file.fileName}</div>
-                  <div className="cursor ml-auto" onClick={(e) => {
+                  <div className="ml-2 text-sm">{file.name}</div>
+                  <div className="ml-auto cursor-pointer" onClick={(e) => {
                     e.stopPropagation()
-                    downloadFile(`/files/${file.id}/file-preview?timestamp=${new Date().getTime()}` || '', file.fileName)
+                    downloadFile(`/files/${file.id}/file-preview?timestamp=${new Date().getTime()}` || '', file.name)
                   }}>
                     <img src="/imgs/download.png"/>
                   </div>
                   {
                     transfer.mode === 'manage' && (
-                      <div className="cursor ml-5" onClick={() => {
+                      <div className="ml-5 cursor-pointer" onClick={() => {
                         setDelId(file.id)
+                        setDelFileName(file.name)
                         setShowConfirmDelete(true)
                       }}>
                         <img src="/imgs/del.png"/>

二进制
web/public/imgs/csv.png


二进制
web/public/imgs/pdf.png


+ 1 - 1
web/service/base.ts

@@ -312,7 +312,7 @@ export const upload = (options: any, isPublicAPI?: boolean, url?: string, search
     xhr.responseType = 'json'
     xhr.onreadystatechange = function () {
       if (xhr.readyState === 4) {
-        if (xhr.status === 201)
+        if (xhr.status === 201 || xhr.status === 200)
           resolve(xhr.response)
         else
           reject(xhr)

+ 27 - 38
web/service/common.ts

@@ -1,5 +1,5 @@
 import type { Fetcher } from 'swr'
-import { del, get, patch, post, put } from './base'
+import { del, get, patch, post, put, upload } from './base'
 import type {
   AccountIntegrate,
   ApiBasedExtension,
@@ -122,7 +122,7 @@ export const fetchTypes = ({ url, params }: any) => {
 }
 
 export const fetchKnowledges = ({ url, params }: any) => {
-  console.log('查询知识服务')
+  console.log('查询知识服务', params, url)
   return get(url, { params })
   // return new Promise((resolve) => {
   //   setTimeout(() => {
@@ -144,24 +144,24 @@ export const fetchKnowledges = ({ url, params }: any) => {
   // })
 }
 
-export const fetchMoulds = ({ url, params }) => {
-  // return get<{ accounts: Member[] | null }>(url, { params })
-  console.log('查询知识库模板')
-  return new Promise((resolve) => {
-    setTimeout(() => {
-      const arr: any = []
-      for (let i = 1; i < 2; i++) {
-        // /files/7be8a2ca-a633-473c-8bcf-b73ee9fd7738/file-preview?timestamp=1744947616&nonce=a4107f3e163bbb0da255914e2ccabaf3&sign=H82Wk2VbWjXXEyzRUhGyNQlR-PG8NEGy5ijCEF0IKgo=
-        arr.push({
-          id: '7be8a2ca-a633-473c-8bcf-b73ee9fd7738',
-          fileName: `文件${i}.doc`,
-        })
-      }
-      resolve({
-        data: arr,
-      })
-    }, 1000)
-  })
+export const fetchMoulds = ({ url, params }: any) => {
+  console.log('查询知识库模板', params, url)
+  return get<{ accounts: Member[] | null }>(url, { params })
+  // return new Promise((resolve) => {
+  //   setTimeout(() => {
+  //     const arr: any = []
+  //     for (let i = 1; i < 2; i++) {
+  //       // /files/7be8a2ca-a633-473c-8bcf-b73ee9fd7738/file-preview?timestamp=1744947616&nonce=a4107f3e163bbb0da255914e2ccabaf3&sign=H82Wk2VbWjXXEyzRUhGyNQlR-PG8NEGy5ijCEF0IKgo=
+  //       arr.push({
+  //         id: '7be8a2ca-a633-473c-8bcf-b73ee9fd7738',
+  //         fileName: `文件${i}.doc`,
+  //       })
+  //     }
+  //     resolve({
+  //       data: arr,
+  //     })
+  //   }, 1000)
+  // })
 }
 
 export const fetchProviders: Fetcher<Provider[] | null, { url: string; params: Record<string, any> }> = ({ url, params }) => {
@@ -222,27 +222,16 @@ export const delKnowledge = ({ url, body }: any) => {
 }
 
 export const addMouldFile = ({ url, body }: any) => {
-  // return post<InvitationResponse>(url, { body })
-  console.log('新增模板文件', body)
-  return new Promise((resolve) => {
-    setTimeout(() => {
-      resolve({
-        result: 'success',
-      })
-    }, 1000)
-  })
+  console.log('新增模板文件', body, url)
+  return upload({
+    xhr: new XMLHttpRequest(),
+    data: body,
+  }, false, url)
 }
 
 export const delMouldFile = ({ url, body }: any) => {
-  // return post<InvitationResponse>(url, { body })
-  console.log('删除模板文件', body)
-  return new Promise((resolve) => {
-    setTimeout(() => {
-      resolve({
-        result: 'success',
-      })
-    }, 1000)
-  })
+  console.log('删除模板文件', url)
+  return del(url)
 }
 
 export const handleExamine = ({ url, body }: any) => {