feat(ledger): add link for download ledger entries to .csv (#3454)

This commit is contained in:
Maciek 2023-04-27 10:53:28 +02:00 committed by GitHub
parent c19bcc5e0c
commit 6a29dc82ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 193 additions and 5 deletions

View File

@ -12,4 +12,5 @@ export default {
}, },
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/ledger', coverageDirectory: '../../coverage/libs/ledger',
setupFilesAfterEnv: ['./src/setup-tests.ts'],
}; };

View File

@ -30,7 +30,10 @@ export type LedgerEntry = LedgerEntryFragment & {
}; };
export type AggregatedLedgerEntriesEdge = Schema.AggregatedLedgerEntriesEdge; export type AggregatedLedgerEntriesEdge = Schema.AggregatedLedgerEntriesEdge;
export type AggregatedLedgerEntriesNode = AggregatedLedgerEntriesEdge & { export type AggregatedLedgerEntriesNode = Omit<
AggregatedLedgerEntriesEdge,
'node'
> & {
node: LedgerEntry; node: LedgerEntry;
}; };

View File

@ -32,7 +32,7 @@ export const ledgerEntriesQuery = (
return merge(defaultResult, override); return merge(defaultResult, override);
}; };
const ledgerEntries: LedgerEntryFragment[] = [ export const ledgerEntries: LedgerEntryFragment[] = [
{ {
vegaTime: '1669224476734364000', vegaTime: '1669224476734364000',
quantity: '0', quantity: '0',
@ -180,7 +180,6 @@ const ledgerEntries: LedgerEntryFragment[] = [
toAccountBalance: '0', toAccountBalance: '0',
fromAccountBalance: '0', fromAccountBalance: '0',
}, },
{ {
vegaTime: '2022-11-24T12:41:22.054428Z', vegaTime: '2022-11-24T12:41:22.054428Z',
quantity: '1000000000', quantity: '1000000000',

View File

@ -0,0 +1,85 @@
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LedgerExportLink } from './ledger-export-link';
import * as Types from '@vegaprotocol/types';
import { ledgerEntries } from './ledger-entries.mock';
import type { LedgerEntry } from './ledger-entries-data-provider';
const VEGA_URL = 'https://vega-url.co.uk/querystuff';
const mockEnvironment = jest.fn(() => VEGA_URL);
jest.mock('@vegaprotocol/environment', () => ({
useEnvironment: jest.fn(() => mockEnvironment()),
}));
const asset = {
id: 'assetID',
name: 'assetName',
symbol: 'assetSymbol',
decimals: 1,
quantum: '1',
status: Types.AssetStatus,
source: {
__typename: 'ERC20',
contractAddress: 'contractAddres',
lifetimeLimit: 'lifetimeLimit',
withdrawThreshold: 'withdraw',
},
};
describe('LedgerExportLink', () => {
const partyId = 'partyId';
const entries = ledgerEntries.map((entry) => {
return {
...entry,
asset: entry.assetId
? {
...asset,
id: entry.assetId,
name: `name ${entry.assetId}`,
symbol: `symbol ${entry.assetId}`,
}
: null,
marketSender: null,
marketReceiver: null,
} as LedgerEntry;
});
it('should be properly rendered', async () => {
render(<LedgerExportLink partyId={partyId} entries={entries} />);
await waitFor(() => {
expect(screen.getByRole('link')).toBeInTheDocument();
expect(screen.getByRole('link')).toHaveAttribute(
'href',
`https://vega-url.co.uk/api/v2/ledgerentry/export?partyId=${partyId}&assetId=asset-id`
);
expect(
screen.getByRole('button', { name: /^symbol asset-id/ })
).toBeInTheDocument();
});
});
it('should be properly change link url', async () => {
render(<LedgerExportLink partyId={partyId} entries={entries} />);
await waitFor(() => {
expect(
screen.getByRole('button', { name: /^symbol asset-id/ })
).toBeInTheDocument();
});
act(() => {
userEvent.click(screen.getByRole('button', { name: /^symbol asset-id/ }));
});
await waitFor(() => {
expect(screen.getByRole('menu')).toBeInTheDocument();
});
act(() => {
userEvent.click(
screen.getByRole('menuitem', { name: /^symbol asset-id-2/ })
);
});
await waitFor(() => {
expect(screen.getByRole('link')).toHaveAttribute(
'href',
`https://vega-url.co.uk/api/v2/ledgerentry/export?partyId=${partyId}&assetId=asset-id-2`
);
});
});
});

View File

@ -0,0 +1,71 @@
import type { LedgerEntry } from './ledger-entries-data-provider';
import { useMemo, useState } from 'react';
import { useEnvironment } from '@vegaprotocol/environment';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Link,
Button,
} from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
const getProtoHost = (vegaurl: string) => {
const loc = new URL(vegaurl);
return `${loc.protocol}//${loc.host}`;
};
export const LedgerExportLink = ({
partyId,
entries,
}: {
partyId: string;
entries: LedgerEntry[];
}) => {
const assets = entries.reduce((aggr, item) => {
if (item.asset && !(item.asset.id in aggr)) {
aggr[item.asset.id] = item.asset.symbol;
}
return aggr;
}, {} as Record<string, string>);
const [assetId, setAssetId] = useState(Object.keys(assets)[0]);
const VEGA_URL = useEnvironment((store) => store.VEGA_URL);
const protohost = VEGA_URL ? getProtoHost(VEGA_URL) : '';
const assetDropDown = useMemo(() => {
return (
<DropdownMenu
trigger={<DropdownMenuTrigger>{assets[assetId]}</DropdownMenuTrigger>}
>
<DropdownMenuContent>
{Object.keys(assets).map((assetKey) => (
<DropdownMenuItem
key={assetKey}
onSelect={() => setAssetId(assetKey)}
>
{assets[assetKey]}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}, [assetId, assets]);
if (!protohost) {
return null;
}
return (
<div className="flex shrink items-stretch gap-2 p-2">
<div className="flex items-center">Export all</div>
{assetDropDown}
<Link
className="text-sm"
title={t('Download all to .csv file')}
href={`${protohost}/api/v2/ledgerentry/export?partyId=${partyId}&assetId=${assetId}`}
>
<Button size="sm">{t('Download')}</Button>
</Link>
</div>
);
};

View File

@ -3,12 +3,13 @@ import type * as Schema from '@vegaprotocol/types';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit'; import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import type { FilterChangedEvent } from 'ag-grid-community'; import type { FilterChangedEvent } from 'ag-grid-community';
import type { AgGridReact } from 'ag-grid-react'; import type { AgGridReact } from 'ag-grid-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { subDays, formatRFC3339 } from 'date-fns'; import { subDays, formatRFC3339 } from 'date-fns';
import type { AggregatedLedgerEntriesNode } from './ledger-entries-data-provider'; import type { AggregatedLedgerEntriesNode } from './ledger-entries-data-provider';
import { useLedgerEntriesDataProvider } from './ledger-entries-data-provider'; import { useLedgerEntriesDataProvider } from './ledger-entries-data-provider';
import { LedgerTable } from './ledger-table'; import { LedgerTable } from './ledger-table';
import type * as Types from '@vegaprotocol/types'; import type * as Types from '@vegaprotocol/types';
import { LedgerExportLink } from './ledger-export-link';
export interface Filter { export interface Filter {
vegaTime?: { vegaTime?: {
@ -22,6 +23,7 @@ const defaultFilter = {
value: { start: formatRFC3339(subDays(Date.now(), 7)) }, value: { start: formatRFC3339(subDays(Date.now(), 7)) },
}, },
}; };
export const LedgerManager = ({ partyId }: { partyId: string }) => { export const LedgerManager = ({ partyId }: { partyId: string }) => {
const gridRef = useRef<AgGridReact | null>(null); const gridRef = useRef<AgGridReact | null>(null);
const [filter, setFilter] = useState<Filter>(defaultFilter); const [filter, setFilter] = useState<Filter>(defaultFilter);
@ -55,6 +57,9 @@ export const LedgerManager = ({ partyId }: { partyId: string }) => {
rowData={extractedData} rowData={extractedData}
onFilterChanged={onFilterChanged} onFilterChanged={onFilterChanged}
/> />
{extractedData && (
<LedgerExportLink entries={extractedData} partyId={partyId} />
)}
<div className="pointer-events-none absolute inset-0"> <div className="pointer-events-none absolute inset-0">
<AsyncRenderer <AsyncRenderer
loading={loading} loading={loading}

View File

@ -49,7 +49,7 @@ export const LedgerTable = forwardRef<AgGridReact, LedgerEntryProps>(
(props, ref) => { (props, ref) => {
return ( return (
<AgGrid <AgGrid
style={{ width: '100%', height: '100%' }} style={{ width: '100%', height: 'calc(100% - 50px)' }}
ref={ref} ref={ref}
tooltipShowDelay={500} tooltipShowDelay={500}
defaultColDef={{ defaultColDef={{

View File

@ -0,0 +1,24 @@
import '@testing-library/jest-dom';
import 'jest-canvas-mock';
import ResizeObserver from 'resize-observer-polyfill';
global.ResizeObserver = ResizeObserver;
global.DOMRect = class DOMRect {
bottom = 0;
left = 0;
right = 0;
top = 0;
constructor(
public x = 0,
public y = 0,
public width = 0,
public height = 0
) {}
static fromRect(other?: DOMRectInit): DOMRect {
return new DOMRect(other?.x, other?.y, other?.width, other?.height);
}
toJSON() {
return JSON.stringify(this);
}
};