78 lines
2.5 KiB
TypeScript
78 lines
2.5 KiB
TypeScript
import { supabase } from './supabaseClient';
|
|
import { tradingRuntime } from './runtime';
|
|
|
|
export interface ManualEntryPayload {
|
|
stock_instance_id?: string;
|
|
symbol: string;
|
|
active: boolean;
|
|
user_id?: string;
|
|
buy_price?: number | null;
|
|
sell_price?: number | null;
|
|
buy_time?: string | null;
|
|
sell_time?: string | null;
|
|
quantity?: number | null;
|
|
filled_quantity?: number | null;
|
|
notes?: string | null;
|
|
status: string;
|
|
is_crypto: boolean;
|
|
is_real_trade: boolean;
|
|
label?: string | null;
|
|
entry_price?: number | null;
|
|
gain_threshold_for_sell?: number | null;
|
|
drop_threshold_for_buy?: number | null;
|
|
}
|
|
|
|
async function getAccessToken(): Promise<string> {
|
|
const { data: sessionData } = await supabase.auth.getSession();
|
|
const accessToken = sessionData.session?.access_token;
|
|
if (!accessToken) {
|
|
throw new Error('Not authenticated');
|
|
}
|
|
return accessToken;
|
|
}
|
|
|
|
async function apiRequest<T>(path: string, init?: RequestInit): Promise<T> {
|
|
const accessToken = await getAccessToken();
|
|
const response = await fetch(`${tradingRuntime.tradingApiUrl}${path}`, {
|
|
...init,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization: `Bearer ${accessToken}`,
|
|
...(init?.headers || {}),
|
|
},
|
|
});
|
|
|
|
const body = await response.json().catch(() => ({} as any));
|
|
if (!response.ok) {
|
|
throw new Error(body?.error || `Request failed (${response.status})`);
|
|
}
|
|
return body as T;
|
|
}
|
|
|
|
export async function fetchManualEntries(): Promise<ManualEntryPayload[]> {
|
|
const response = await apiRequest<{ entries: ManualEntryPayload[] }>('/api/manual-entries');
|
|
return Array.isArray(response.entries) ? response.entries : [];
|
|
}
|
|
|
|
export async function createManualEntry(payload: ManualEntryPayload): Promise<ManualEntryPayload> {
|
|
const response = await apiRequest<{ entry: ManualEntryPayload }>('/api/manual-entries', {
|
|
method: 'POST',
|
|
body: JSON.stringify(payload),
|
|
});
|
|
return response.entry;
|
|
}
|
|
|
|
export async function updateManualEntry(id: string, payload: ManualEntryPayload): Promise<ManualEntryPayload> {
|
|
const response = await apiRequest<{ entry: ManualEntryPayload }>(`/api/manual-entries/${id}`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify(payload),
|
|
});
|
|
return response.entry;
|
|
}
|
|
|
|
export async function deleteManualEntry(id: string): Promise<void> {
|
|
await apiRequest<{ success: boolean }>(`/api/manual-entries/${id}`, {
|
|
method: 'DELETE',
|
|
});
|
|
}
|