aboutsummaryrefslogtreecommitdiffstats
path: root/frontend/src/lib/api.ts
blob: e654007b480befe4c20f8dc3ece3110556c4b26a (plain) (blame)
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
// API base URL
const API_BASE_URL = 'http://localhost:8080/api/v1';

// Helper function for fetching data with authorization
async function fetchWithAuth(url: string, options: RequestInit = {}) {
  // Get token from local storage
  const token = localStorage.getItem('token');
  
  // Set up headers with authorization
  const headers = {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
    ...options.headers
  };

  // Perform fetch
  const response = await fetch(`${API_BASE_URL}${url}`, {
    ...options,
    headers
  });

  // Handle unauthorized responses
  if (response.status === 401) {
    localStorage.removeItem('token');
    window.location.href = '/login';
    throw new Error('Unauthorized');
  }

  // Parse response
  if (!response.ok) {
    const errorData = await response.json().catch(() => null);
    throw new Error(errorData?.error || `API Error: ${response.status}`);
  }

  return response.json();
}

// Auth API
export const authApi = {
  login: async (email: string, password: string) => {
    const response = await fetch(`${API_BASE_URL}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => null);
      throw new Error(errorData?.error || 'Login failed');
    }

    const data = await response.json();
    localStorage.setItem('token', data.token);
    return data;
  },
  
  signup: async (name: string, email: string, password: string) => {
    const response = await fetch(`${API_BASE_URL}/auth/signup`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, password })
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => null);
      throw new Error(errorData?.error || 'Signup failed');
    }

    return response.json();
  },
  
  logout: () => {
    localStorage.removeItem('token');
    window.location.href = '/login';
  }
};

// Account API
export interface Account {
  ID: number;
  CreatedAt: string;
  UpdatedAt: string;
  DeletedAt: string | null;
  UserID: number;
  Name: string;
  Type: string;
  Balance: number;
}

export interface AccountInput {
  name: string;
  type: string;
  balance: number;
}

export const accountApi = {
  getAccounts: () => fetchWithAuth('/accounts'),
  getAccount: (id: number) => fetchWithAuth(`/accounts/${id}`),
  createAccount: (account: AccountInput) => fetchWithAuth('/accounts', {
    method: 'POST',
    body: JSON.stringify(account)
  }),
  updateAccount: (id: number, account: Partial<AccountInput>) => fetchWithAuth(`/accounts/${id}`, {
    method: 'PUT',
    body: JSON.stringify(account)
  }),
  deleteAccount: (id: number) => fetchWithAuth(`/accounts/${id}`, {
    method: 'DELETE'
  })
};

// Transaction API
export interface Transaction {
  ID: number;
  CreatedAt: string;
  UpdatedAt: string;
  DeletedAt: string | null;
  UserID: number;
  AccountID: number | null;
  Description: string;
  Amount: number;
  Type: "Income" | "Expense";
  Date: string;
  Category: string;
}

export interface TransactionInput {
  description: string;
  amount: number;
  type: "Income" | "Expense";
  date: string; // YYYY-MM-DD format
  category: string;
  accountId?: number;
}

export interface TransactionFilters {
  type?: "Income" | "Expense";
  accountId?: number;
  category?: string;
  startDate?: string; // YYYY-MM-DD format
  endDate?: string; // YYYY-MM-DD format
}

export const transactionApi = {
  getTransactions: (filters?: TransactionFilters) => {
    let queryParams = '';
    
    if (filters) {
      const params = new URLSearchParams();
      if (filters.type) params.append('type', filters.type);
      if (filters.accountId) params.append('account_id', filters.accountId.toString());
      if (filters.category) params.append('category', filters.category);
      if (filters.startDate) params.append('start_date', filters.startDate);
      if (filters.endDate) params.append('end_date', filters.endDate);
      
      queryParams = `?${params.toString()}`;
    }
    
    return fetchWithAuth(`/transactions${queryParams}`);
  },
  
  getTransaction: (id: number) => fetchWithAuth(`/transactions/${id}`),
  
  createTransaction: (transaction: TransactionInput) => fetchWithAuth('/transactions', {
    method: 'POST',
    body: JSON.stringify(transaction)
  }),
  
  updateTransaction: (id: number, transaction: Partial<TransactionInput>) => fetchWithAuth(`/transactions/${id}`, {
    method: 'PUT',
    body: JSON.stringify(transaction)
  }),
  
  deleteTransaction: (id: number) => fetchWithAuth(`/transactions/${id}`, {
    method: 'DELETE'
  })
};

// Loan API
export interface Loan {
  ID: number;
  CreatedAt: string;
  UpdatedAt: string;
  DeletedAt: string | null;
  UserID: number;
  AccountID: number | null;
  Name: string;
  OriginalAmount: number;
  CurrentBalance: number;
  InterestRate: number;
  StartDate: string;
  EndDate: string;
}

export interface LoanInput {
  name: string;
  originalAmount: number;
  currentBalance: number;
  interestRate: number;
  startDate: string;
  endDate: string;
  accountId?: number;
}

export const loanApi = {
  getLoans: () => fetchWithAuth('/loans'),
  getLoan: (id: number) => fetchWithAuth(`/loans/${id}`),
  createLoan: (loan: LoanInput) => fetchWithAuth('/loans', {
    method: 'POST',
    body: JSON.stringify(loan)
  }),
  updateLoan: (id: number, loan: Partial<LoanInput>) => fetchWithAuth(`/loans/${id}`, {
    method: 'PUT',
    body: JSON.stringify(loan)
  }),
  deleteLoan: (id: number) => fetchWithAuth(`/loans/${id}`, {
    method: 'DELETE'
  })
};

// User API
export const userApi = {
  getProfile: () => fetchWithAuth('/users/me')
};