refactored monorepo for more projects

This commit is contained in:
Boki 2025-06-22 23:48:01 -04:00
parent 4632c174dc
commit 9492f1b15e
180 changed files with 1438 additions and 424 deletions

View file

@ -0,0 +1,174 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, Button } from '@/components/ui';
import { useCallback } from 'react';
import { CreateExchangeRequest, AddExchangeDialogProps } from '../types';
import { validateExchangeForm } from '../utils/validation';
import { useFormValidation } from '../hooks/useFormValidation';
const initialFormData: CreateExchangeRequest = {
code: '',
name: '',
country: '',
currency: '',
active: true,
};
export function AddExchangeDialog({
isOpen,
onClose,
onCreateExchange,
}: AddExchangeDialogProps) {
const {
formData,
errors,
isSubmitting,
updateField,
handleSubmit,
reset,
} = useFormValidation(initialFormData, validateExchangeForm);
const onSubmit = useCallback(
async (data: CreateExchangeRequest) => {
await onCreateExchange({
...data,
code: data.code.toUpperCase(),
country: data.country.toUpperCase(),
currency: data.currency.toUpperCase(),
});
},
[onCreateExchange]
);
const handleFormSubmit = useCallback(
(e: React.FormEvent) => {
e.preventDefault();
handleSubmit(onSubmit, onClose);
},
[handleSubmit, onSubmit, onClose]
);
const handleClose = useCallback(() => {
reset();
onClose();
}, [reset, onClose]);
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Add New Exchange</DialogTitle>
<p className="text-sm text-text-muted">
Create a new master exchange with no provider mappings
</p>
</DialogHeader>
<form onSubmit={handleFormSubmit} className="space-y-4">
{/* Exchange Code */}
<div>
<label htmlFor="code" className="block text-sm font-medium text-text-primary mb-1">
Exchange Code *
</label>
<input
id="code"
type="text"
value={formData.code}
onChange={e => updateField('code', e.target.value)}
placeholder="e.g., NASDAQ, NYSE, TSX"
className={`w-full px-3 py-2 border rounded-md bg-surface text-text-primary focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono ${
errors.code ? 'border-danger' : 'border-border'
}`}
maxLength={10}
required
/>
{errors.code && <p className="text-xs text-danger mt-1">{errors.code}</p>}
</div>
{/* Exchange Name */}
<div>
<label htmlFor="name" className="block text-sm font-medium text-text-primary mb-1">
Exchange Name *
</label>
<input
id="name"
type="text"
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="e.g., NASDAQ Stock Market, New York Stock Exchange"
className={`w-full px-3 py-2 border rounded-md bg-surface text-text-primary focus:ring-2 focus:ring-primary-500 focus:border-primary-500 ${
errors.name ? 'border-danger' : 'border-border'
}`}
maxLength={255}
required
/>
{errors.name && <p className="text-xs text-danger mt-1">{errors.name}</p>}
</div>
{/* Country */}
<div>
<label htmlFor="country" className="block text-sm font-medium text-text-primary mb-1">
Country Code *
</label>
<input
id="country"
type="text"
value={formData.country}
onChange={e => updateField('country', e.target.value)}
placeholder="e.g., US, CA, GB"
className={`w-full px-3 py-2 border rounded-md bg-surface text-text-primary focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono ${
errors.country ? 'border-danger' : 'border-border'
}`}
maxLength={2}
required
/>
{errors.country && <p className="text-xs text-danger mt-1">{errors.country}</p>}
</div>
{/* Currency */}
<div>
<label htmlFor="currency" className="block text-sm font-medium text-text-primary mb-1">
Currency Code *
</label>
<input
id="currency"
type="text"
value={formData.currency}
onChange={e => updateField('currency', e.target.value)}
placeholder="e.g., USD, EUR, CAD"
className={`w-full px-3 py-2 border rounded-md bg-surface text-text-primary focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono ${
errors.currency ? 'border-danger' : 'border-border'
}`}
maxLength={3}
required
/>
{errors.currency && <p className="text-xs text-danger mt-1">{errors.currency}</p>}
</div>
{/* Active Toggle */}
<div>
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={formData.active}
onChange={e => updateField('active', e.target.checked)}
className="rounded"
/>
<span className="text-sm text-text-primary">Active exchange</span>
</label>
<p className="text-xs text-text-muted mt-1">
Inactive exchanges won't be used for new symbol mappings
</p>
</div>
{/* Action Buttons */}
<div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={handleClose} disabled={isSubmitting}>
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Creating...' : 'Create Exchange'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,251 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, Button } from '@/components/ui';
import { useCallback, useEffect, useState } from 'react';
import { useExchanges } from '../hooks/useExchanges';
import { CreateProviderMappingRequest } from '../types';
interface AddProviderMappingDialogProps {
isOpen: boolean;
exchangeId: string;
exchangeName: string;
onClose: () => void;
onCreateMapping: (request: CreateProviderMappingRequest) => Promise<any>;
}
export function AddProviderMappingDialog({
isOpen,
exchangeId,
exchangeName,
onClose,
onCreateMapping,
}: AddProviderMappingDialogProps) {
const { fetchProviders, fetchUnmappedProviderExchanges } = useExchanges();
const [providers, setProviders] = useState<string[]>([]);
const [selectedProvider, setSelectedProvider] = useState('');
const [unmappedExchanges, setUnmappedExchanges] = useState<any[]>([]);
const [selectedProviderExchange, setSelectedProviderExchange] = useState('');
const [loading, setLoading] = useState(false);
const [providersLoading, setProvidersLoading] = useState(false);
const [exchangesLoading, setExchangesLoading] = useState(false);
// Load providers on mount
useEffect(() => {
if (isOpen) {
loadProviders();
}
}, [isOpen, loadProviders]);
// Load unmapped exchanges when provider changes
useEffect(() => {
if (selectedProvider) {
loadUnmappedExchanges(selectedProvider);
} else {
setUnmappedExchanges([]);
setSelectedProviderExchange('');
}
}, [selectedProvider, loadUnmappedExchanges]);
const loadProviders = useCallback(async () => {
setProvidersLoading(true);
try {
const providersData = await fetchProviders();
setProviders(providersData);
} catch {
// Error loading providers - could add toast notification here
} finally {
setProvidersLoading(false);
}
}, [fetchProviders]);
const loadUnmappedExchanges = useCallback(
async (provider: string) => {
setExchangesLoading(true);
try {
const exchangesData = await fetchUnmappedProviderExchanges(provider);
setUnmappedExchanges(exchangesData);
} catch {
// Error loading unmapped exchanges - could add toast notification here
} finally {
setExchangesLoading(false);
}
},
[fetchUnmappedProviderExchanges]
);
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedProvider || !selectedProviderExchange) {
return;
}
const selectedExchange = unmappedExchanges.find(
exchange => exchange.provider_exchange_code === selectedProviderExchange
);
if (!selectedExchange) {
return;
}
setLoading(true);
try {
const request: CreateProviderMappingRequest = {
provider: selectedProvider,
provider_exchange_code: selectedExchange.provider_exchange_code,
provider_exchange_name: selectedExchange.provider_exchange_name,
master_exchange_id: exchangeId,
country_code: selectedExchange.country_code,
currency: selectedExchange.currency,
confidence: 1.0,
active: false,
verified: false,
};
await onCreateMapping(request);
} catch {
// Error creating provider mapping - could add toast notification here
} finally {
setLoading(false);
}
},
[selectedProvider, selectedProviderExchange, unmappedExchanges, exchangeId, onCreateMapping]
);
const handleClose = useCallback(() => {
setSelectedProvider('');
setSelectedProviderExchange('');
setUnmappedExchanges([]);
onClose();
}, [onClose]);
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Add Provider Mapping</DialogTitle>
<p className="text-sm text-text-muted">
Map a provider exchange to <strong>{exchangeName}</strong>
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Provider Selection */}
<div>
<label htmlFor="provider" className="block text-sm font-medium text-text-primary mb-1">
Provider
</label>
<select
id="provider"
value={selectedProvider}
onChange={e => setSelectedProvider(e.target.value)}
disabled={providersLoading}
className="w-full px-3 py-2 border border-border rounded-md bg-surface text-text-primary focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
required
>
<option value="">
{providersLoading ? 'Loading providers...' : 'Select a provider'}
</option>
{providers.map(provider => (
<option key={provider} value={provider}>
{provider.toUpperCase()}
</option>
))}
</select>
</div>
{/* Provider Exchange Selection */}
<div>
<label
htmlFor="providerExchange"
className="block text-sm font-medium text-text-primary mb-1"
>
Provider Exchange
</label>
<select
id="providerExchange"
value={selectedProviderExchange}
onChange={e => setSelectedProviderExchange(e.target.value)}
disabled={!selectedProvider || exchangesLoading}
className="w-full px-3 py-2 border border-border rounded-md bg-surface text-text-primary focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
required
>
<option value="">
{!selectedProvider
? 'Select a provider first'
: exchangesLoading
? 'Loading exchanges...'
: unmappedExchanges.length === 0
? 'No unmapped exchanges available'
: 'Select an exchange'}
</option>
{unmappedExchanges.map(exchange => (
<option key={exchange.provider_exchange_code} value={exchange.provider_exchange_code}>
{exchange.provider_exchange_code} - {exchange.provider_exchange_name}
{exchange.country_code && ` (${exchange.country_code})`}
</option>
))}
</select>
{selectedProvider && unmappedExchanges.length === 0 && !exchangesLoading && (
<p className="text-xs text-text-muted mt-1">
All exchanges for this provider are already mapped.
</p>
)}
</div>
{/* Selected Exchange Info */}
{selectedProviderExchange && (
<div className="p-3 bg-surface-secondary rounded-md">
<h4 className="text-sm font-medium text-text-primary mb-2">Selected Exchange Info</h4>
{(() => {
const exchange = unmappedExchanges.find(
ex => ex.provider_exchange_code === selectedProviderExchange
);
if (!exchange) {return null;}
return (
<div className="space-y-1 text-xs">
<div>
<span className="text-text-muted">Code:</span>{' '}
<span className="font-mono">{exchange.provider_exchange_code}</span>
</div>
<div>
<span className="text-text-muted">Name:</span> {exchange.provider_exchange_name}
</div>
{exchange.country_code && (
<div>
<span className="text-text-muted">Country:</span> {exchange.country_code}
</div>
)}
{exchange.currency && (
<div>
<span className="text-text-muted">Currency:</span> {exchange.currency}
</div>
)}
{exchange.symbol_count && (
<div>
<span className="text-text-muted">Symbols:</span> {exchange.symbol_count}
</div>
)}
</div>
);
})()}
</div>
)}
{/* Action Buttons */}
<div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={handleClose} disabled={loading}>
Cancel
</Button>
<Button
type="submit"
disabled={!selectedProvider || !selectedProviderExchange || loading}
>
{loading ? 'Creating...' : 'Create Mapping'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,216 @@
import { Dialog, Transition } from '@headlessui/react';
import { XMarkIcon } from '@heroicons/react/24/outline';
import React, { useState } from 'react';
import { AddSourceRequest } from '../types';
interface AddSourceDialogProps {
isOpen: boolean;
onClose: () => void;
onAddSource: (request: AddSourceRequest) => Promise<void>;
exchangeId: string;
exchangeName: string;
}
export function AddSourceDialog({
isOpen,
onClose,
onAddSource,
exchangeName,
}: AddSourceDialogProps) {
const [source, setSource] = useState('');
const [sourceCode, setSourceCode] = useState('');
const [id, setId] = useState('');
const [name, setName] = useState('');
const [code, setCode] = useState('');
const [aliases, setAliases] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!source || !sourceCode || !id || !name || !code) {return;}
setLoading(true);
try {
await onAddSource({
source,
source_code: sourceCode,
mapping: {
id,
name,
code,
aliases: aliases
.split(',')
.map(a => a.trim())
.filter(Boolean),
},
});
// Reset form
setSource('');
setSourceCode('');
setId('');
setName('');
setCode('');
setAliases('');
} catch (_error) {
// TODO: Implement proper error handling/toast notification
// eslint-disable-next-line no-console
console.error('Error adding source:', _error);
} finally {
setLoading(false);
}
};
return (
<Transition appear show={isOpen} as={React.Fragment}>
<Dialog as="div" className="relative z-50" onClose={onClose}>
<Transition.Child
as={React.Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<Transition.Child
as={React.Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-lg bg-background border border-border p-6 text-left align-middle shadow-xl transition-all">
<div className="flex items-center justify-between mb-4">
<Dialog.Title className="text-lg font-medium text-text-primary">
Add Source to {exchangeName}
</Dialog.Title>
<button
onClick={onClose}
className="text-text-muted hover:text-text-primary transition-colors"
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-text-primary mb-1">
Source Provider
</label>
<select
value={source}
onChange={e => setSource(e.target.value)}
className="w-full bg-surface border border-border rounded px-3 py-2 text-text-primary focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
required
>
<option value="">Select a source</option>
<option value="ib">Interactive Brokers</option>
<option value="alpaca">Alpaca</option>
<option value="polygon">Polygon</option>
<option value="yahoo">Yahoo Finance</option>
<option value="alpha_vantage">Alpha Vantage</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-text-primary mb-1">
Source Code
</label>
<input
type="text"
value={sourceCode}
onChange={e => setSourceCode(e.target.value)}
className="w-full bg-surface border border-border rounded px-3 py-2 text-text-primary focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
placeholder="e.g., IB, ALP, POLY"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-primary mb-1">
Source ID
</label>
<input
type="text"
value={id}
onChange={e => setId(e.target.value)}
className="w-full bg-surface border border-border rounded px-3 py-2 text-text-primary focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
placeholder="e.g., NYSE, NASDAQ"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-primary mb-1">
Source Name
</label>
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
className="w-full bg-surface border border-border rounded px-3 py-2 text-text-primary focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
placeholder="e.g., New York Stock Exchange"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-primary mb-1">
Source Code
</label>
<input
type="text"
value={code}
onChange={e => setCode(e.target.value)}
className="w-full bg-surface border border-border rounded px-3 py-2 text-text-primary focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
placeholder="e.g., NYSE"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-primary mb-1">
Aliases (comma-separated)
</label>
<input
type="text"
value={aliases}
onChange={e => setAliases(e.target.value)}
className="w-full bg-surface border border-border rounded px-3 py-2 text-text-primary focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
placeholder="e.g., NYSE, New York, Big Board"
/>
</div>
<div className="flex justify-end space-x-3 pt-4">
<button
type="button"
onClick={onClose}
className="px-4 py-2 border border-border text-text-secondary hover:text-text-primary hover:bg-surface-secondary rounded transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={loading || !source || !sourceCode || !id || !name || !code}
className="px-4 py-2 bg-primary-500 text-white rounded hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Adding...' : 'Add Source'}
</button>
</div>
</form>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
}

View file

@ -0,0 +1,110 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, Button } from '@/components/ui';
import { useCallback, useState } from 'react';
import { TrashIcon, ExclamationTriangleIcon } from '@heroicons/react/24/outline';
interface DeleteExchangeDialogProps {
isOpen: boolean;
exchangeId: string;
exchangeName: string;
providerMappingCount: number;
onClose: () => void;
onConfirmDelete: (exchangeId: string) => Promise<boolean>;
}
export function DeleteExchangeDialog({
isOpen,
exchangeId,
exchangeName,
providerMappingCount,
onClose,
onConfirmDelete,
}: DeleteExchangeDialogProps) {
const [loading, setLoading] = useState(false);
const handleConfirm = useCallback(async () => {
setLoading(true);
try {
const success = await onConfirmDelete(exchangeId);
if (success) {
onClose();
}
} catch {
// Error deleting exchange - could add toast notification here
} finally {
setLoading(false);
}
}, [exchangeId, onConfirmDelete, onClose]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-danger">
<ExclamationTriangleIcon className="h-5 w-5" />
Delete Exchange
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="p-4 bg-danger/10 border border-danger/20 rounded-lg">
<p className="text-sm text-text-primary">
Are you sure you want to delete <strong>"{exchangeName}"</strong>?
</p>
</div>
<div className="space-y-2 text-sm text-text-secondary">
<p className="font-medium text-text-primary">This action will:</p>
<ul className="list-disc list-inside space-y-1 ml-2">
<li>Hide the exchange from all lists</li>
{providerMappingCount > 0 && (
<li className="text-yellow-400">
Delete {providerMappingCount} provider mapping{providerMappingCount !== 1 ? 's' : ''}
</li>
)}
<li>Make provider exchanges available for remapping</li>
</ul>
</div>
{providerMappingCount > 0 && (
<div className="p-3 bg-yellow-500/10 border border-yellow-500/20 rounded-md">
<div className="flex items-start gap-2">
<ExclamationTriangleIcon className="h-4 w-4 text-yellow-400 mt-0.5 flex-shrink-0" />
<div className="text-sm">
<p className="font-medium text-yellow-400">Warning</p>
<p className="text-text-secondary">
This exchange has {providerMappingCount} provider mapping{providerMappingCount !== 1 ? 's' : ''}.
Deleting will permanently remove these mappings and make the provider exchanges
available for mapping to other exchanges.
</p>
</div>
</div>
</div>
)}
<div className="bg-surface-secondary p-3 rounded-md">
<p className="text-xs text-text-muted">
<strong>Note:</strong> This action cannot be undone. The exchange will be hidden
but can be restored by directly updating the database if needed.
</p>
</div>
</div>
{/* Action Buttons */}
<div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={onClose} disabled={loading}>
Cancel
</Button>
<Button
type="button"
onClick={handleConfirm}
disabled={loading}
className="bg-danger hover:bg-danger/90 text-white"
>
<TrashIcon className="h-4 w-4 mr-1" />
{loading ? 'Deleting...' : 'Delete Exchange'}
</Button>
</div>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,448 @@
import { DataTable } from '@/components/ui';
import { PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
import { ColumnDef } from '@tanstack/react-table';
import { useCallback, useMemo, useState } from 'react';
import { useExchanges } from '../hooks/useExchanges';
import { Exchange, EditingCell, AddProviderMappingDialogState, DeleteDialogState } from '../types';
import { AddProviderMappingDialog } from './AddProviderMappingDialog';
import { DeleteExchangeDialog } from './DeleteExchangeDialog';
import { sortProviderMappings, getProviderMappingColor, formatProviderMapping, formatDate } from '../utils/formatters';
export function ExchangesTable() {
const {
exchanges,
loading,
error,
updateExchange,
updateProviderMapping,
createProviderMapping,
refetch
} = useExchanges();
const [editingCell, setEditingCell] = useState<EditingCell | null>(null);
const [editValue, setEditValue] = useState('');
const [addProviderDialog, setAddProviderDialog] = useState<AddProviderMappingDialogState | null>(null);
const [deleteDialog, setDeleteDialog] = useState<DeleteDialogState | null>(null);
const handleCellEdit = useCallback(
async (id: string, field: string, value: string) => {
if (field === 'name' || field === 'code') {
await updateExchange(id, { [field]: value });
}
setEditingCell(null);
setEditValue('');
},
[updateExchange]
);
const handleToggleActive = useCallback(
async (id: string, currentStatus: boolean) => {
await updateExchange(id, { active: !currentStatus });
},
[updateExchange]
);
const handleAddProviderMapping = useCallback(async (exchangeId: string, exchangeName: string) => {
setAddProviderDialog({ exchangeId, exchangeName });
}, []);
const handleDeleteExchange = useCallback((exchangeId: string, exchangeName: string, providerMappingCount: number) => {
setDeleteDialog({ exchangeId, exchangeName, providerMappingCount });
}, []);
const handleConfirmDelete = useCallback(async (exchangeId: string) => {
const success = await updateExchange(exchangeId, { visible: false });
if (success) {
refetch();
}
return success;
}, [updateExchange, refetch]);
const handleToggleProviderMapping = useCallback(
async (mappingId: string, currentStatus: boolean) => {
const success = await updateProviderMapping(mappingId, { active: !currentStatus });
if (success) {
// Refresh the main table data to get updated counts and mappings
refetch();
}
},
[updateProviderMapping, refetch]
);
const handleRowExpand = useCallback(
async (_row: any) => {
// Row expansion is now handled automatically by TanStack Table
// No need to fetch data since all mappings are already loaded
},
[]
);
const columns = useMemo<ColumnDef<Exchange>[]>(() => {
return [
{
id: 'expander',
header: '',
cell: ({ row }) => {
return row.getCanExpand() ? (
<button
onClick={() => {
row.getToggleExpandedHandler()();
handleRowExpand(row);
}}
className="text-text-secondary hover:text-text-primary transition-colors w-6 h-6 flex items-center justify-center"
>
{row.getIsExpanded() ? '▼' : '▶'}
</button>
) : null;
},
size: 40,
enableResizing: false,
disableTooltip: true,
},
{
id: 'code',
header: 'Code',
accessorKey: 'code',
size: 120,
cell: ({ getValue, row, cell: _cell }) => {
const isEditing =
editingCell?.id === row.original.id && editingCell?.field === 'code';
if (isEditing) {
return (
<input
type="text"
value={editValue}
onChange={e => setEditValue(e.target.value)}
onBlur={() => handleCellEdit(row.original.id, 'code', editValue)}
onKeyDown={e => {
if (e.key === 'Enter') {
handleCellEdit(row.original.id, 'code', editValue);
} else if (e.key === 'Escape') {
setEditingCell(null);
setEditValue('');
}
}}
className="w-full bg-surface border border-border rounded px-2 py-1 text-sm font-mono"
autoFocus
/>
);
}
return (
<div
className="cursor-pointer hover:bg-surface-secondary rounded px-2 py-1 transition-colors text-sm font-mono font-medium truncate overflow-hidden text-ellipsis whitespace-nowrap"
onClick={() => {
setEditingCell({ id: row.original.id, field: 'code' });
setEditValue(getValue() as string);
}}
>
{getValue() as string}
</div>
);
},
},
{
id: 'name',
header: 'Name',
accessorKey: 'name',
size: 250,
cell: ({ getValue, row, cell: _cell }) => {
const isEditing =
editingCell?.id === row.original.id && editingCell?.field === 'name';
if (isEditing) {
return (
<input
type="text"
value={editValue}
onChange={e => setEditValue(e.target.value)}
onBlur={() => handleCellEdit(row.original.id, 'name', editValue)}
onKeyDown={e => {
if (e.key === 'Enter') {
handleCellEdit(row.original.id, 'name', editValue);
} else if (e.key === 'Escape') {
setEditingCell(null);
setEditValue('');
}
}}
className="w-full bg-surface border border-border rounded px-2 py-1 text-sm"
autoFocus
/>
);
}
return (
<div
className="cursor-pointer hover:bg-surface-secondary rounded px-2 py-1 transition-colors text-sm truncate overflow-hidden text-ellipsis whitespace-nowrap"
onClick={() => {
setEditingCell({ id: row.original.id, field: 'name' });
setEditValue(getValue() as string);
}}
>
{getValue() as string}
</div>
);
},
},
{
id: 'country',
header: 'Country',
accessorKey: 'country',
size: 80,
cell: ({ getValue }) => (
<span className="text-text-secondary text-sm block truncate">{getValue() as string}</span>
),
},
{
id: 'currency',
header: 'Currency',
accessorKey: 'currency',
size: 80,
cell: ({ getValue }) => (
<span className="font-mono text-text-secondary text-sm block truncate">
{getValue() as string}
</span>
),
},
{
id: 'active',
header: 'Active',
accessorKey: 'active',
size: 80,
disableTooltip: true,
cell: ({ getValue, row }) => {
const isActive = getValue() as boolean;
return (
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
checked={isActive}
onChange={() => handleToggleActive(row.original.id, isActive)}
className="sr-only peer"
/>
<div className="w-9 h-5 bg-surface-secondary peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary-500 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-primary-500"></div>
</label>
);
},
},
{
id: 'provider_mappings',
header: 'Provider Mappings',
accessorKey: 'provider_mapping_count',
size: 180,
disableTooltip: true,
cell: ({ getValue, row }) => {
const totalMappings = parseInt(getValue() as string) || 0;
const activeMappings = parseInt(row.original.active_mapping_count) || 0;
const _verifiedMappings = parseInt(row.original.verified_mapping_count) || 0;
// Get provider mappings directly from the exchange data
const mappings = row.original.provider_mappings || [];
const sortedMappings = sortProviderMappings(mappings);
return (
<div className="flex flex-col gap-1">
<div className="text-sm">
<span className="text-text-primary font-medium">{totalMappings}</span>
<span className="text-text-muted"> total</span>
{activeMappings > 0 && (
<span className="ml-2 text-green-400 text-xs">
{activeMappings} active
</span>
)}
</div>
{mappings.length > 0 ? (
<div className="flex flex-wrap gap-1 text-xs">
{sortedMappings.slice(0, 3).map((mapping, index) => (
<span key={index} className={getProviderMappingColor(mapping)}>
{formatProviderMapping(mapping)}
</span>
))}
{sortedMappings.length > 3 && (
<span className="text-text-muted">+{sortedMappings.length - 3} more</span>
)}
</div>
) : (
<div className="text-xs text-text-muted">No mappings</div>
)}
</div>
);
},
},
{
id: 'actions',
header: 'Actions',
size: 160,
disableTooltip: true,
cell: ({ row }) => (
<div className="flex gap-1">
<button
onClick={() => handleAddProviderMapping(row.original.id, row.original.name)}
className="inline-flex items-center gap-1 px-3 py-1.5 bg-primary-500/20 text-primary-400 rounded text-xs hover:bg-primary-500/30 transition-colors whitespace-nowrap"
title="Add Provider Mapping"
>
<PlusIcon className="h-3 w-3" />
Add
</button>
<button
onClick={() => handleDeleteExchange(
row.original.id,
row.original.name,
parseInt(row.original.provider_mapping_count) || 0
)}
className="inline-flex items-center gap-1 px-3 py-1.5 bg-danger/20 text-danger rounded text-xs hover:bg-danger/30 transition-colors whitespace-nowrap"
title="Delete Exchange"
>
<TrashIcon className="h-3 w-3" />
Delete
</button>
</div>
),
},
{
id: 'updated_at',
header: 'Last Updated',
accessorKey: 'updated_at',
size: 120,
cell: ({ getValue }) => (
<span className="text-xs text-text-muted">
{formatDate(getValue() as string)}
</span>
),
},
];
}, [
editingCell,
editValue,
handleCellEdit,
handleToggleActive,
handleAddProviderMapping,
handleDeleteExchange,
handleConfirmDelete,
handleRowExpand,
]);
if (error) {
return (
<div className="bg-danger/10 border border-danger/20 rounded-lg p-4">
<h3 className="text-danger font-medium mb-2">Error Loading Exchanges</h3>
<p className="text-text-secondary text-sm">{error}</p>
<p className="text-text-muted text-xs mt-2">
Make sure the web-api service is running on localhost:4000
</p>
</div>
);
}
const renderSubComponent = ({ row }: { row: any }) => {
const exchange = row.original as Exchange;
const mappings = exchange.provider_mappings || [];
if (mappings.length === 0) {
return (
<div className="p-4 text-center text-text-muted">
<div className="text-sm">No provider mappings found for this exchange.</div>
<button
onClick={() => handleAddProviderMapping(exchange.id, exchange.name)}
className="mt-2 text-primary-400 hover:text-primary-300 text-sm underline"
>
Add the first provider mapping
</button>
</div>
);
}
return (
<div className="p-4 bg-surface-secondary/50">
<h4 className="text-sm font-medium text-text-primary mb-3">Provider Mappings</h4>
<div className="space-y-2">
{mappings.map((mapping) => (
<div key={mapping.id} className="flex items-center justify-between p-3 bg-surface rounded border border-border">
<div className="flex-1">
<div className="flex items-center gap-3">
<span className="font-mono text-xs bg-primary-500/20 text-primary-400 px-2 py-1 rounded">
{mapping.provider.toUpperCase()}
</span>
<span className="font-medium text-text-primary">
{mapping.provider_exchange_code}
</span>
<span className="text-text-secondary">
{mapping.provider_exchange_name}
</span>
{mapping.country_code && (
<span className="text-xs text-text-muted">
{mapping.country_code}
</span>
)}
</div>
<div className="flex items-center gap-4 mt-1 text-xs text-text-muted">
<span>Confidence: {mapping.confidence}</span>
<span>Created: {formatDate(mapping.created_at)}</span>
{mapping.auto_mapped && <span className="text-yellow-400">Auto-mapped</span>}
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex items-center gap-1">
{mapping.verified && (
<span className="text-blue-400" title="Verified">
✓
</span>
)}
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
checked={mapping.active}
onChange={() => handleToggleProviderMapping(mapping.id, mapping.active)}
className="sr-only peer"
/>
<div className="w-6 h-3 bg-surface-secondary peer-focus:outline-none peer-focus:ring-1 peer-focus:ring-primary-500 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[1px] after:left-[1px] after:bg-white after:rounded-full after:h-2.5 after:w-2.5 after:transition-all peer-checked:bg-primary-500"></div>
</label>
</div>
</div>
</div>
))}
</div>
</div>
);
};
return (
<>
<DataTable
data={exchanges || []}
columns={columns}
loading={loading}
getRowCanExpand={() => true}
renderSubComponent={renderSubComponent}
/>
{addProviderDialog && (
<AddProviderMappingDialog
isOpen={true}
exchangeId={addProviderDialog.exchangeId}
exchangeName={addProviderDialog.exchangeName}
onClose={() => setAddProviderDialog(null)}
onCreateMapping={async (mappingRequest) => {
const result = await createProviderMapping(mappingRequest);
if (result) {
setAddProviderDialog(null);
refetch();
}
}}
/>
)}
{deleteDialog && (
<DeleteExchangeDialog
isOpen={true}
exchangeId={deleteDialog.exchangeId}
exchangeName={deleteDialog.exchangeName}
providerMappingCount={deleteDialog.providerMappingCount}
onClose={() => setDeleteDialog(null)}
onConfirmDelete={handleConfirmDelete}
/>
)}
</>
);
}

View file

@ -0,0 +1,5 @@
export { AddSourceDialog } from './AddSourceDialog';
export { AddProviderMappingDialog } from './AddProviderMappingDialog';
export { AddExchangeDialog } from './AddExchangeDialog';
export { DeleteExchangeDialog } from './DeleteExchangeDialog';
export { ExchangesTable } from './ExchangesTable';