File size: 4,930 Bytes
87337b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { FileTextIcon } from "lucide-react"

import { OptionType, IPdfData } from "@/types"
import {
  apiGetDocumentList,
  apiUpdateDocument,
  useAppSelector,
  genUUID,
} from "@/common"
import { toast } from "sonner"

export default function PdfSelect() {
  const options = useAppSelector((state) => state.global.options)
  const { channel, userId } = options
  const [pdfOptions, setPdfOptions] = React.useState<OptionType[]>([])
  const [selectedPdf, setSelectedPdf] = React.useState<string>("")
  const agentConnected = useAppSelector((state) => state.global.agentConnected)

  React.useEffect(() => {
    if (agentConnected) {
      getPDFOptions()
    }
  }, [agentConnected])

  const getPDFOptions = async () => {
    const res = await apiGetDocumentList()
    setPdfOptions(
      res.data.map((item: any) => {
        return {
          value: item.collection,
          label: item.file_name,
        }
      }),
    )
    setSelectedPdf("")
  }

  const onUploadSuccess = (data: IPdfData) => {
    setPdfOptions([
      ...pdfOptions,
      {
        value: data.collection,
        label: data.fileName,
      },
    ])
    setSelectedPdf(data.collection)
  }

  const onSelectPdf = async (val: string) => {
    const item = pdfOptions.find((item) => item.value === val)
    if (!item) {
      //   return message.error("Please select a PDF file")
      return
    }
    setSelectedPdf(val)
    await apiUpdateDocument({
      collection: val,
      fileName: item.label,
      channel,
    })
  }

  return (
    <>
      <Dialog>
        <DialogTrigger asChild>
          <Button variant="outline" size="sm" className="w-fit bg-transparent">
            <FileTextIcon />
            PDF
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>Upload & Select PDF</DialogTitle>
          </DialogHeader>
          <UploadPdf onSuccess={onUploadSuccess} />
          <div className="mt-4">
            <Select
              value={selectedPdf}
              onValueChange={onSelectPdf}
              disabled={!agentConnected}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select a PDF file" />
              </SelectTrigger>
              <SelectContent>
                {pdfOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}

export function UploadPdf({
  onSuccess,
}: {
  onSuccess?: (data: IPdfData) => void
}) {
  const agentConnected = useAppSelector((state) => state.global.agentConnected)
  const options = useAppSelector((state) => state.global.options)
  const { channel, userId } = options
  const [uploading, setUploading] = React.useState(false)

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!agentConnected) {
      toast.error("Please connect to agent first")
      return
    }

    const file = e.target.files?.[0]
    if (!file) return

    setUploading(true)

    const formData = new FormData()
    formData.append("file", file)
    formData.append("channel_name", channel)
    formData.append("uid", String(userId))
    formData.append("request_id", genUUID())

    try {
      const response = await fetch("/api/vector/document/upload", {
        method: "POST",
        body: formData,
      })
      const data = await response.json()

      if (data.code === "0") {
        toast.success(`Upload ${file.name} success`)
        const { collection, file_name } = data.data
        onSuccess?.({
          fileName: file_name,
          collection,
        })
      } else {
        toast.info(data.msg)
      }
    } catch (err) {
      toast.error(`Upload ${file.name} failed`)
    } finally {
      setUploading(false)
    }
  }

  return (
    <div>
      <Label htmlFor="pdf-upload" className="cursor-pointer">
        <Input
          id="pdf-upload"
          type="file"
          accept="application/pdf"
          className="hidden"
          onChange={handleUpload}
          disabled={uploading}
        />
        <Button variant="outline" size="sm" disabled={uploading} asChild>
          <span>{uploading ? "Uploading..." : "Upload PDF"}</span>
        </Button>
      </Label>
    </div>
  )
}