- Extract API error handling utility (utils/error-handling.ts) - Centralize error message extraction logic - Add type guards for API errors - Replace duplicated error handling across components - Create reusable Toast component (components/Toast.tsx) - Extract toast notification logic from profile page - Support auto-dismiss functionality - Consistent styling with shared styles - Extract form validation debouncing hook (hooks/useDebouncedValidation.ts) - Reusable debounced validation logic - Clean timeout management - Used in profile page for form validation - Consolidate duplicate styles (styles/auth-form.ts) - Use shared style tokens instead of duplicating values - Reduce code duplication between auth-form and shared styles - Extract loading state component (components/LoadingState.tsx) - Standardize loading UI across pages - Replace duplicated loading JSX patterns - Used in profile, exchange, and trades pages - Fix useRequireAuth dependency array - Remove unnecessary hasPermission from dependencies - Add eslint-disable comment with explanation - Improve hook stability and performance All frontend tests pass. Linting passes.
362 lines
14 KiB
TypeScript
362 lines
14 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Permission } from "../auth-context";
|
|
import { api } from "../api";
|
|
import { Header } from "../components/Header";
|
|
import { SatsDisplay } from "../components/SatsDisplay";
|
|
import { LoadingState } from "../components/LoadingState";
|
|
import { useRequireAuth } from "../hooks/useRequireAuth";
|
|
import { components } from "../generated/api";
|
|
import { formatDateTime } from "../utils/date";
|
|
import { formatEur, getTradeStatusDisplay } from "../utils/exchange";
|
|
import {
|
|
layoutStyles,
|
|
typographyStyles,
|
|
bannerStyles,
|
|
badgeStyles,
|
|
buttonStyles,
|
|
tradeCardStyles,
|
|
} from "../styles/shared";
|
|
|
|
type ExchangeResponse = components["schemas"]["ExchangeResponse"];
|
|
|
|
export default function TradesPage() {
|
|
const router = useRouter();
|
|
const { user, isLoading, isAuthorized } = useRequireAuth({
|
|
requiredPermission: Permission.VIEW_OWN_EXCHANGES,
|
|
fallbackRedirect: "/",
|
|
});
|
|
|
|
const [trades, setTrades] = useState<ExchangeResponse[]>([]);
|
|
const [isLoadingTrades, setIsLoadingTrades] = useState(true);
|
|
const [cancellingId, setCancellingId] = useState<string | null>(null);
|
|
const [confirmCancelId, setConfirmCancelId] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const fetchTrades = useCallback(async () => {
|
|
try {
|
|
const data = await api.get<ExchangeResponse[]>("/api/trades");
|
|
setTrades(data);
|
|
} catch (err) {
|
|
console.error("Failed to fetch trades:", err);
|
|
setError("Failed to load trades");
|
|
} finally {
|
|
setIsLoadingTrades(false);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (user && isAuthorized) {
|
|
fetchTrades();
|
|
}
|
|
}, [user, isAuthorized, fetchTrades]);
|
|
|
|
const handleCancel = async (publicId: string) => {
|
|
setCancellingId(publicId);
|
|
setError(null);
|
|
|
|
try {
|
|
await api.post<ExchangeResponse>(`/api/trades/${publicId}/cancel`, {});
|
|
await fetchTrades();
|
|
setConfirmCancelId(null);
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Failed to cancel trade");
|
|
} finally {
|
|
setCancellingId(null);
|
|
}
|
|
};
|
|
|
|
if (isLoading) {
|
|
return <LoadingState />;
|
|
}
|
|
|
|
if (!isAuthorized) {
|
|
return null;
|
|
}
|
|
|
|
const upcomingTrades = trades.filter(
|
|
(t) => t.status === "booked" && new Date(t.slot_start) > new Date()
|
|
);
|
|
const pastOrFinalTrades = trades.filter(
|
|
(t) => t.status !== "booked" || new Date(t.slot_start) <= new Date()
|
|
);
|
|
|
|
return (
|
|
<main style={layoutStyles.main}>
|
|
<Header currentPage="trades" />
|
|
<div style={styles.content}>
|
|
<h1 style={typographyStyles.pageTitle}>My Trades</h1>
|
|
<p style={typographyStyles.pageSubtitle}>View and manage your Bitcoin trades</p>
|
|
|
|
{error && <div style={bannerStyles.errorBanner}>{error}</div>}
|
|
|
|
{isLoadingTrades ? (
|
|
<div style={tradeCardStyles.emptyState}>Loading trades...</div>
|
|
) : trades.length === 0 ? (
|
|
<div style={tradeCardStyles.emptyState}>
|
|
<p>You don't have any trades yet.</p>
|
|
<a href="/exchange" style={styles.emptyStateLink}>
|
|
Start trading
|
|
</a>
|
|
</div>
|
|
) : (
|
|
<>
|
|
{/* Upcoming Trades */}
|
|
{upcomingTrades.length > 0 && (
|
|
<div style={styles.section}>
|
|
<h2 style={styles.sectionTitle}>Upcoming ({upcomingTrades.length})</h2>
|
|
<div style={tradeCardStyles.tradeList}>
|
|
{upcomingTrades.map((trade) => {
|
|
const status = getTradeStatusDisplay(trade.status);
|
|
const isBuy = trade.direction === "buy";
|
|
return (
|
|
<div key={trade.id} style={tradeCardStyles.tradeCard}>
|
|
<div style={tradeCardStyles.tradeHeader}>
|
|
<div style={tradeCardStyles.tradeInfo}>
|
|
<div style={tradeCardStyles.tradeTime}>
|
|
{formatDateTime(trade.slot_start)}
|
|
</div>
|
|
<div style={tradeCardStyles.tradeDetails}>
|
|
<span
|
|
style={{
|
|
...tradeCardStyles.directionBadge,
|
|
background: isBuy
|
|
? "rgba(74, 222, 128, 0.15)"
|
|
: "rgba(248, 113, 113, 0.15)",
|
|
color: isBuy ? "#4ade80" : "#f87171",
|
|
}}
|
|
>
|
|
{isBuy ? "BUY BTC" : "SELL BTC"}
|
|
</span>
|
|
<span
|
|
style={{
|
|
...tradeCardStyles.directionBadge,
|
|
background: "rgba(167, 139, 250, 0.15)",
|
|
color: "#a78bfa",
|
|
}}
|
|
>
|
|
{isBuy
|
|
? `Receive via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`
|
|
: `Send via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`}
|
|
</span>
|
|
<span style={tradeCardStyles.amount}>
|
|
{formatEur(trade.eur_amount)}
|
|
</span>
|
|
<span style={tradeCardStyles.arrow}>↔</span>
|
|
<span style={tradeCardStyles.satsAmount}>
|
|
<SatsDisplay sats={trade.sats_amount} />
|
|
</span>
|
|
</div>
|
|
<div style={tradeCardStyles.rateRow}>
|
|
<span style={tradeCardStyles.rateLabel}>Rate:</span>
|
|
<span style={tradeCardStyles.rateValue}>
|
|
€
|
|
{trade.agreed_price_eur.toLocaleString("de-DE", {
|
|
maximumFractionDigits: 0,
|
|
})}
|
|
/BTC
|
|
</span>
|
|
</div>
|
|
<span
|
|
style={{
|
|
...badgeStyles.badge,
|
|
background: status.bgColor,
|
|
color: status.textColor,
|
|
marginTop: "0.5rem",
|
|
}}
|
|
>
|
|
{status.text}
|
|
</span>
|
|
</div>
|
|
|
|
<div style={tradeCardStyles.buttonGroup}>
|
|
{trade.status === "booked" && (
|
|
<>
|
|
{confirmCancelId === trade.public_id ? (
|
|
<>
|
|
<button
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
handleCancel(trade.public_id);
|
|
}}
|
|
disabled={cancellingId === trade.public_id}
|
|
style={styles.confirmButton}
|
|
>
|
|
{cancellingId === trade.public_id ? "..." : "Confirm"}
|
|
</button>
|
|
<button
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
setConfirmCancelId(null);
|
|
}}
|
|
style={buttonStyles.secondaryButton}
|
|
>
|
|
No
|
|
</button>
|
|
</>
|
|
) : (
|
|
<button
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
setConfirmCancelId(trade.public_id);
|
|
}}
|
|
style={buttonStyles.secondaryButton}
|
|
>
|
|
Cancel
|
|
</button>
|
|
)}
|
|
</>
|
|
)}
|
|
<button
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
router.push(`/trades/${trade.public_id}`);
|
|
}}
|
|
style={styles.viewDetailsButton}
|
|
>
|
|
View Details
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Past/Completed/Cancelled Trades */}
|
|
{pastOrFinalTrades.length > 0 && (
|
|
<div style={styles.section}>
|
|
<h2 style={typographyStyles.sectionTitleMuted}>
|
|
History ({pastOrFinalTrades.length})
|
|
</h2>
|
|
<div style={tradeCardStyles.tradeList}>
|
|
{pastOrFinalTrades.map((trade) => {
|
|
const status = getTradeStatusDisplay(trade.status);
|
|
const isBuy = trade.direction === "buy";
|
|
return (
|
|
<div
|
|
key={trade.id}
|
|
style={{
|
|
...tradeCardStyles.tradeCard,
|
|
...styles.tradeCardPast,
|
|
}}
|
|
>
|
|
<div style={tradeCardStyles.tradeTime}>
|
|
{formatDateTime(trade.slot_start)}
|
|
</div>
|
|
<div style={tradeCardStyles.tradeDetails}>
|
|
<span
|
|
style={{
|
|
...tradeCardStyles.directionBadge,
|
|
background: isBuy
|
|
? "rgba(74, 222, 128, 0.1)"
|
|
: "rgba(248, 113, 113, 0.1)",
|
|
color: isBuy ? "rgba(74, 222, 128, 0.7)" : "rgba(248, 113, 113, 0.7)",
|
|
}}
|
|
>
|
|
{isBuy ? "BUY BTC" : "SELL BTC"}
|
|
</span>
|
|
<span
|
|
style={{
|
|
...tradeCardStyles.directionBadge,
|
|
background: "rgba(167, 139, 250, 0.1)",
|
|
color: "rgba(167, 139, 250, 0.7)",
|
|
}}
|
|
>
|
|
{isBuy
|
|
? `Receive via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`
|
|
: `Send via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`}
|
|
</span>
|
|
<span style={tradeCardStyles.amount}>{formatEur(trade.eur_amount)}</span>
|
|
<span style={tradeCardStyles.arrow}>↔</span>
|
|
<span style={tradeCardStyles.satsAmount}>
|
|
<SatsDisplay sats={trade.sats_amount} />
|
|
</span>
|
|
</div>
|
|
<div style={tradeCardStyles.buttonGroup}>
|
|
<span
|
|
style={{
|
|
...badgeStyles.badge,
|
|
background: status.bgColor,
|
|
color: status.textColor,
|
|
}}
|
|
>
|
|
{status.text}
|
|
</span>
|
|
<button
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
router.push(`/trades/${trade.public_id}`);
|
|
}}
|
|
style={styles.viewDetailsButton}
|
|
>
|
|
View Details
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
// Page-specific styles (trade card styles are shared via tradeCardStyles)
|
|
const styles: Record<string, CSSProperties> = {
|
|
content: {
|
|
flex: 1,
|
|
padding: "2rem",
|
|
maxWidth: "800px",
|
|
margin: "0 auto",
|
|
width: "100%",
|
|
},
|
|
section: {
|
|
marginBottom: "2rem",
|
|
},
|
|
sectionTitle: {
|
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
fontSize: "1.1rem",
|
|
fontWeight: 500,
|
|
color: "#fff",
|
|
marginBottom: "1rem",
|
|
},
|
|
tradeCardPast: {
|
|
opacity: 0.6,
|
|
background: "rgba(255, 255, 255, 0.01)",
|
|
},
|
|
confirmButton: {
|
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
padding: "0.35rem 0.75rem",
|
|
fontSize: "0.75rem",
|
|
background: "rgba(239, 68, 68, 0.2)",
|
|
border: "1px solid rgba(239, 68, 68, 0.3)",
|
|
borderRadius: "6px",
|
|
color: "#f87171",
|
|
cursor: "pointer",
|
|
transition: "all 0.2s",
|
|
},
|
|
emptyStateLink: {
|
|
color: "#a78bfa",
|
|
textDecoration: "none",
|
|
},
|
|
viewDetailsButton: {
|
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
padding: "0.35rem 0.75rem",
|
|
fontSize: "0.75rem",
|
|
background: "rgba(167, 139, 250, 0.15)",
|
|
border: "1px solid rgba(167, 139, 250, 0.3)",
|
|
borderRadius: "6px",
|
|
color: "#a78bfa",
|
|
cursor: "pointer",
|
|
transition: "all 0.2s",
|
|
},
|
|
};
|