Spaces:
Running
Running
File size: 13,227 Bytes
afd56bc | 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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | import axios from 'axios';
import toast from 'react-hot-toast';
// Bazowy URL to backend
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL
? import.meta.env.VITE_API_URL.replace('/api', '')
: import.meta.env.VITE_LANGSERVE_URL
? import.meta.env.VITE_LANGSERVE_URL.replace('/api', '')
: 'http://localhost:8000',
headers: { 'Content-Type': 'application/json' },
});
// --- Interceptory ---
// Request: automatyczne wstrzykiwanie tokena Clerk
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token && !config.headers['Authorization']) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
// Response: obsługa błędów globalnych
apiClient.interceptors.response.use(
(response) => response,
(error) => {
const status = error?.response?.status;
if (status === 429) {
const retryAfter = error.response?.data?.retry_after;
const msg = retryAfter
? `Przekroczono limit zapytań. Spróbuj za ${retryAfter}s.`
: 'Przekroczono limit zapytań. Poczekaj chwilę.';
toast.error(`⏳ ${msg}`, { duration: 8000, id: 'rate-limit' });
}
return Promise.reject(error);
}
);
export const getSubscriptionStatus = async () => {
// /api/me zwraca {tier, wizard_iterations_today, tokens_used_month, limits}
const { data } = await apiClient.get('/api/me');
return data;
};
export const getMe = getSubscriptionStatus;
export const deleteUserAccount = async () => {
const { data } = await apiClient.delete('/api/account');
return data;
};
export const getAccountExport = async () => {
const { data } = await apiClient.get('/api/account/export');
return data;
};
export const updateAccountSettings = async (settings: { gdpr_consent_accepted?: boolean; ai_disclaimer_enabled?: boolean }) => {
const { data } = await apiClient.post('/api/account/settings', settings);
return data;
};
export const submitFeedback = async (text: string, type: string = "feedback") => {
const { data } = await apiClient.post('/api/feedback', { text, type });
return data;
};
export const lookupCompany = async (nip: string) => {
const { data } = await apiClient.get(`/api/projects/lookup-company?nip=${nip}`);
return data;
};
export const getAdminStats = async () => {
const { data } = await apiClient.get('/api/admin/stats');
return data;
};
export const getCurrentSession = async () => {
// Stub w fazie bez połączenia pełnego PostgresSaver w backendzie
const { data } = await apiClient.get('/api/session/current').catch(() => ({ data: {
thread_id: "test-thread-123",
status: "wizard",
agent: "wizard",
critic_evaluation: { is_approved: false, feedback: "Brak sekcji z oceną ryzyka ekologicznego." },
tokens_used: 1250,
active_step: 3
} }));
return data;
};
// Projects API
export const getProjects = async () => {
const { data } = await apiClient.get('/api/projects');
return data;
};
export const getProject = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}`);
return data;
};
export const updateProject = async (projectId: string, updateData: any) => {
const { data } = await apiClient.put(`/api/projects/${projectId}`, updateData);
return data;
};
export const deleteProject = async (projectId: string) => {
await apiClient.delete(`/api/projects/${projectId}`);
};
export const createProject = async (projectData: { title: string; program_type: string; description?: string; program_name?: string; estimated_value?: number; external_context?: Record<string, any> }) => {
const { data } = await apiClient.post('/api/projects', projectData);
return data;
};
export const matchProgram = async (description: string, nip?: string) => {
const { data } = await apiClient.post('/api/projects/match-program', {
description: description,
nip: nip
});
return data;
};
export const createWelcomeSeed = async () => {
const { data } = await apiClient.post('/api/projects/welcome-seed');
return data;
};
// --- SECTION ENDPOINTS ---
export const getProjectSections = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/sections`);
return data;
};
export const generateProjectSection = async (projectId: string, sectionType: string, promptContext?: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/generate-section`, {
section_type: sectionType,
prompt_context: promptContext
});
return data;
};
// --- Q&A / VERIFIER ENDPOINTS ---
export const getProjectQuestionsHistory = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/ask/history`);
return data;
};
export const askProjectQuestion = async (projectId: string, question: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/ask`, { question });
return data;
};
export const clearProjectQuestionsHistory = async (projectId: string) => {
const { data } = await apiClient.delete(`/api/projects/${projectId}/ask/history`);
return data;
};
export const updateProjectSection = async (projectId: string, sectionId: string, content: string) => {
const { data } = await apiClient.put(`/api/projects/${projectId}/sections/${sectionId}`, {
content: content
});
return data;
};
export const reviewProjectSection = async (projectId: string, sectionType: string, content: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/review-section`, {
section_type: sectionType,
content: content
});
return data;
};
export interface SectionVersion {
id: string;
old_content: string;
author: string;
summary: string | null;
timestamp: string;
}
export const getSectionVersions = async (projectId: string, sectionId: string): Promise<SectionVersion[]> => {
const { data } = await apiClient.get(`/api/projects/${projectId}/sections/${sectionId}/versions`);
return data;
};
export const restoreSectionVersion = async (projectId: string, sectionId: string, versionId: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/sections/${sectionId}/versions/${versionId}/restore`);
return data;
};
export const previewProject = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/preview`);
return data;
};
export const compileFinalDocument = async (projectId: string, approvedOnly: boolean = false) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/compile-final`, {
approved_only: approvedOnly
});
return data;
};
export const auditFinalDocument = async (projectId: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/global-audit`);
return data;
};
export const clearGlobalAudit = async (projectId: string) => {
// Czyści wynik audytu przez zapis pustego stanu (backend nie ma DELETE /audit -
// resetujemy przez POST z flagą) – fallback do PATCH
try {
const { data } = await apiClient.delete(`/api/projects/${projectId}/global-audit`);
return data;
} catch {
// Backend może nie mieć DELETE — wrócimy z sukcesem, audit zostanie nadpisany przy kolejnym uruchomieniu
return { status: 'cleared' };
}
};
export const autofixProjectSection = async (projectId: string, sectionId: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/sections/${sectionId}/autofix`);
return data;
};
export const syncRAGKnowledge = async () => {
const { data } = await apiClient.post('/api/rag/sync', { category: "ALL" });
return data;
};
// --- CHATBOT PROJECT ENDPOINTS ---
export const getProjectChatHistory = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/chat`);
return data;
};
export const clearProjectChatHistory = async (projectId: string) => {
const { data } = await apiClient.delete(`/api/projects/${projectId}/chat`);
return data;
};
export const sendProjectChatMessage = async (projectId: string, content: string, activeSectionId?: string, activeSectionTitle?: string) => {
const payload: any = { content };
if (activeSectionId) {
payload.active_section = activeSectionId;
if (activeSectionTitle) payload.active_section_title = activeSectionTitle;
}
const { data } = await apiClient.post(`/api/projects/${projectId}/chat`, payload);
return data;
};
// --- EXPORT ENDPOINT ---
export const exportProjectDocument = async (projectId: string, format: string, template: string) => {
// Return the response so we can extract blob
return await apiClient.post(`/api/projects/${projectId}/export`, {
format,
template
}, {
responseType: 'blob' // Ważne, żeby Axios traktował to jako strumień binarny
});
};
export const getProjectVersions = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/versions`);
return data;
};
export const createProjectVersion = async (projectId: string, title?: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/versions`, { title });
return data;
};
export const exportProjectPDF = async (projectId: string, versionId?: string) => {
const payload: any = { format: 'pdf', template: 'standard' };
if (versionId) payload.version_id = versionId;
const response = await apiClient.post(`/api/projects/${projectId}/export`, payload, { responseType: 'blob' });
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', versionId ? `dotacja_v${versionId.substring(0, 6)}.pdf` : `dotacja_${projectId}.pdf`);
document.body.appendChild(link);
link.click();
link.remove();
};
export const exportProjectDOCX = async (projectId: string, approvedOnly: boolean = false, versionId?: string) => {
const payload: any = { format: 'docx', template: 'standard' };
if (versionId) payload.version_id = versionId;
const response = await apiClient.post(`/api/projects/${projectId}/export`, payload, { responseType: 'blob' });
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', versionId ? `dotacja_v${versionId.substring(0, 6)}.docx` : `dotacja_${projectId}.docx`);
document.body.appendChild(link);
link.click();
link.remove();
};
// --- EXTERNAL KNOWLEDGE / DOCUMENTS ENDPOINTS ---
export const uploadProjectDocument = async (projectId: string, file: File) => {
const formData = new FormData();
formData.append('file', file);
const { data } = await apiClient.post(`/api/projects/${projectId}/documents`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
return data;
};
export const getProjectDocuments = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/documents`);
return data;
};
export const deleteProjectDocument = async (projectId: string, filename: string) => {
const { data } = await apiClient.delete(`/api/projects/${projectId}/documents/${filename}`);
return data;
};
// --- AUDIT ENDPOINTS ---
export const getProjectAudit = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}`);
return data.final_document_audit_result;
};
export const runProjectAudit = async (projectId: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/global-audit`);
return data;
};
export const getHolisticReview = async (projectId: string) => {
const { data } = await apiClient.get(`/api/projects/${projectId}/holistic-review`);
return data;
};
export const runHolisticReview = async (projectId: string) => {
const { data } = await apiClient.post(`/api/projects/${projectId}/holistic-review`);
return data;
};
// --- GRANTS / NABORY ENDPOINTS ---
export const getGrantNabory = async (forceRefresh = false) => {
const { data } = await apiClient.get('/api/grants/nabory', {
params: { force_refresh: forceRefresh },
});
return data as { status: string; count: number; nabory: any[] };
};
export interface UserAnswer {
question: string;
answer: string;
}
export const matchGrantsForProject = async (projectId: string, userAnswers: UserAnswer[] = []) => {
const { data } = await apiClient.post('/api/grants/match', {
project_id: projectId,
user_answers: userAnswers
});
return data as { status: string; project_id: string; needs_more_info: boolean; clarifying_questions: string[]; matches: any[] };
};
// --- HEALTH ---
export const getApiHealth = async () => {
const { data } = await apiClient.get('/api/health');
return data;
};
|