Refactor API layer into structured domain-specific modules
- Created new api/ directory with domain-specific API modules: - api/client.ts: Base API client with error handling - api/auth.ts: Authentication endpoints - api/exchange.ts: Exchange/price endpoints - api/trades.ts: User trade endpoints - api/profile.ts: Profile management endpoints - api/invites.ts: Invite endpoints - api/admin.ts: Admin endpoints - api/index.ts: Centralized exports - Migrated all API calls from ad-hoc api.get/post/put to typed domain APIs - Updated all imports across codebase - Fixed test mocks to use new API structure - Fixed type issues in validation utilities - Removed old api.ts file Benefits: - Type-safe endpoints (no more string typos) - Centralized API surface (easy to discover endpoints) - Better organization (domain-specific modules) - Uses generated OpenAPI types automatically
This commit is contained in:
parent
6d0f125536
commit
a6fa6a8012
24 changed files with 529 additions and 255 deletions
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import { Permission } from "../../auth-context";
|
import { Permission } from "../../auth-context";
|
||||||
import { api } from "../../api";
|
import { adminApi } from "../../api";
|
||||||
import { Header } from "../../components/Header";
|
import { Header } from "../../components/Header";
|
||||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||||
import { components } from "../../generated/api";
|
import { components } from "../../generated/api";
|
||||||
|
|
@ -25,7 +25,6 @@ import {
|
||||||
const { slotDurationMinutes, maxAdvanceDays, minAdvanceDays } = constants.exchange;
|
const { slotDurationMinutes, maxAdvanceDays, minAdvanceDays } = constants.exchange;
|
||||||
|
|
||||||
type _AvailabilityDay = components["schemas"]["AvailabilityDay"];
|
type _AvailabilityDay = components["schemas"]["AvailabilityDay"];
|
||||||
type AvailabilityResponse = components["schemas"]["AvailabilityResponse"];
|
|
||||||
type TimeSlot = components["schemas"]["TimeSlot"];
|
type TimeSlot = components["schemas"]["TimeSlot"];
|
||||||
|
|
||||||
// Generate time options for dropdowns (15-min intervals)
|
// Generate time options for dropdowns (15-min intervals)
|
||||||
|
|
@ -73,9 +72,7 @@ export default function AdminAvailabilityPage() {
|
||||||
try {
|
try {
|
||||||
const fromDate = formatDate(dateRange[0]);
|
const fromDate = formatDate(dateRange[0]);
|
||||||
const toDate = formatDate(dateRange[dateRange.length - 1]);
|
const toDate = formatDate(dateRange[dateRange.length - 1]);
|
||||||
const data = await api.get<AvailabilityResponse>(
|
const data = await adminApi.getAvailability(fromDate, toDate);
|
||||||
`/api/admin/availability?from=${fromDate}&to=${toDate}`
|
|
||||||
);
|
|
||||||
|
|
||||||
const map = new Map<string, TimeSlot[]>();
|
const map = new Map<string, TimeSlot[]>();
|
||||||
for (const day of data.days) {
|
for (const day of data.days) {
|
||||||
|
|
@ -140,7 +137,7 @@ export default function AdminAvailabilityPage() {
|
||||||
end_time: s.end_time + ":00",
|
end_time: s.end_time + ":00",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
await api.put("/api/admin/availability", {
|
await adminApi.updateAvailability({
|
||||||
date: formatDate(selectedDate),
|
date: formatDate(selectedDate),
|
||||||
slots,
|
slots,
|
||||||
});
|
});
|
||||||
|
|
@ -161,7 +158,7 @@ export default function AdminAvailabilityPage() {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.put("/api/admin/availability", {
|
await adminApi.updateAvailability({
|
||||||
date: formatDate(selectedDate),
|
date: formatDate(selectedDate),
|
||||||
slots: [],
|
slots: [],
|
||||||
});
|
});
|
||||||
|
|
@ -203,7 +200,7 @@ export default function AdminAvailabilityPage() {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.post("/api/admin/availability/copy", {
|
await adminApi.copyAvailability({
|
||||||
source_date: copySource,
|
source_date: copySource,
|
||||||
target_dates: Array.from(copyTargets),
|
target_dates: Array.from(copyTargets),
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import { Permission } from "../../auth-context";
|
import { Permission } from "../../auth-context";
|
||||||
import { api } from "../../api";
|
import { adminApi } from "../../api";
|
||||||
import { Header } from "../../components/Header";
|
import { Header } from "../../components/Header";
|
||||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||||
import { components } from "../../generated/api";
|
import { components } from "../../generated/api";
|
||||||
|
|
@ -41,7 +41,7 @@ export default function AdminInvitesPage() {
|
||||||
|
|
||||||
const fetchUsers = useCallback(async () => {
|
const fetchUsers = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const data = await api.get<UserOption[]>("/api/admin/users");
|
const data = await adminApi.getUsers();
|
||||||
setUsers(data);
|
setUsers(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to fetch users:", err);
|
console.error("Failed to fetch users:", err);
|
||||||
|
|
@ -51,11 +51,7 @@ export default function AdminInvitesPage() {
|
||||||
const fetchInvites = useCallback(async (page: number, status: string) => {
|
const fetchInvites = useCallback(async (page: number, status: string) => {
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
let url = `/api/admin/invites?page=${page}&per_page=10`;
|
const data = await adminApi.getInvites(page, 10, status || undefined);
|
||||||
if (status) {
|
|
||||||
url += `&status=${status}`;
|
|
||||||
}
|
|
||||||
const data = await api.get<PaginatedInvites>(url);
|
|
||||||
setData(data);
|
setData(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setData(null);
|
setData(null);
|
||||||
|
|
@ -80,7 +76,7 @@ export default function AdminInvitesPage() {
|
||||||
setCreateError(null);
|
setCreateError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.post("/api/admin/invites", {
|
await adminApi.createInvite({
|
||||||
godfather_id: parseInt(newGodfatherId),
|
godfather_id: parseInt(newGodfatherId),
|
||||||
});
|
});
|
||||||
setNewGodfatherId("");
|
setNewGodfatherId("");
|
||||||
|
|
@ -95,7 +91,7 @@ export default function AdminInvitesPage() {
|
||||||
|
|
||||||
const handleRevoke = async (inviteId: number) => {
|
const handleRevoke = async (inviteId: number) => {
|
||||||
try {
|
try {
|
||||||
await api.post(`/api/admin/invites/${inviteId}/revoke`);
|
await adminApi.revokeInvite(inviteId);
|
||||||
setError(null);
|
setError(null);
|
||||||
fetchInvites(page, statusFilter);
|
fetchInvites(page, statusFilter);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import { Permission } from "../../auth-context";
|
import { Permission } from "../../auth-context";
|
||||||
import { api } from "../../api";
|
import { adminApi } from "../../api";
|
||||||
import { sharedStyles } from "../../styles/shared";
|
import { sharedStyles } from "../../styles/shared";
|
||||||
import { Header } from "../../components/Header";
|
import { Header } from "../../components/Header";
|
||||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||||
|
|
@ -24,7 +24,7 @@ export default function AdminPriceHistoryPage() {
|
||||||
setError(null);
|
setError(null);
|
||||||
setIsLoadingData(true);
|
setIsLoadingData(true);
|
||||||
try {
|
try {
|
||||||
const data = await api.get<PriceHistoryRecord[]>("/api/audit/price-history");
|
const data = await adminApi.getPriceHistory();
|
||||||
setRecords(data);
|
setRecords(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setRecords([]);
|
setRecords([]);
|
||||||
|
|
@ -38,7 +38,7 @@ export default function AdminPriceHistoryPage() {
|
||||||
setIsFetching(true);
|
setIsFetching(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
await api.post<PriceHistoryRecord>("/api/audit/price-history/fetch", {});
|
await adminApi.fetchPrice();
|
||||||
await fetchRecords();
|
await fetchRecords();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Failed to fetch price");
|
setError(err instanceof Error ? err.message : "Failed to fetch price");
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
||||||
import { Permission } from "../../auth-context";
|
import { Permission } from "../../auth-context";
|
||||||
import { api } from "../../api";
|
import { adminApi } from "../../api";
|
||||||
import { Header } from "../../components/Header";
|
import { Header } from "../../components/Header";
|
||||||
import { SatsDisplay } from "../../components/SatsDisplay";
|
import { SatsDisplay } from "../../components/SatsDisplay";
|
||||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||||
|
|
@ -47,7 +47,7 @@ export default function AdminTradesPage() {
|
||||||
|
|
||||||
const fetchUpcomingTrades = useCallback(async (): Promise<string | null> => {
|
const fetchUpcomingTrades = useCallback(async (): Promise<string | null> => {
|
||||||
try {
|
try {
|
||||||
const data = await api.get<AdminExchangeResponse[]>("/api/admin/trades/upcoming");
|
const data = await adminApi.getUpcomingTrades();
|
||||||
setUpcomingTrades(data);
|
setUpcomingTrades(data);
|
||||||
return null;
|
return null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
@ -58,21 +58,17 @@ export default function AdminTradesPage() {
|
||||||
|
|
||||||
const fetchPastTrades = useCallback(async (): Promise<string | null> => {
|
const fetchPastTrades = useCallback(async (): Promise<string | null> => {
|
||||||
try {
|
try {
|
||||||
let url = "/api/admin/trades/past";
|
const params: { status?: string; user_search?: string } = {};
|
||||||
const params = new URLSearchParams();
|
|
||||||
|
|
||||||
if (statusFilter !== "all") {
|
if (statusFilter !== "all") {
|
||||||
params.append("status", statusFilter);
|
params.status = statusFilter;
|
||||||
}
|
}
|
||||||
if (userSearch.trim()) {
|
if (userSearch.trim()) {
|
||||||
params.append("user_search", userSearch.trim());
|
params.user_search = userSearch.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (params.toString()) {
|
const data = await adminApi.getPastTrades(
|
||||||
url += `?${params.toString()}`;
|
Object.keys(params).length > 0 ? params : undefined
|
||||||
}
|
);
|
||||||
|
|
||||||
const data = await api.get<AdminExchangeResponse[]>(url);
|
|
||||||
setPastTrades(data);
|
setPastTrades(data);
|
||||||
return null;
|
return null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
@ -105,12 +101,13 @@ export default function AdminTradesPage() {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const endpoint =
|
if (action === "complete") {
|
||||||
action === "no_show"
|
await adminApi.completeTrade(publicId);
|
||||||
? `/api/admin/trades/${publicId}/no-show`
|
} else if (action === "no_show") {
|
||||||
: `/api/admin/trades/${publicId}/${action}`;
|
await adminApi.noShowTrade(publicId);
|
||||||
|
} else if (action === "cancel") {
|
||||||
await api.post<AdminExchangeResponse>(endpoint, {});
|
await adminApi.cancelTrade(publicId);
|
||||||
|
}
|
||||||
// Refetch trades - errors from fetch are informational, not critical
|
// Refetch trades - errors from fetch are informational, not critical
|
||||||
const [upcomingErr, pastErr] = await Promise.all([fetchUpcomingTrades(), fetchPastTrades()]);
|
const [upcomingErr, pastErr] = await Promise.all([fetchUpcomingTrades(), fetchPastTrades()]);
|
||||||
const fetchErrors = [upcomingErr, pastErr].filter(Boolean);
|
const fetchErrors = [upcomingErr, pastErr].filter(Boolean);
|
||||||
|
|
|
||||||
156
frontend/app/api/admin.ts
Normal file
156
frontend/app/api/admin.ts
Normal file
|
|
@ -0,0 +1,156 @@
|
||||||
|
import { client } from "./client";
|
||||||
|
import { components } from "../generated/api";
|
||||||
|
|
||||||
|
type AdminUserResponse = components["schemas"]["AdminUserResponse"];
|
||||||
|
type PaginatedInvites = components["schemas"]["PaginatedResponse_InviteResponse_"];
|
||||||
|
type AdminExchangeResponse = components["schemas"]["AdminExchangeResponse"];
|
||||||
|
type AvailabilityResponse = components["schemas"]["AvailabilityResponse"];
|
||||||
|
type PriceHistoryRecord = components["schemas"]["PriceHistoryResponse"];
|
||||||
|
|
||||||
|
interface CreateInviteRequest {
|
||||||
|
godfather_id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UpdateAvailabilityRequest {
|
||||||
|
date: string;
|
||||||
|
slots: Array<{ start_time: string; end_time: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CopyAvailabilityRequest {
|
||||||
|
source_date: string;
|
||||||
|
target_dates: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GetPastTradesParams {
|
||||||
|
status?: string;
|
||||||
|
user_search?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Admin API endpoints
|
||||||
|
*/
|
||||||
|
export const adminApi = {
|
||||||
|
/**
|
||||||
|
* Get all users (for dropdowns, etc.)
|
||||||
|
*/
|
||||||
|
getUsers(): Promise<AdminUserResponse[]> {
|
||||||
|
return client.get<AdminUserResponse[]>("/api/admin/users");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get paginated invites
|
||||||
|
*/
|
||||||
|
getInvites(page: number, perPage: number = 10, status?: string): Promise<PaginatedInvites> {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.append("page", page.toString());
|
||||||
|
params.append("per_page", perPage.toString());
|
||||||
|
if (status) {
|
||||||
|
params.append("status", status);
|
||||||
|
}
|
||||||
|
return client.get<PaginatedInvites>(`/api/admin/invites?${params.toString()}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new invite
|
||||||
|
*/
|
||||||
|
createInvite(request: CreateInviteRequest): Promise<void> {
|
||||||
|
return client.post<void>("/api/admin/invites", request);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revoke an invite
|
||||||
|
*/
|
||||||
|
revokeInvite(inviteId: number): Promise<void> {
|
||||||
|
return client.post<void>(`/api/admin/invites/${inviteId}/revoke`);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get upcoming trades
|
||||||
|
*/
|
||||||
|
getUpcomingTrades(): Promise<AdminExchangeResponse[]> {
|
||||||
|
return client.get<AdminExchangeResponse[]>("/api/admin/trades/upcoming");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get past trades with optional filters
|
||||||
|
*/
|
||||||
|
getPastTrades(params?: GetPastTradesParams): Promise<AdminExchangeResponse[]> {
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
if (params?.status) {
|
||||||
|
searchParams.append("status", params.status);
|
||||||
|
}
|
||||||
|
if (params?.user_search) {
|
||||||
|
searchParams.append("user_search", params.user_search);
|
||||||
|
}
|
||||||
|
const queryString = searchParams.toString();
|
||||||
|
const url = queryString ? `/api/admin/trades/past?${queryString}` : "/api/admin/trades/past";
|
||||||
|
return client.get<AdminExchangeResponse[]>(url);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Complete a trade
|
||||||
|
*/
|
||||||
|
completeTrade(publicId: string): Promise<AdminExchangeResponse> {
|
||||||
|
return client.post<AdminExchangeResponse>(
|
||||||
|
`/api/admin/trades/${encodeURIComponent(publicId)}/complete`,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark a trade as no-show
|
||||||
|
*/
|
||||||
|
noShowTrade(publicId: string): Promise<AdminExchangeResponse> {
|
||||||
|
return client.post<AdminExchangeResponse>(
|
||||||
|
`/api/admin/trades/${encodeURIComponent(publicId)}/no-show`,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancel a trade (admin)
|
||||||
|
*/
|
||||||
|
cancelTrade(publicId: string): Promise<AdminExchangeResponse> {
|
||||||
|
return client.post<AdminExchangeResponse>(
|
||||||
|
`/api/admin/trades/${encodeURIComponent(publicId)}/cancel`,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get availability for a date range
|
||||||
|
*/
|
||||||
|
getAvailability(fromDate: string, toDate: string): Promise<AvailabilityResponse> {
|
||||||
|
return client.get<AvailabilityResponse>(
|
||||||
|
`/api/admin/availability?from=${encodeURIComponent(fromDate)}&to=${encodeURIComponent(toDate)}`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update availability for a specific date
|
||||||
|
*/
|
||||||
|
updateAvailability(request: UpdateAvailabilityRequest): Promise<void> {
|
||||||
|
return client.put<void>("/api/admin/availability", request);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy availability from one date to multiple dates
|
||||||
|
*/
|
||||||
|
copyAvailability(request: CopyAvailabilityRequest): Promise<void> {
|
||||||
|
return client.post<void>("/api/admin/availability/copy", request);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get price history records
|
||||||
|
*/
|
||||||
|
getPriceHistory(): Promise<PriceHistoryRecord[]> {
|
||||||
|
return client.get<PriceHistoryRecord[]>("/api/audit/price-history");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger a price fetch
|
||||||
|
*/
|
||||||
|
fetchPrice(): Promise<PriceHistoryRecord> {
|
||||||
|
return client.post<PriceHistoryRecord>("/api/audit/price-history/fetch", {});
|
||||||
|
},
|
||||||
|
};
|
||||||
41
frontend/app/api/auth.ts
Normal file
41
frontend/app/api/auth.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
import { client } from "./client";
|
||||||
|
import { components } from "../generated/api";
|
||||||
|
|
||||||
|
type User = components["schemas"]["UserResponse"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentication API endpoints
|
||||||
|
*/
|
||||||
|
export const authApi = {
|
||||||
|
/**
|
||||||
|
* Get current authenticated user
|
||||||
|
*/
|
||||||
|
getMe(): Promise<User> {
|
||||||
|
return client.get<User>("/api/auth/me");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Login with email and password
|
||||||
|
*/
|
||||||
|
login(email: string, password: string): Promise<User> {
|
||||||
|
return client.post<User>("/api/auth/login", { email, password });
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new user with invite code
|
||||||
|
*/
|
||||||
|
register(email: string, password: string, inviteIdentifier: string): Promise<User> {
|
||||||
|
return client.post<User>("/api/auth/register", {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
invite_identifier: inviteIdentifier,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logout current user
|
||||||
|
*/
|
||||||
|
logout(): Promise<void> {
|
||||||
|
return client.post<void>("/api/auth/logout");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { API_URL } from "./config";
|
import { API_URL } from "../config";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple API client that centralizes fetch configuration.
|
* Base API client that centralizes fetch configuration.
|
||||||
* All requests include credentials and proper headers.
|
* All requests include credentials and proper headers.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
@ -46,7 +46,11 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<
|
||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
export const api = {
|
/**
|
||||||
|
* Base API client methods.
|
||||||
|
* Domain-specific APIs should use these internally.
|
||||||
|
*/
|
||||||
|
export const client = {
|
||||||
get<T>(endpoint: string): Promise<T> {
|
get<T>(endpoint: string): Promise<T> {
|
||||||
return request<T>(endpoint);
|
return request<T>(endpoint);
|
||||||
},
|
},
|
||||||
41
frontend/app/api/exchange.ts
Normal file
41
frontend/app/api/exchange.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
import { client } from "./client";
|
||||||
|
import { components } from "../generated/api";
|
||||||
|
|
||||||
|
type ExchangePriceResponse = components["schemas"]["ExchangePriceResponse"];
|
||||||
|
type AvailableSlotsResponse = components["schemas"]["AvailableSlotsResponse"];
|
||||||
|
type ExchangeResponse = components["schemas"]["ExchangeResponse"];
|
||||||
|
|
||||||
|
interface CreateExchangeRequest {
|
||||||
|
slot_start: string;
|
||||||
|
direction: "buy" | "sell";
|
||||||
|
bitcoin_transfer_method: "onchain" | "lightning";
|
||||||
|
eur_amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exchange API endpoints
|
||||||
|
*/
|
||||||
|
export const exchangeApi = {
|
||||||
|
/**
|
||||||
|
* Get current exchange price
|
||||||
|
*/
|
||||||
|
getPrice(): Promise<ExchangePriceResponse> {
|
||||||
|
return client.get<ExchangePriceResponse>("/api/exchange/price");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get available slots for a specific date
|
||||||
|
*/
|
||||||
|
getSlots(date: string): Promise<AvailableSlotsResponse> {
|
||||||
|
return client.get<AvailableSlotsResponse>(
|
||||||
|
`/api/exchange/slots?date=${encodeURIComponent(date)}`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new exchange/trade
|
||||||
|
*/
|
||||||
|
createExchange(request: CreateExchangeRequest): Promise<ExchangeResponse> {
|
||||||
|
return client.post<ExchangeResponse>("/api/exchange", request);
|
||||||
|
},
|
||||||
|
};
|
||||||
12
frontend/app/api/index.ts
Normal file
12
frontend/app/api/index.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
/**
|
||||||
|
* Centralized API exports.
|
||||||
|
* Import domain-specific APIs from here.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export { ApiError, client } from "./client";
|
||||||
|
export { authApi } from "./auth";
|
||||||
|
export { exchangeApi } from "./exchange";
|
||||||
|
export { tradesApi } from "./trades";
|
||||||
|
export { profileApi } from "./profile";
|
||||||
|
export { invitesApi } from "./invites";
|
||||||
|
export { adminApi } from "./admin";
|
||||||
24
frontend/app/api/invites.ts
Normal file
24
frontend/app/api/invites.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { client } from "./client";
|
||||||
|
import { components } from "../generated/api";
|
||||||
|
|
||||||
|
type Invite = components["schemas"]["UserInviteResponse"];
|
||||||
|
type InviteCheckResponse = components["schemas"]["InviteCheckResponse"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invites API endpoints (user-facing)
|
||||||
|
*/
|
||||||
|
export const invitesApi = {
|
||||||
|
/**
|
||||||
|
* Get all invites for the current user
|
||||||
|
*/
|
||||||
|
getInvites(): Promise<Invite[]> {
|
||||||
|
return client.get<Invite[]>("/api/invites");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if an invite code is valid
|
||||||
|
*/
|
||||||
|
checkInvite(code: string): Promise<InviteCheckResponse> {
|
||||||
|
return client.get<InviteCheckResponse>(`/api/invites/${encodeURIComponent(code)}/check`);
|
||||||
|
},
|
||||||
|
};
|
||||||
30
frontend/app/api/profile.ts
Normal file
30
frontend/app/api/profile.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { client } from "./client";
|
||||||
|
import { components } from "../generated/api";
|
||||||
|
|
||||||
|
type ProfileData = components["schemas"]["ProfileResponse"];
|
||||||
|
|
||||||
|
interface UpdateProfileRequest {
|
||||||
|
contact_email: string | null;
|
||||||
|
telegram: string | null;
|
||||||
|
signal: string | null;
|
||||||
|
nostr_npub: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Profile API endpoints
|
||||||
|
*/
|
||||||
|
export const profileApi = {
|
||||||
|
/**
|
||||||
|
* Get current user's profile
|
||||||
|
*/
|
||||||
|
getProfile(): Promise<ProfileData> {
|
||||||
|
return client.get<ProfileData>("/api/profile");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update current user's profile
|
||||||
|
*/
|
||||||
|
updateProfile(request: UpdateProfileRequest): Promise<ProfileData> {
|
||||||
|
return client.put<ProfileData>("/api/profile", request);
|
||||||
|
},
|
||||||
|
};
|
||||||
30
frontend/app/api/trades.ts
Normal file
30
frontend/app/api/trades.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { client } from "./client";
|
||||||
|
import { components } from "../generated/api";
|
||||||
|
|
||||||
|
type ExchangeResponse = components["schemas"]["ExchangeResponse"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trades API endpoints (user-facing)
|
||||||
|
*/
|
||||||
|
export const tradesApi = {
|
||||||
|
/**
|
||||||
|
* Get all trades for the current user
|
||||||
|
*/
|
||||||
|
getTrades(): Promise<ExchangeResponse[]> {
|
||||||
|
return client.get<ExchangeResponse[]>("/api/trades");
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a specific trade by public ID
|
||||||
|
*/
|
||||||
|
getTrade(publicId: string): Promise<ExchangeResponse> {
|
||||||
|
return client.get<ExchangeResponse>(`/api/trades/${encodeURIComponent(publicId)}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancel a trade
|
||||||
|
*/
|
||||||
|
cancelTrade(publicId: string): Promise<ExchangeResponse> {
|
||||||
|
return client.post<ExchangeResponse>(`/api/trades/${encodeURIComponent(publicId)}/cancel`, {});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
|
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
|
||||||
|
|
||||||
import { api } from "./api";
|
import { authApi } from "./api";
|
||||||
import { components } from "./generated/api";
|
import { components } from "./generated/api";
|
||||||
import { extractApiErrorMessage } from "./utils/error-handling";
|
import { extractApiErrorMessage } from "./utils/error-handling";
|
||||||
|
|
||||||
|
|
@ -54,7 +54,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
|
||||||
const checkAuth = async () => {
|
const checkAuth = async () => {
|
||||||
try {
|
try {
|
||||||
const userData = await api.get<User>("/api/auth/me");
|
const userData = await authApi.getMe();
|
||||||
setUser(userData);
|
setUser(userData);
|
||||||
} catch {
|
} catch {
|
||||||
// Not authenticated
|
// Not authenticated
|
||||||
|
|
@ -65,7 +65,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
|
||||||
const login = async (email: string, password: string) => {
|
const login = async (email: string, password: string) => {
|
||||||
try {
|
try {
|
||||||
const userData = await api.post<User>("/api/auth/login", { email, password });
|
const userData = await authApi.login(email, password);
|
||||||
setUser(userData);
|
setUser(userData);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(extractApiErrorMessage(err, "Login failed"));
|
throw new Error(extractApiErrorMessage(err, "Login failed"));
|
||||||
|
|
@ -74,11 +74,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
|
||||||
const register = async (email: string, password: string, inviteIdentifier: string) => {
|
const register = async (email: string, password: string, inviteIdentifier: string) => {
|
||||||
try {
|
try {
|
||||||
const userData = await api.post<User>("/api/auth/register", {
|
const userData = await authApi.register(email, password, inviteIdentifier);
|
||||||
email,
|
|
||||||
password,
|
|
||||||
invite_identifier: inviteIdentifier,
|
|
||||||
});
|
|
||||||
setUser(userData);
|
setUser(userData);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(extractApiErrorMessage(err, "Registration failed"));
|
throw new Error(extractApiErrorMessage(err, "Registration failed"));
|
||||||
|
|
@ -87,7 +83,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
|
||||||
const logout = async () => {
|
const logout = async () => {
|
||||||
try {
|
try {
|
||||||
await api.post("/api/auth/logout");
|
await authApi.logout();
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore errors on logout
|
// Ignore errors on logout
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import { api } from "../../api";
|
import { exchangeApi } from "../../api";
|
||||||
import { components } from "../../generated/api";
|
import { components } from "../../generated/api";
|
||||||
import { formatDate } from "../../utils/date";
|
import { formatDate } from "../../utils/date";
|
||||||
|
|
||||||
type BookableSlot = components["schemas"]["BookableSlot"];
|
type BookableSlot = components["schemas"]["BookableSlot"];
|
||||||
type AvailableSlotsResponse = components["schemas"]["AvailableSlotsResponse"];
|
|
||||||
|
|
||||||
interface UseAvailableSlotsOptions {
|
interface UseAvailableSlotsOptions {
|
||||||
/** Whether the user is authenticated and authorized */
|
/** Whether the user is authenticated and authorized */
|
||||||
|
|
@ -48,7 +47,7 @@ export function useAvailableSlots(options: UseAvailableSlotsOptions): UseAvailab
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const dateStr = formatDate(date);
|
const dateStr = formatDate(date);
|
||||||
const data = await api.get<AvailableSlotsResponse>(`/api/exchange/slots?date=${dateStr}`);
|
const data = await exchangeApi.getSlots(dateStr);
|
||||||
setAvailableSlots(data.slots);
|
setAvailableSlots(data.slots);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to fetch slots:", err);
|
console.error("Failed to fetch slots:", err);
|
||||||
|
|
@ -70,7 +69,7 @@ export function useAvailableSlots(options: UseAvailableSlotsOptions): UseAvailab
|
||||||
const promises = dates.map(async (date) => {
|
const promises = dates.map(async (date) => {
|
||||||
try {
|
try {
|
||||||
const dateStr = formatDate(date);
|
const dateStr = formatDate(date);
|
||||||
const data = await api.get<AvailableSlotsResponse>(`/api/exchange/slots?date=${dateStr}`);
|
const data = await exchangeApi.getSlots(dateStr);
|
||||||
if (data.slots.length > 0) {
|
if (data.slots.length > 0) {
|
||||||
availabilitySet.add(dateStr);
|
availabilitySet.add(dateStr);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import { api } from "../../api";
|
import { exchangeApi } from "../../api";
|
||||||
import { components } from "../../generated/api";
|
import { components } from "../../generated/api";
|
||||||
|
|
||||||
type ExchangePriceResponse = components["schemas"]["ExchangePriceResponse"];
|
type ExchangePriceResponse = components["schemas"]["ExchangePriceResponse"];
|
||||||
|
|
@ -37,7 +37,7 @@ export function useExchangePrice(options: UseExchangePriceOptions = {}): UseExch
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await api.get<ExchangePriceResponse>("/api/exchange/price");
|
const data = await exchangeApi.getPrice();
|
||||||
setPriceData(data);
|
setPriceData(data);
|
||||||
setLastUpdate(new Date());
|
setLastUpdate(new Date());
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
import { useEffect, useState, useCallback, useMemo } from "react";
|
import { useEffect, useState, useCallback, useMemo } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Permission } from "../auth-context";
|
import { Permission } from "../auth-context";
|
||||||
import { api } from "../api";
|
import { exchangeApi, tradesApi } from "../api";
|
||||||
import { extractApiErrorMessage } from "../utils/error-handling";
|
import { extractApiErrorMessage } from "../utils/error-handling";
|
||||||
import { Header } from "../components/Header";
|
import { Header } from "../components/Header";
|
||||||
import { LoadingState } from "../components/LoadingState";
|
import { LoadingState } from "../components/LoadingState";
|
||||||
|
|
@ -166,7 +166,7 @@ export default function ExchangePage() {
|
||||||
|
|
||||||
const fetchUserTrades = async () => {
|
const fetchUserTrades = async () => {
|
||||||
try {
|
try {
|
||||||
const data = await api.get<ExchangeResponse[]>("/api/trades");
|
const data = await tradesApi.getTrades();
|
||||||
setUserTrades(data);
|
setUserTrades(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to fetch user trades:", err);
|
console.error("Failed to fetch user trades:", err);
|
||||||
|
|
@ -242,7 +242,7 @@ export default function ExchangePage() {
|
||||||
setExistingTradeId(null);
|
setExistingTradeId(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.post<ExchangeResponse>("/api/exchange", {
|
await exchangeApi.createExchange({
|
||||||
slot_start: selectedSlot.start_time,
|
slot_start: selectedSlot.start_time,
|
||||||
direction,
|
direction,
|
||||||
bitcoin_transfer_method: bitcoinTransferMethod,
|
bitcoin_transfer_method: bitcoinTransferMethod,
|
||||||
|
|
|
||||||
|
|
@ -9,16 +9,19 @@ import { useEffect, useRef, useState } from "react";
|
||||||
* @param delay - Debounce delay in milliseconds (default: 500)
|
* @param delay - Debounce delay in milliseconds (default: 500)
|
||||||
* @returns Object containing current errors and a function to manually trigger validation
|
* @returns Object containing current errors and a function to manually trigger validation
|
||||||
*/
|
*/
|
||||||
export function useDebouncedValidation<T>(
|
export function useDebouncedValidation<
|
||||||
|
T,
|
||||||
|
E extends Record<string, string | undefined> = Record<string, string>,
|
||||||
|
>(
|
||||||
formData: T,
|
formData: T,
|
||||||
validator: (data: T) => Record<string, string>,
|
validator: (data: T) => E,
|
||||||
delay: number = 500
|
delay: number = 500
|
||||||
): {
|
): {
|
||||||
errors: Record<string, string>;
|
errors: E;
|
||||||
setErrors: React.Dispatch<React.SetStateAction<Record<string, string>>>;
|
setErrors: React.Dispatch<React.SetStateAction<E>>;
|
||||||
validate: (data?: T) => void;
|
validate: (data?: T) => void;
|
||||||
} {
|
} {
|
||||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
const [errors, setErrors] = useState<E>({} as E);
|
||||||
const validationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
const validationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
const formDataRef = useRef<T>(formData);
|
const formDataRef = useRef<T>(formData);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import { api } from "../api";
|
import { invitesApi } from "../api";
|
||||||
import { Header } from "../components/Header";
|
import { Header } from "../components/Header";
|
||||||
import { useRequireAuth } from "../hooks/useRequireAuth";
|
import { useRequireAuth } from "../hooks/useRequireAuth";
|
||||||
import { components } from "../generated/api";
|
import { components } from "../generated/api";
|
||||||
|
|
@ -29,7 +29,7 @@ export default function InvitesPage() {
|
||||||
|
|
||||||
const fetchInvites = useCallback(async () => {
|
const fetchInvites = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const data = await api.get<Invite[]>("/api/invites");
|
const data = await invitesApi.getInvites();
|
||||||
setInvites(data);
|
setInvites(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to load invites:", err);
|
console.error("Failed to load invites:", err);
|
||||||
|
|
|
||||||
|
|
@ -53,6 +53,24 @@ vi.mock("../auth-context", () => ({
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock profileApi
|
||||||
|
const mockGetProfile = vi.fn();
|
||||||
|
const mockUpdateProfile = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("../api", async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import("../api")>();
|
||||||
|
// Create a getter that returns the mock functions
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
get profileApi() {
|
||||||
|
return {
|
||||||
|
getProfile: mockGetProfile,
|
||||||
|
updateProfile: mockUpdateProfile,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
// Mock profile data
|
// Mock profile data
|
||||||
const mockProfileData = {
|
const mockProfileData = {
|
||||||
contact_email: "contact@example.com",
|
contact_email: "contact@example.com",
|
||||||
|
|
@ -80,6 +98,9 @@ beforeEach(() => {
|
||||||
mockHasPermission.mockImplementation(
|
mockHasPermission.mockImplementation(
|
||||||
(permission: string) => mockUser?.permissions.includes(permission) ?? false
|
(permission: string) => mockUser?.permissions.includes(permission) ?? false
|
||||||
);
|
);
|
||||||
|
// Reset API mocks
|
||||||
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
|
mockUpdateProfile.mockResolvedValue(mockProfileData);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
|
@ -89,17 +110,14 @@ afterEach(() => {
|
||||||
describe("ProfilePage - Display", () => {
|
describe("ProfilePage - Display", () => {
|
||||||
test("renders loading state initially", () => {
|
test("renders loading state initially", () => {
|
||||||
mockIsLoading = true;
|
mockIsLoading = true;
|
||||||
vi.spyOn(global, "fetch").mockImplementation(() => new Promise(() => {}));
|
mockGetProfile.mockImplementation(() => new Promise(() => {}));
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
expect(screen.getByText("Loading...")).toBeDefined();
|
expect(screen.getByText("Loading...")).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders profile page title", async () => {
|
test("renders profile page title", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -108,10 +126,7 @@ describe("ProfilePage - Display", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("displays login email as read-only", async () => {
|
test("displays login email as read-only", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -122,10 +137,7 @@ describe("ProfilePage - Display", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("shows read-only badge for login email", async () => {
|
test("shows read-only badge for login email", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -134,10 +146,7 @@ describe("ProfilePage - Display", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("shows hint about login email", async () => {
|
test("shows hint about login email", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -146,10 +155,7 @@ describe("ProfilePage - Display", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("displays contact details section hint", async () => {
|
test("displays contact details section hint", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -158,10 +164,7 @@ describe("ProfilePage - Display", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("displays fetched profile data", async () => {
|
test("displays fetched profile data", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -173,34 +176,22 @@ describe("ProfilePage - Display", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("fetches profile with credentials", async () => {
|
test("fetches profile with credentials", async () => {
|
||||||
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(fetchSpy).toHaveBeenCalledWith(
|
expect(mockGetProfile).toHaveBeenCalled();
|
||||||
"http://localhost:8000/api/profile",
|
|
||||||
expect.objectContaining({
|
|
||||||
credentials: "include",
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("displays empty fields when profile has null values", async () => {
|
test("displays empty fields when profile has null values", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue({
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -213,10 +204,7 @@ describe("ProfilePage - Display", () => {
|
||||||
|
|
||||||
describe("ProfilePage - Navigation", () => {
|
describe("ProfilePage - Navigation", () => {
|
||||||
test("shows nav links for regular user", async () => {
|
test("shows nav links for regular user", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -226,10 +214,7 @@ describe("ProfilePage - Navigation", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("highlights My Profile in nav", async () => {
|
test("highlights My Profile in nav", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -273,13 +258,12 @@ describe("ProfilePage - Access Control", () => {
|
||||||
roles: ["admin"],
|
roles: ["admin"],
|
||||||
permissions: ["view_audit"],
|
permissions: ["view_audit"],
|
||||||
};
|
};
|
||||||
const fetchSpy = vi.spyOn(global, "fetch");
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
// Give it a moment to potentially fetch
|
// Give it a moment to potentially fetch
|
||||||
await new Promise((r) => setTimeout(r, 100));
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
expect(fetchSpy).not.toHaveBeenCalled();
|
expect(mockGetProfile).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -304,10 +288,7 @@ describe("ProfilePage - Loading State", () => {
|
||||||
|
|
||||||
describe("ProfilePage - Form Behavior", () => {
|
describe("ProfilePage - Form Behavior", () => {
|
||||||
test("submit button is disabled when no changes", async () => {
|
test("submit button is disabled when no changes", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|
@ -317,10 +298,7 @@ describe("ProfilePage - Form Behavior", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("submit button is enabled after field changes", async () => {
|
test("submit button is enabled after field changes", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve(mockProfileData),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -338,16 +316,12 @@ describe("ProfilePage - Form Behavior", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("auto-prepends @ to telegram when user starts with letter", async () => {
|
test("auto-prepends @ to telegram when user starts with letter", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue({
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -364,16 +338,12 @@ describe("ProfilePage - Form Behavior", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("does not auto-prepend @ if user types @ first", async () => {
|
test("does not auto-prepend @ if user types @ first", async () => {
|
||||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
mockGetProfile.mockResolvedValue({
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -392,28 +362,25 @@ describe("ProfilePage - Form Behavior", () => {
|
||||||
|
|
||||||
describe("ProfilePage - Form Submission", () => {
|
describe("ProfilePage - Form Submission", () => {
|
||||||
test("shows success toast after successful save", async () => {
|
test("shows success toast after successful save", async () => {
|
||||||
const fetchSpy = vi
|
mockGetProfile
|
||||||
.spyOn(global, "fetch")
|
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
})
|
||||||
} as Response)
|
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: "new@example.com",
|
contact_email: "new@example.com",
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response);
|
mockUpdateProfile.mockResolvedValue({
|
||||||
|
contact_email: "new@example.com",
|
||||||
|
telegram: null,
|
||||||
|
signal: null,
|
||||||
|
nostr_npub: null,
|
||||||
|
});
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -433,40 +400,33 @@ describe("ProfilePage - Form Submission", () => {
|
||||||
expect(screen.getByText(/saved successfully/i)).toBeDefined();
|
expect(screen.getByText(/saved successfully/i)).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Verify PUT was called
|
// Verify updateProfile was called
|
||||||
expect(fetchSpy).toHaveBeenCalledWith(
|
expect(mockUpdateProfile).toHaveBeenCalledWith({
|
||||||
"http://localhost:8000/api/profile",
|
contact_email: "new@example.com",
|
||||||
expect.objectContaining({
|
telegram: null,
|
||||||
method: "PUT",
|
signal: null,
|
||||||
credentials: "include",
|
nostr_npub: null,
|
||||||
})
|
});
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("shows inline errors from backend validation", async () => {
|
test("shows inline errors from backend validation", async () => {
|
||||||
vi.spyOn(global, "fetch")
|
mockGetProfile.mockResolvedValue({
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response)
|
// Import ApiError from the actual module (not mocked)
|
||||||
.mockResolvedValueOnce({
|
const { ApiError } = await import("../api/client");
|
||||||
ok: false,
|
mockUpdateProfile.mockRejectedValue(
|
||||||
status: 422,
|
new ApiError("Validation failed", 422, {
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
detail: {
|
detail: {
|
||||||
field_errors: {
|
field_errors: {
|
||||||
telegram: "Backend error: invalid handle",
|
telegram: "Backend error: invalid handle",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
})
|
||||||
} as Response);
|
);
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -488,18 +448,13 @@ describe("ProfilePage - Form Submission", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("shows error toast on network failure", async () => {
|
test("shows error toast on network failure", async () => {
|
||||||
vi.spyOn(global, "fetch")
|
mockGetProfile.mockResolvedValue({
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response)
|
mockUpdateProfile.mockRejectedValue(new Error("Network error"));
|
||||||
.mockRejectedValueOnce(new Error("Network error"));
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -521,23 +476,28 @@ describe("ProfilePage - Form Submission", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("submit button shows 'Saving...' while submitting", async () => {
|
test("submit button shows 'Saving...' while submitting", async () => {
|
||||||
let resolveSubmit: (value: Response) => void;
|
let resolveSubmit: (value: {
|
||||||
const submitPromise = new Promise<Response>((resolve) => {
|
contact_email: string | null;
|
||||||
|
telegram: string | null;
|
||||||
|
signal: string | null;
|
||||||
|
nostr_npub: string | null;
|
||||||
|
}) => void;
|
||||||
|
const submitPromise = new Promise<{
|
||||||
|
contact_email: string | null;
|
||||||
|
telegram: string | null;
|
||||||
|
signal: string | null;
|
||||||
|
nostr_npub: string | null;
|
||||||
|
}>((resolve) => {
|
||||||
resolveSubmit = resolve;
|
resolveSubmit = resolve;
|
||||||
});
|
});
|
||||||
|
|
||||||
vi.spyOn(global, "fetch")
|
mockGetProfile.mockResolvedValue({
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: null,
|
contact_email: null,
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response)
|
mockUpdateProfile.mockReturnValue(submitPromise);
|
||||||
.mockReturnValueOnce(submitPromise as Promise<Response>);
|
|
||||||
|
|
||||||
render(<ProfilePage />);
|
render(<ProfilePage />);
|
||||||
|
|
||||||
|
|
@ -559,15 +519,11 @@ describe("ProfilePage - Form Submission", () => {
|
||||||
|
|
||||||
// Resolve the promise
|
// Resolve the promise
|
||||||
resolveSubmit!({
|
resolveSubmit!({
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
contact_email: "new@example.com",
|
contact_email: "new@example.com",
|
||||||
telegram: null,
|
telegram: null,
|
||||||
signal: null,
|
signal: null,
|
||||||
nostr_npub: null,
|
nostr_npub: null,
|
||||||
}),
|
});
|
||||||
} as Response);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(screen.getByRole("button", { name: /save changes/i })).toBeDefined();
|
expect(screen.getByRole("button", { name: /save changes/i })).toBeDefined();
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
|
|
||||||
import { api } from "../api";
|
import { profileApi } from "../api";
|
||||||
import { extractApiErrorMessage, extractFieldErrors } from "../utils/error-handling";
|
import { extractApiErrorMessage, extractFieldErrors } from "../utils/error-handling";
|
||||||
import { Permission } from "../auth-context";
|
import { Permission } from "../auth-context";
|
||||||
import { Header } from "../components/Header";
|
import { Header } from "../components/Header";
|
||||||
|
|
@ -81,7 +81,7 @@ export default function ProfilePage() {
|
||||||
|
|
||||||
const fetchProfile = useCallback(async () => {
|
const fetchProfile = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const data = await api.get<ProfileData>("/api/profile");
|
const data = await profileApi.getProfile();
|
||||||
const formValues = toFormData(data);
|
const formValues = toFormData(data);
|
||||||
setFormData(formValues);
|
setFormData(formValues);
|
||||||
setOriginalData(formValues);
|
setOriginalData(formValues);
|
||||||
|
|
@ -132,7 +132,7 @@ export default function ProfilePage() {
|
||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await api.put<ProfileData>("/api/profile", {
|
const data = await profileApi.updateProfile({
|
||||||
contact_email: formData.contact_email || null,
|
contact_email: formData.contact_email || null,
|
||||||
telegram: formData.telegram || null,
|
telegram: formData.telegram || null,
|
||||||
signal: formData.signal || null,
|
signal: formData.signal || null,
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,9 @@
|
||||||
import { useState, useEffect, useCallback, Suspense } from "react";
|
import { useState, useEffect, useCallback, Suspense } from "react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { useAuth } from "../auth-context";
|
import { useAuth } from "../auth-context";
|
||||||
import { api } from "../api";
|
import { invitesApi } from "../api";
|
||||||
import { authFormStyles as styles } from "../styles/auth-form";
|
import { authFormStyles as styles } from "../styles/auth-form";
|
||||||
|
|
||||||
interface InviteCheckResponse {
|
|
||||||
valid: boolean;
|
|
||||||
status?: string;
|
|
||||||
error?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SignupContent() {
|
function SignupContent() {
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const initialCode = searchParams.get("code") || "";
|
const initialCode = searchParams.get("code") || "";
|
||||||
|
|
@ -49,9 +43,7 @@ function SignupContent() {
|
||||||
setInviteError("");
|
setInviteError("");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await api.get<InviteCheckResponse>(
|
const response = await invitesApi.checkInvite(code.trim());
|
||||||
`/api/invites/${encodeURIComponent(code.trim())}/check`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (response.valid) {
|
if (response.valid) {
|
||||||
setInviteValid(true);
|
setInviteValid(true);
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
import { useEffect, useState, CSSProperties } from "react";
|
import { useEffect, useState, CSSProperties } from "react";
|
||||||
import { useParams, useRouter } from "next/navigation";
|
import { useParams, useRouter } from "next/navigation";
|
||||||
import { Permission } from "../../auth-context";
|
import { Permission } from "../../auth-context";
|
||||||
import { api } from "../../api";
|
import { tradesApi } from "../../api";
|
||||||
import { Header } from "../../components/Header";
|
import { Header } from "../../components/Header";
|
||||||
import { SatsDisplay } from "../../components/SatsDisplay";
|
import { SatsDisplay } from "../../components/SatsDisplay";
|
||||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||||
|
|
@ -42,7 +42,7 @@ export default function TradeDetailPage() {
|
||||||
try {
|
try {
|
||||||
setIsLoadingTrade(true);
|
setIsLoadingTrade(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const data = await api.get<ExchangeResponse>(`/api/trades/${publicId}`);
|
const data = await tradesApi.getTrade(publicId);
|
||||||
setTrade(data);
|
setTrade(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to fetch trade:", err);
|
console.error("Failed to fetch trade:", err);
|
||||||
|
|
@ -221,7 +221,7 @@ export default function TradeDetailPage() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await api.post(`/api/trades/${trade.public_id}/cancel`, {});
|
await tradesApi.cancelTrade(trade.public_id);
|
||||||
router.push("/trades");
|
router.push("/trades");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Failed to cancel trade");
|
setError(err instanceof Error ? err.message : "Failed to cancel trade");
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Permission } from "../auth-context";
|
import { Permission } from "../auth-context";
|
||||||
import { api } from "../api";
|
import { tradesApi } from "../api";
|
||||||
import { Header } from "../components/Header";
|
import { Header } from "../components/Header";
|
||||||
import { SatsDisplay } from "../components/SatsDisplay";
|
import { SatsDisplay } from "../components/SatsDisplay";
|
||||||
import { LoadingState } from "../components/LoadingState";
|
import { LoadingState } from "../components/LoadingState";
|
||||||
|
|
@ -37,7 +37,7 @@ export default function TradesPage() {
|
||||||
|
|
||||||
const fetchTrades = useCallback(async () => {
|
const fetchTrades = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const data = await api.get<ExchangeResponse[]>("/api/trades");
|
const data = await tradesApi.getTrades();
|
||||||
setTrades(data);
|
setTrades(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to fetch trades:", err);
|
console.error("Failed to fetch trades:", err);
|
||||||
|
|
@ -58,7 +58,7 @@ export default function TradesPage() {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.post<ExchangeResponse>(`/api/trades/${publicId}/cancel`, {});
|
await tradesApi.cancelTrade(publicId);
|
||||||
await fetchTrades();
|
await fetchTrades();
|
||||||
setConfirmCancelId(null);
|
setConfirmCancelId(null);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,7 @@ export function validateNostrNpub(value: string): string | undefined {
|
||||||
/**
|
/**
|
||||||
* Field errors object type.
|
* Field errors object type.
|
||||||
*/
|
*/
|
||||||
export interface FieldErrors {
|
export interface FieldErrors extends Record<string, string | undefined> {
|
||||||
contact_email?: string;
|
contact_email?: string;
|
||||||
telegram?: string;
|
telegram?: string;
|
||||||
signal?: string;
|
signal?: string;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue