Files
goal-planner/frontend/services/apiService.ts
T
2026-11-02 16:43:15 +08:00

429 lines
13 KiB
TypeScript

import { currentText } from '../i18n/translations';
const API_BASE_URL = '/api-proxy';
function getAuthHeaders(): Record<string, string> {
const token = localStorage.getItem('token');
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
};
}
export interface User {
id: number;
name: string;
email: string;
xp?: number;
}
export type TaskPriority = 'low' | 'medium' | 'high';
export interface Task {
id: number;
plan_id: number;
parent_id: number | null;
task_id: string;
title: string;
description: string;
dependencies: string[];
durationInHours: number;
priority: TaskPriority;
dueDate: string | null;
status: 'todo' | 'in_progress' | 'done';
sortOrder: number;
children: Task[];
}
export interface Plan {
id: number;
user_id: number;
goal: string;
created_at: string;
tasks: Task[];
}
function mapTask(t: any): Task {
return {
id: t.id,
plan_id: t.plan_id,
parent_id: t.parent_id ?? null,
task_id: t.task_id,
title: t.title,
description: t.description,
dependencies: t.dependencies || [],
durationInHours: t.duration_in_hours,
priority: t.priority || 'medium',
dueDate: t.due_date || null,
status: t.status,
sortOrder: t.sort_order || 0,
children: (t.children || []).map(mapTask),
};
}
export const registerUser = async (name: string, email: string, password: string): Promise<User> => {
const response = await fetch(`${API_BASE_URL}/api/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email, password }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('registerFail'));
}
return response.json();
};
export const loginUser = async (email: string, password: string): Promise<{ token: string; user: User }> => {
const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('loginFail'));
}
const data = await response.json();
localStorage.setItem('token', data.access_token);
// Fetch full user info (including xp) from /me endpoint using Authorization header
const userResponse = await fetch(`${API_BASE_URL}/api/auth/me`, {
headers: { 'Authorization': `Bearer ${data.access_token}` },
});
let user: User;
if (userResponse.ok) {
user = await userResponse.json();
} else {
// Fallback to token payload
const userPayload = decodeToken(data.access_token);
user = {
id: parseInt(userPayload.sub),
name: userPayload.name,
email: userPayload.email,
};
}
localStorage.setItem('user', JSON.stringify(user));
return { token: data.access_token, user };
};
export const getCurrentUser = async (): Promise<User | null> => {
const token = localStorage.getItem('token');
if (!token) return null;
const savedUser = localStorage.getItem('user');
try {
const response = await fetch(`${API_BASE_URL}/api/auth/me`, {
headers: { 'Authorization': `Bearer ${token}` },
});
if (!response.ok) {
localStorage.removeItem('token');
localStorage.removeItem('user');
return null;
}
const user = await response.json();
localStorage.setItem('user', JSON.stringify(user));
return user;
} catch {
if (savedUser) {
try {
return JSON.parse(savedUser);
} catch {
// Ignore
}
}
localStorage.removeItem('token');
localStorage.removeItem('user');
return null;
}
};
export interface GenerateProgressEvent {
type: 'progress' | 'complete' | 'error';
step?: string;
progress: number;
message: string;
data?: any;
}
export const generatePlan = async (
goal: string,
additionalInfo?: string,
onProgress?: (event: GenerateProgressEvent) => void
): Promise<Plan> => {
const token = localStorage.getItem('token');
if (!token) throw new Error(currentText('notAuthenticated'));
const response = await fetch(`${API_BASE_URL}/api/generate/`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ goal, additional_info: additionalInfo || "" }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('generateFail'));
}
if (!response.body) {
throw new Error(currentText('streamUnsupported'));
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let resultData: any = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed.startsWith('data: ')) continue;
try {
const event: GenerateProgressEvent = JSON.parse(trimmed.slice(6));
if (event.type === 'error') {
throw new Error(event.message);
}
if (event.type === 'progress' && onProgress) {
onProgress(event);
}
if (event.type === 'complete') {
resultData = event.data;
if (onProgress) onProgress(event);
}
} catch (e) {
if (e instanceof Error && e.message !== 'Unexpected end of JSON input') {
throw e;
}
}
}
}
if (!resultData) {
throw new Error(currentText('noResult'));
}
return {
id: resultData.plan_id,
user_id: resultData.user_id,
goal: resultData.goal,
created_at: resultData.created_at,
tasks: (resultData.tasks || []).map(mapTask),
};
};
export const getUserPlans = async (): Promise<Plan[]> => {
const response = await fetch(`${API_BASE_URL}/api/plans/`, {
headers: getAuthHeaders(),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('fetchPlansFail'));
}
const data = await response.json();
return data.map((plan: any) => ({
...plan,
tasks: (plan.tasks || []).map(mapTask),
}));
};
export const getPlan = async (planId: number): Promise<Plan> => {
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}`, {
headers: getAuthHeaders(),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('fetchPlanFail'));
}
const data = await response.json();
return {
...data,
tasks: (data.tasks || []).map(mapTask),
};
};
export const deletePlan = async (planId: number): Promise<void> => {
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('deletePlanFail'));
}
};
export const updateTask = async (planId: number, taskDbId: number, updates: Partial<Task>): Promise<Task> => {
const body: Record<string, any> = {};
if (updates.title !== undefined) body.title = updates.title;
if (updates.description !== undefined) body.description = updates.description;
if (updates.dependencies !== undefined) body.dependencies = updates.dependencies;
if (updates.durationInHours !== undefined) body.duration_in_hours = updates.durationInHours;
if (updates.priority !== undefined) body.priority = updates.priority;
if (updates.dueDate !== undefined) body.due_date = updates.dueDate;
if (updates.sortOrder !== undefined) body.sort_order = updates.sortOrder;
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}/tasks/${taskDbId}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(body),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('updateTaskFail'));
}
const data = await response.json();
return mapTask(data);
};
export interface StatusChange {
id: number;
status: string;
}
export interface StatusUpdateResult {
changes: StatusChange[];
xp_change: number;
all_done_bonus: number;
user_xp: number;
user_level: number;
level_up: boolean;
old_level: number;
new_level: number;
}
export interface CreateTaskParams {
task_id: string;
title: string;
description: string;
parent_id?: number | null;
dependencies?: string[];
durationInHours?: number;
priority?: TaskPriority;
dueDate?: string | null;
status?: string;
sortOrder?: number;
}
export const createTask = async (planId: number, params: CreateTaskParams): Promise<Task> => {
const body: Record<string, any> = {
task_id: params.task_id,
title: params.title,
description: params.description,
parent_id: params.parent_id ?? null,
dependencies: params.dependencies || [],
duration_in_hours: params.durationInHours ?? 0,
priority: params.priority || 'medium',
due_date: params.dueDate ?? null,
status: params.status || 'todo',
sort_order: params.sortOrder ?? 0,
};
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}/tasks`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(body),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('createTaskFail'));
}
const data = await response.json();
return mapTask(data);
};
export const deleteTask = async (planId: number, taskDbId: number): Promise<{ deleted_ids: number[] }> => {
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}/tasks/${taskDbId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('deleteTaskFail'));
}
const data = await response.json();
return { deleted_ids: data.deleted_ids || [taskDbId] };
};
export const updateTaskStatus = async (planId: number, taskDbId: number, status: string): Promise<StatusUpdateResult> => {
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}/tasks/${taskDbId}/status?status=${encodeURIComponent(status)}`, {
method: 'PUT',
headers: getAuthHeaders(),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || currentText('updateStatusFail'));
}
const data = await response.json();
return {
changes: data.changes || [{ id: taskDbId, status }],
xp_change: data.xp_change || 0,
all_done_bonus: data.all_done_bonus || 0,
user_xp: data.user_xp || 0,
user_level: data.user_level || 0,
level_up: data.level_up || false,
old_level: data.old_level || 0,
new_level: data.new_level || 0,
};
};
export const reorderTasks = async (planId: number, taskOrders: { id: number; sort_order: number }[]): Promise<void> => {
const response = await fetch(`${API_BASE_URL}/api/plans/${planId}/tasks/reorder`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(taskOrders),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: '排序更新失败' }));
throw new Error(error.detail || currentText('reorderFail'));
}
};
function decodeToken(token: string): any {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
atob(base64)
.split('')
.map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
return JSON.parse(jsonPayload);
}
export const logout = (): void => {
localStorage.removeItem('token');
localStorage.removeItem('user');
};