Spaces:
Running
Running
File size: 13,149 Bytes
ce8f04a | 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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | /**
* DocumentUploadPanel β Upload PDF do projektu + RAG re-ingest
*
* Auth: always via apiClient (Clerk Bearer from ApiInterceptor).
* No query-string tokens (P0 security).
*/
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Upload, FileText, CheckCircle, XCircle, Loader2, RefreshCw, Trash2, AlertTriangle, Database, FileSearch } from 'lucide-react';
import toast from 'react-hot-toast';
import { apiClient, resolveApiBaseUrl } from '../../api/client';
interface ProjectDocument {
doc_id: string;
filename: string;
file_size_bytes: number;
status: 'uploaded' | 'processing' | 'indexed' | 'error';
parser_used: string | null;
chunks_count: number | null;
error_message: string | null;
uploaded_at: string;
indexed_at: string | null;
}
interface QuotaInfo {
current: number;
limit: number;
plan: string;
can_upload: boolean;
}
interface Props {
projectId: string;
/** @deprecated ignored β auth via Clerk/apiClient only */
token?: string;
}
// Kolor + ikona dla statusu indeksacji
function StatusBadge({ status }: { status: ProjectDocument['status'] }) {
const map = {
uploaded: { label: 'Oczekuje', color: '#f59e0b', bg: 'rgba(245,158,11,0.1)', Icon: Loader2 },
processing: { label: 'Indeksowanieβ¦', color: '#3b82f6', bg: 'rgba(59,130,246,0.1)', Icon: Loader2 },
indexed: { label: 'Gotowy', color: '#10b981', bg: 'rgba(16,185,129,0.1)', Icon: CheckCircle },
error: { label: 'BΕΔ
d parsera', color: '#ef4444', bg: 'rgba(239,68,68,0.1)', Icon: XCircle },
};
const { label, color, bg, Icon } = map[status] ?? map.uploaded;
const spinning = status === 'processing' || status === 'uploaded';
return (
<span style={{
display: 'inline-flex', alignItems: 'center', gap: 4,
padding: '2px 8px', borderRadius: 6, fontSize: '0.72rem',
fontWeight: 700, background: bg, color,
}}>
<Icon size={11} style={spinning ? { animation: 'spin 1s linear infinite' } : {}} />
{label}
</span>
);
}
function fmtBytes(b: number) {
if (b < 1024) return `${b} B`;
if (b < 1024 * 1024) return `${(b / 1024).toFixed(0)} KB`;
return `${(b / (1024 * 1024)).toFixed(1)} MB`;
}
export default function DocumentUploadPanel({ projectId }: Props) {
const [docs, setDocs] = useState<ProjectDocument[]>([]);
const [quota, setQuota] = useState<QuotaInfo | null>(null);
const [dragging, setDragging] = useState(false);
const [uploading, setUploading] = useState(false);
const [loadingList, setLoadingList] = useState(true);
const [docType, setDocType] = useState<'knowledge_base' | 'external_grant'>('knowledge_base');
const fileInputRef = useRef<HTMLInputElement>(null);
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
/* ββ Fetch listy dokumentΓ³w ββββββββββββββββββββββββββββββββββββββββββββββ */
const fetchDocs = useCallback(async () => {
try {
const { data } = await apiClient.get(`/api/projects/${projectId}/documents`);
setDocs(data.documents || []);
if (data.quota) setQuota(data.quota);
} catch {
// sieΔ / 401 handled by interceptor
} finally {
setLoadingList(false);
}
}, [projectId]);
/* ββ Polling co 3s gdy jest document w trakcie przetwarzania ββββββββββββ */
useEffect(() => {
fetchDocs();
}, [fetchDocs]);
useEffect(() => {
const hasPending = docs.some(d => d.status === 'processing' || d.status === 'uploaded');
if (hasPending && !pollingRef.current) {
pollingRef.current = setInterval(fetchDocs, 3000);
} else if (!hasPending && pollingRef.current) {
clearInterval(pollingRef.current);
pollingRef.current = null;
}
return () => {
if (pollingRef.current) clearInterval(pollingRef.current);
};
}, [docs, fetchDocs]);
/* ββ Upload ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
const uploadFile = async (file: File) => {
if (!file.name.toLowerCase().endsWith('.pdf')) {
toast.error('ObsΕugiwane sΔ
wyΕΔ
cznie pliki PDF.');
return;
}
if (file.size > 20 * 1024 * 1024) {
toast.error('Plik przekracza limit 20 MB.');
return;
}
if (quota && !quota.can_upload) {
toast.error(
quota.plan === 'free'
? `OsiΔ
gniΔto limit ${quota.limit} plikΓ³w na planie Free. PrzejdΕΊ na plan Pro.`
: `OsiΔ
gniΔto limit ${quota.limit} plikΓ³w dla tego projektu.`,
{ duration: 5000 }
);
return;
}
setUploading(true);
const form = new FormData();
form.append('file', file);
try {
const { data, status } = await apiClient.post(
`/api/projects/${projectId}/documents`,
form,
{
params: { doc_type: docType },
headers: { 'Content-Type': 'multipart/form-data' },
validateStatus: (s) => s < 500,
}
);
if (status === 429) {
const msg = typeof data?.detail === 'object'
? data.detail.message
: data?.detail;
toast.error(msg || 'Przekroczono limit plikΓ³w dla tego planu.', { duration: 6000 });
await fetchDocs();
} else if (status >= 400) {
toast.error(
(typeof data?.detail === 'string' ? data.detail : data?.detail?.message) || 'BΕΔ
d uploadu.'
);
} else {
toast.success(`π "${file.name}" wgrany. Przetwarzanie w tokuβ¦`);
await fetchDocs();
}
} catch {
toast.error('BΕΔ
d poΕΔ
czenia z serwerem.');
} finally {
setUploading(false);
}
};
const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) uploadFile(file);
e.target.value = '';
};
const onDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragging(false);
const file = e.dataTransfer.files?.[0];
if (file) uploadFile(file);
};
/* ββ Re-ingest βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
const reingest = async (docId: string) => {
try {
await apiClient.post(`/api/projects/${projectId}/documents/${docId}/reingest`);
toast.success('Ponowna indeksacja uruchomiona.');
fetchDocs();
} catch {
toast.error('BΕΔ
d ponownej indeksacji.');
}
};
/* ββ Delete ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
const deleteDoc = async (docId: string, filename: string) => {
if (!window.confirm(`UsunΔ
Δ "${filename}" z projektu?`)) return;
try {
await apiClient.delete(`/api/projects/${projectId}/documents/${docId}`);
toast.success('Dokument usuniΔty.');
setDocs(d => d.filter(x => x.doc_id !== docId));
} catch {
toast.error('BΕΔ
d usuwania.');
}
};
/* ββ Render ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
const baseHint = resolveApiBaseUrl(import.meta.env.VITE_API_URL);
return (
<div style={{ maxWidth: 820, margin: '2rem auto', padding: '0 1rem', display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<Database size={20} color="#3b82f6" />
<div>
<h3 style={{ margin: 0, fontSize: '1.05rem' }}>Baza wiedzy projektu (RAG)</h3>
<p style={{ margin: '4px 0 0', fontSize: '0.8rem', color: '#64748b' }}>
PDF regulaminΓ³w i dokumentΓ³w firmowych β indeksowane do dopasowaΕ i generatora.
</p>
</div>
</div>
{quota && (
<div style={{
fontSize: '0.8rem', color: quota.can_upload ? '#64748b' : '#b45309',
padding: '8px 12px', borderRadius: 8,
background: quota.can_upload ? 'rgba(100,116,139,0.08)' : 'rgba(245,158,11,0.12)',
}}>
Limit: {quota.current}/{quota.limit} plikΓ³w (plan {quota.plan})
</div>
)}
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button
type="button"
onClick={() => setDocType('knowledge_base')}
style={{
padding: '6px 12px', borderRadius: 8, border: '1px solid #e2e8f0',
background: docType === 'knowledge_base' ? '#eff6ff' : '#fff',
fontWeight: 600, fontSize: '0.8rem', cursor: 'pointer',
}}
>
<FileSearch size={14} style={{ verticalAlign: 'middle', marginRight: 4 }} />
Baza wiedzy
</button>
<button
type="button"
onClick={() => setDocType('external_grant')}
style={{
padding: '6px 12px', borderRadius: 8, border: '1px solid #e2e8f0',
background: docType === 'external_grant' ? '#eff6ff' : '#fff',
fontWeight: 600, fontSize: '0.8rem', cursor: 'pointer',
}}
>
<FileText size={14} style={{ verticalAlign: 'middle', marginRight: 4 }} />
Wniosek / regulamin zewnΔtrzny
</button>
</div>
<div
onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
onDragLeave={() => setDragging(false)}
onDrop={onDrop}
onClick={() => fileInputRef.current?.click()}
style={{
border: `2px dashed ${dragging ? '#3b82f6' : '#cbd5e1'}`,
borderRadius: 12, padding: '2rem', textAlign: 'center',
background: dragging ? 'rgba(59,130,246,0.06)' : '#f8fafc',
cursor: uploading ? 'wait' : 'pointer',
}}
>
<input
ref={fileInputRef}
type="file"
accept="application/pdf,.pdf"
style={{ display: 'none' }}
onChange={onFileChange}
/>
{uploading ? (
<Loader2 size={28} style={{ animation: 'spin 1s linear infinite', color: '#3b82f6' }} />
) : (
<Upload size={28} color="#64748b" />
)}
<p style={{ margin: '12px 0 0', fontWeight: 600 }}>
{uploading ? 'WysyΕanieβ¦' : 'UpuΕΔ PDF lub kliknij, aby wybraΔ'}
</p>
<p style={{ margin: '6px 0 0', fontSize: '0.75rem', color: '#94a3b8' }}>
Max 20 MB Β· API: {baseHint || 'relative'}
</p>
</div>
{loadingList ? (
<div style={{ color: '#94a3b8', fontSize: '0.85rem' }}>Εadowanie listyβ¦</div>
) : docs.length === 0 ? (
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: 12, borderRadius: 8, background: 'rgba(245,158,11,0.08)', color: '#92400e',
fontSize: '0.85rem',
}}>
<AlertTriangle size={16} />
Brak wgranych dokumentΓ³w. Dodaj regulamin programu dla wiarygodnej generacji.
</div>
) : (
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
{docs.map((d) => (
<li
key={d.doc_id}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 12px', borderRadius: 10, border: '1px solid #e2e8f0', background: '#fff',
}}
>
<FileText size={18} color="#64748b" />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: '0.9rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{d.filename}
</div>
<div style={{ fontSize: '0.72rem', color: '#94a3b8' }}>
{fmtBytes(d.file_size_bytes || 0)}
{d.chunks_count != null ? ` Β· ${d.chunks_count} chunkΓ³w` : ''}
{d.parser_used ? ` Β· ${d.parser_used}` : ''}
</div>
{d.error_message && (
<div style={{ fontSize: '0.72rem', color: '#ef4444' }}>{d.error_message}</div>
)}
</div>
<StatusBadge status={d.status} />
<button type="button" title="Re-ingest" onClick={() => reingest(d.doc_id)}
style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4 }}>
<RefreshCw size={15} color="#64748b" />
</button>
<button type="button" title="UsuΕ" onClick={() => deleteDoc(d.doc_id, d.filename)}
style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4 }}>
<Trash2 size={15} color="#ef4444" />
</button>
</li>
))}
</ul>
)}
</div>
);
}
|