diff --git a/deploy/site.py b/deploy/site.py index 3fd9a8cad..25f013501 100644 --- a/deploy/site.py +++ b/deploy/site.py @@ -253,7 +253,7 @@ def deploy(m, root, metadata, receipt): d.require(aws.call('s3api', 'get-bucket-versioning', Bucket=m['bucket']).get('Status') == 'Enabled', 'Enable bucket versioning before release') release = sha + '-' + os.environ.get('CIRCLE_BUILD_NUM', '') d.require(re.fullmatch(r'[a-f0-9]{40}-[0-9]{1,12}', release), 'Invalid release identity') - entries = {'asset-manifest.json': root / 'asset-manifest.json', 'index.html': root / 'index.html', 'gigs/index.html': root / 'index.html', 'timeline-wall/index.html': root / 'index.html'} + entries = {'asset-manifest.json': root / 'asset-manifest.json', 'index.html': root / 'index.html', 'gigs/index.html': root / 'index.html', 'timeline-wall/index.html': root / 'index.html', 'statistics/index.html': root / 'index.html'} with tempfile.TemporaryDirectory(prefix='platform-ui-rollback-') as directory: previous = {} for number, key in enumerate(entries): @@ -262,13 +262,13 @@ def deploy(m, root, metadata, receipt): info = aws.call('s3api', 'get-object', extra=(str(target),), Bucket=m['bucket'], Key=key) previous[key] = (target, info.get('VersionId')) except d.DeployError as exc: - if key not in ('gigs/index.html', 'timeline-wall/index.html') or not re.search(r'\((NoSuchKey|404)\)|: (NoSuchKey|404)$', str(exc)): + if key not in ('gigs/index.html', 'timeline-wall/index.html', 'statistics/index.html') or not re.search(r'\((NoSuchKey|404)\)|: (NoSuchKey|404)$', str(exc)): raise previous[key] = previous['index.html'] promoted = False try: aws.sync(root, m['bucket'], ['--exclude', '*', '--include', 'static/*'], 'public,max-age=31536000,immutable') - aws.sync(root, m['bucket'], ['--exclude', 'static/*', '--exclude', 'index.html', '--exclude', 'gigs/index.html', '--exclude', 'timeline-wall/index.html', '--exclude', 'asset-manifest.json'], NO_CACHE) + aws.sync(root, m['bucket'], ['--exclude', 'static/*', '--exclude', 'index.html', '--exclude', 'gigs/index.html', '--exclude', 'timeline-wall/index.html', '--exclude', 'statistics/index.html', '--exclude', 'asset-manifest.json'], NO_CACHE) for key, path in entries.items(): promoted = True put(aws, m, key, path, sha) diff --git a/deploy/tests/test_site.py b/deploy/tests/test_site.py index 17e70e40e..edcec8836 100644 --- a/deploy/tests/test_site.py +++ b/deploy/tests/test_site.py @@ -146,10 +146,10 @@ def test_failed_public_verification_restores_previous_shells(self): with patch.object(site, 'check_job', return_value='a' * 40), patch.object(site, 'verify_artifact'), patch.object(site, 'authenticate', return_value=aws), patch.object(site, 'invalidate', return_value='invalidation'), patch.object(site, 'urlopen', side_effect=OSError('network')), patch.dict(os.environ, {'CIRCLE_BUILD_NUM': '1'}): with self.assertRaises(OSError): site.deploy(self.m, root, self.root / 'artifact.json', self.root / 'receipt.json') - self.assertEqual(len(aws.puts), 8) - self.assertTrue(all(body == b'previous' for _, body in aws.puts[-4:])) - self.assertEqual([key for key, _ in aws.puts[-4:]], - ['asset-manifest.json', 'index.html', 'gigs/index.html', 'timeline-wall/index.html']) + self.assertEqual(len(aws.puts), 10) + self.assertTrue(all(body == b'previous' for _, body in aws.puts[-5:])) + self.assertEqual([key for key, _ in aws.puts[-5:]], + ['asset-manifest.json', 'index.html', 'gigs/index.html', 'timeline-wall/index.html', 'statistics/index.html']) class FakeAWS: diff --git a/infrastructure/statistics-routing/README.md b/infrastructure/statistics-routing/README.md new file mode 100644 index 000000000..83103d5c4 --- /dev/null +++ b/infrastructure/statistics-routing/README.md @@ -0,0 +1,65 @@ +# Public statistics migration + +`src/apps/statistics` restores the public community statistics page in Platform UI. +The General, Development, Design, QA, SRM, and Marathon Match categories use the +existing public `/v6/reports/statistics` endpoints. Totals, sortable/filterable +reports, member profile links, pagination, empty states, and retry are available +without signing in. SRM/MM reports are historical snapshots, as in the API. + +## Routes and release + +- `statistics.topcoder-dev.com` / `statistics.topcoder.com`: Platform UI distribution + aliases, covered by the existing wildcard ACM certificates. Public Route 53 A + aliases target the respective platform distribution; add AAAA only when IPv6 is enabled. +- `topcoder-dev.com/statistics` / `topcoder.com/statistics` (including `www` and + category paths): website viewer function selects the existing private Platform UI + origin and requests `/statistics/index.html`. Apex canonicalizes to `www`. +- `/community/statistics` and descendants: permanent redirects to `/statistics`, + retaining category suffixes and encoded/repeated query parameters. Platform UI + also supplies a client redirect for SPA navigation, retaining the fragment. +- Insert `platform-host-fragment.js` after the host lookup in the **current** platform + viewer function. Preserve all existing Contact, Accounts, TopGear, and Timeline logic. +- Add the new statistics origin to the existing Universal Navigation CORS policy. + The reports API already permits public browser requests. +- Grant the website distribution `s3:GetObject` on only `statistics/index.html` + in the existing platform bucket, retaining all other policy statements. + +The website source change belongs to `topcoder-website/infra/aws/site.yml`. +Apply its narrow function change to the current deployed CloudFormation template, +retaining independently installed Timeline/Gigs behaviors and all unrelated resources. +Review a change set before execution. Never replace a live template with a stale checkout. + +Build each environment with its pinned browser configuration. Upload immutable +`static/` assets first and publish only `statistics/index.html` for an isolated +pre-merge release; preserve shared root HTML and existing assets. After merge, +`deploy/site.py` promotes and rolls back the statistics shell alongside the other +entry points. Existing website `/static/` routing serves the assets from Platform UI. + +Before activation, capture templates/parameters, functions/configuration/ETags, +bucket policies, navigation CORS policy, distribution aliases, and DNS. Re-read +before each write and preserve concurrent changes. Wait for CloudFormation +`UPDATE_COMPLETE`, CloudFront `Deployed`, DNS `INSYNC`, and completed invalidations. +Verify all host/path variants, deep links, queries, categories, API responses, +mobile layout, and unrelated website/platform smoke checks. + +## Rollback + +Restore the prior statistics HTML object version, remove only the added host aliases +and DNS records, and revert the marked statistics function code and website function +change with current ETags. Remove only the statistics bucket grant and navigation +CORS origin. Preserve assets for open tabs. Invalidate the statistics and legacy paths. + +## Validation + +```sh +yarn tsc --noEmit +yarn eslint src/apps/statistics src/config/constants.ts src/apps/platform/src/platform.routes.tsx +yarn craco test --watchAll=false --runInBand src/apps/statistics +python3 -m unittest discover -s infrastructure/statistics-routing +python3 -m unittest discover -s deploy/tests +``` + +The website viewer tests cover both environments and retirement modes. The related +reports-api change prevents service-account member IDs from breaking first-time +submitter reports; its PostgreSQL regression checks preserve earliest-submission +and maximum-rating semantics. diff --git a/infrastructure/statistics-routing/platform-host-fragment.js b/infrastructure/statistics-routing/platform-host-fragment.js new file mode 100644 index 000000000..5ec3d4d41 --- /dev/null +++ b/infrastructure/statistics-routing/platform-host-fragment.js @@ -0,0 +1,10 @@ + // Public statistics shell; keep shared assets and all other hosts unchanged. + if (host === 'statistics.topcoder-dev.com' || host === 'statistics.topcoder.com' + || host === 'statistics.topcoder-dev.com:443' || host === 'statistics.topcoder.com:443') { + if (request.uri.indexOf('/static/') === 0 + || ['/global.css', '/favicon.png', '/manifest.json', '/logo_512x512.png', '/robots.txt'].indexOf(request.uri) !== -1) { + return request; + } + request.uri = '/statistics/index.html'; + return request; + } diff --git a/infrastructure/statistics-routing/test_routes.py b/infrastructure/statistics-routing/test_routes.py new file mode 100644 index 000000000..2442f30e0 --- /dev/null +++ b/infrastructure/statistics-routing/test_routes.py @@ -0,0 +1,29 @@ +"""Execute the hostname fragment and check the surrounding platform routes are unchanged.""" +from pathlib import Path +import subprocess +import unittest + + +class HostRoutingTest(unittest.TestCase): + def test_host_shell_and_asset_isolation(self): + fragment = Path(__file__).with_name('platform-host-fragment.js').read_text() + source = 'function handler(event) { var request = event.request; var host = request.headers.host.value;\n' + source += fragment + '\nreturn request; }\n' + checks = r''' +const assert = require('node:assert/strict'); +function run(host, uri) { return handler({ request: { headers: {host: {value: host}}, uri } }).uri; } +for (const env of ['topcoder-dev.com', 'topcoder.com']) { + for (const port of ['', ':443']) { + for (const uri of ['/', '/design', '/statistics', '/statistics/qa']) { + assert.equal(run('statistics.' + env + port, uri), '/statistics/index.html'); + } + for (const uri of ['/static/js/main.js', '/global.css', '/manifest.json']) { + assert.equal(run('statistics.' + env + port, uri), uri); + } + } + for (const host of ['platform-ui.', 'sales.', 'timeline.', 'topgear.', 'account-settings.']) { + for (const uri of ['/', '/design', '/challenges']) assert.equal(run(host + env, uri), uri); + } +} +''' + subprocess.run(['node', '-e', source + checks], check=True) diff --git a/src/apps/platform/src/platform.routes.tsx b/src/apps/platform/src/platform.routes.tsx index a592b3420..25afa3ade 100644 --- a/src/apps/platform/src/platform.routes.tsx +++ b/src/apps/platform/src/platform.routes.tsx @@ -26,6 +26,7 @@ import { forumsRoutes } from '~/apps/forums' import { legacyOpportunityRoutes, opportunitiesRoutes, topgearRoutes } from '~/apps/opportunities' import { analyticsRoutes } from '~/apps/analytics' import { contactRoutes } from '~/apps/contact' +import { statisticsRoutes } from '~/apps/statistics' import { gigsRoutes } from '~/apps/gigs' const Home: LazyLoadedComponent = lazyLoad( @@ -68,6 +69,7 @@ export const platformRoutes: Array = [ ...forumsRoutes, ...timelineWallRoutes, ...gigsRoutes, + ...statisticsRoutes, ...devCenterRoutes, ...campusRoutes, ...copilotsRoutes, diff --git a/src/apps/statistics/index.ts b/src/apps/statistics/index.ts new file mode 100644 index 000000000..6a173993d --- /dev/null +++ b/src/apps/statistics/index.ts @@ -0,0 +1 @@ +export { statisticsRoutes } from './src/statistics.routes' diff --git a/src/apps/statistics/src/ReportTable.tsx b/src/apps/statistics/src/ReportTable.tsx new file mode 100644 index 000000000..5a3857bf0 --- /dev/null +++ b/src/apps/statistics/src/ReportTable.tsx @@ -0,0 +1,125 @@ +import { ChangeEvent, FC, MouseEvent, useState } from 'react' +import useSWR from 'swr' + +import { EnvironmentConfig } from '~/config' + +import { Column, Report, ReportRow } from './reports' +import { fetchStatistics, formatValue, reportOptions } from './statistics.service' +import styles from './StatisticsPage.module.scss' + +interface Props { report: Report } +interface Sort { field: string; ascending: boolean } + +/** Sortable public report with bounded rendering, filtering, and retryable errors. */ +const ReportTable: FC = (props: Props) => { + const report = props.report + const result = useSWR(report.path, fetchStatistics, reportOptions) + const [sort, setSort] = useState() + const [search, setSearch] = useState('') + const [limit, setLimit] = useState(25) + const rows = (result.data || []).filter(row => report.columns.some(column => ( + String(row[column.field] ?? '') + .toLowerCase() + .includes(search.toLowerCase()) + ))) + if (sort) { + rows.sort((a: ReportRow, b: ReportRow) => { + const comparison = String(a[sort.field] ?? '') + .localeCompare(String(b[sort.field] ?? ''), 'en', { numeric: true }) + return sort.ascending ? comparison : -comparison + }) + } + + function retry(): void { result.mutate() } + function showMore(): void { setLimit(limit + 25) } + function filter(event: ChangeEvent): void { + setSearch(event.target.value) + setLimit(25) + } + + function sortColumn(event: MouseEvent): void { + const field = event.currentTarget.dataset.field || '' + setSort({ ascending: sort?.field === field ? !sort.ascending : false, field }) + } + + function sortDirection(column: Column): 'ascending' | 'descending' | 'none' { + return sort?.field === column.field ? (sort.ascending ? 'ascending' : 'descending') : 'none' + } + + const headingId = report.path.replace(/\//g, '-') + return ( +
+

{report.title}

+ {result.error && ( +
+ Statistics could not be loaded. + {' '} + +
+ )} + {!result.data && !result.error &&

Loading statistics…

} + {result.data && !result.error && ( + <> + + {!rows.length ? ( +

+ {result.data.length ? 'No matching results.' : 'No statistics available yet.'} +

+ ) : ( + <> +
+ + + + + {report.columns.map(column => ( + + ))} + + + + {rows.slice(0, limit) + .map(row => ( + + + {report.columns.map(column => ( + + ))} + + ))} + +
Rank + +
{row.rank ?? ((result.data || []).indexOf(row) + 1)} + {column.member && row[column.field] ? ( + + {formatValue(row[column.field], true)} + + ) : formatValue(row[column.field])} +
+
+
+ {`${Math.min(limit, rows.length)} of ${rows.length} results`} + {limit < rows.length && } +
+ + )} + + )} +
+ ) +} + +export default ReportTable diff --git a/src/apps/statistics/src/StatisticsPage.module.scss b/src/apps/statistics/src/StatisticsPage.module.scss new file mode 100644 index 000000000..895d3b53e --- /dev/null +++ b/src/apps/statistics/src/StatisticsPage.module.scss @@ -0,0 +1,14 @@ +.page { max-width: 1440px; margin: 0 auto; padding: 40px 32px 64px; color: #1e293b; } +.header { margin-bottom: 32px; h1 { font-size: 48px; margin: 8px 0 16px; } p { line-height: 1.6; } p:first-child { font-size: 12px; font-weight: 700; letter-spacing: 2px; } } +.totals { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 32px; } +.total { padding: 24px; background: #e9f7f1; border-radius: 12px; display: flex; flex-direction: column; gap: 12px; strong { font-size: 32px; } } +.nav { display: flex; gap: 8px; flex-wrap: wrap; border-bottom: 1px solid #ccd6db; margin-bottom: 28px; a { padding: 14px 20px; color: #334155; text-decoration: none; border-bottom: 3px solid transparent; } a[aria-current] { color: #0a6747; border-color: #0a6747; font-weight: 700; } } +.reports { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; align-items: start; } +.report { padding: 24px; border: 1px solid #d9e1e7; border-radius: 12px; background: white; h2 { font-size: 22px; margin: 0 0 20px; } button { cursor: pointer; } a { color: #086e53; text-decoration: underline; } } +.search { display: flex; flex-direction: column; gap: 8px; font-size: 13px; margin-bottom: 20px; input { padding: 10px 12px; border: 1px solid #8a98a6; border-radius: 6px; width: 100%; } } +.tableScroll { overflow: auto; max-height: 600px; table { width: 100%; border-collapse: collapse; font-size: 14px; } th, td { text-align: left; padding: 12px 10px; border-bottom: 1px solid #e5e7eb; } th { position: sticky; top: 0; background: #f1f5f9; font-weight: 700; white-space: nowrap; } th button { color: inherit; font: inherit; background: none; border: 0; padding: 0; text-align: left; } } +.pagination { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-top: 20px; font-size: 13px; button { padding: 8px 14px; } } +.note { margin-bottom: 24px; color: #526070; } +.page :focus-visible { outline: 3px solid #0a7859; outline-offset: 3px; } +@media (max-width: 900px) { .reports { grid-template-columns: 1fr; } .total strong { font-size: 24px; } } +@media (max-width: 600px) { .page { padding: 24px 16px; } .totals { grid-template-columns: 1fr; gap: 12px; } .total { padding: 16px; } .header h1 { font-size: 36px; } .report { padding: 16px; } .nav a { padding: 12px; } } diff --git a/src/apps/statistics/src/StatisticsPage.spec.tsx b/src/apps/statistics/src/StatisticsPage.spec.tsx new file mode 100644 index 000000000..9cd5b3169 --- /dev/null +++ b/src/apps/statistics/src/StatisticsPage.spec.tsx @@ -0,0 +1,122 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { MemoryRouter } from 'react-router-dom' +import { SWRConfig } from 'swr' + +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' + +import { fetchStatistics, formatValue } from './statistics.service' +import ReportTable from './ReportTable' +import StatisticsPage from './StatisticsPage' + +jest.mock('~/config', () => ({ + AppSubdomain: { statistics: 'statistics' }, + EnvironmentConfig: { + REPORTS_API: 'https://api.example.com/v6/reports', + SUBDOMAIN: 'www', + USER_PROFILE_URL: 'https://profiles.example.com', + }, +}), { virtual: true }) + +const report = { + columns: [{ field: 'handle', label: 'Member', member: true }, { field: 'count', label: 'Wins' }], + path: 'qa/wins', + title: 'First-place wins', +} + +function wrapper(props: { children: React.ReactNode }): JSX.Element { + return new Map() }}>{props.children} +} + +beforeEach(() => { global.fetch = jest.fn() }) + +it('loads public data, preserves zero, sorts numeric strings, filters and links handles safely', async () => { + (fetch as jest.Mock).mockResolvedValue({ + json: async () => [ + { count: '2', handle: '2', rank: 2 }, + { count: '10', handle: 'a/b', rank: 1 }, + { count: 0, handle: 'zero', rank: 3 }, + ], + ok: true, + }) + render(, { wrapper }) + expect(screen.getByRole('status').textContent) + .toContain('Loading') + await screen.findByRole('link', { name: 'a/b' }) + expect(fetch) + .toHaveBeenCalledWith('https://api.example.com/v6/reports/statistics/qa/wins') + expect(screen.getByRole('link', { name: 'a/b' }) + .getAttribute('href')) + .toBe('https://profiles.example.com/a%2Fb') + expect(screen.getByRole('link', { name: '2' }).textContent) + .toBe('2') + fireEvent.click(screen.getByRole('button', { name: 'Wins' })) + expect(within(screen.getAllByRole('row')[1]) + .getByRole('link').textContent) + .toBe('a/b') + fireEvent.click(screen.getByRole('button', { name: 'Wins' })) + expect(within(screen.getAllByRole('row')[1]) + .getByRole('link').textContent) + .toBe('zero') + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'zero' } }) + expect(screen.getAllByRole('row')) + .toHaveLength(2) + expect(screen.getByText('0')) + .toBeTruthy() + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'missing' } }) + expect(screen.getByRole('status').textContent) + .toBe('No matching results.') +}) + +it('recovers from an API failure and distinguishes an empty report', async () => { + (fetch as jest.Mock).mockResolvedValueOnce({ ok: false }) + .mockResolvedValueOnce({ json: async () => [], ok: true }) + render(, { wrapper }) + await screen.findByRole('alert') + fireEvent.click(screen.getByRole('button', { name: 'Retry' })) + await screen.findByText('No statistics available yet.') + expect(screen.queryByRole('alert')) + .toBeNull() +}) + +it('renders more than the initial page without losing report rows', async () => { + (fetch as jest.Mock).mockResolvedValue({ + json: async () => Array.from({ length: 30 }, (_, index) => ({ count: index, handle: `member${index}` })), + ok: true, + }) + render(, { wrapper }) + await screen.findByText('25 of 30 results') + expect(screen.getAllByRole('link')) + .toHaveLength(25) + fireEvent.click(screen.getByRole('button', { name: 'Show more' })) + expect(screen.getAllByRole('link')) + .toHaveLength(30) +}) + +it('opens a bookmarked category and only fetches its reports plus the summary', async () => { + (fetch as jest.Mock).mockResolvedValue({ json: async () => [], ok: true }) + render(, { wrapper }) + await waitFor(() => expect(fetch) + .toHaveBeenCalledTimes(4)) + expect(screen.getByRole('link', { name: 'QA' }) + .getAttribute('aria-current')) + .toBe('page') + expect(screen.getByRole('link', { name: 'Design' }) + .getAttribute('href')) + .toBe('/statistics/design') + expect(screen.getByRole('heading', { name: 'First-place wins' })) + .toBeTruthy() +}) + +it('normalizes singleton totals and rejects malformed reports', async () => { + (fetch as jest.Mock).mockResolvedValueOnce({ json: async () => ({ total: '0' }), ok: true }) + .mockResolvedValueOnce({ json: async () => 'not rows', ok: true }) + expect(await fetchStatistics('general/total-prizes')) + .toEqual([{ total: '0' }]) + await expect(fetchStatistics('general/total-prizes')).rejects.toThrow('unexpected response') + expect(formatValue(0)) + .toBe('0') + expect(formatValue('12345', true)) + .toBe('12345') + expect(formatValue('12345.67')) + .toBe('12,345.67') +}) diff --git a/src/apps/statistics/src/StatisticsPage.tsx b/src/apps/statistics/src/StatisticsPage.tsx new file mode 100644 index 000000000..56452bcfc --- /dev/null +++ b/src/apps/statistics/src/StatisticsPage.tsx @@ -0,0 +1,83 @@ +import { FC } from 'react' +import { Link, useLocation } from 'react-router-dom' +import useSWR from 'swr' + +import { AppSubdomain, EnvironmentConfig } from '~/config' + +import { sections } from './reports' +import { fetchStatistics, formatValue, reportOptions } from './statistics.service' +import ReportTable from './ReportTable' +import styles from './StatisticsPage.module.scss' + +const root = EnvironmentConfig.SUBDOMAIN === AppSubdomain.statistics ? '' : '/statistics' +interface TotalProps { field: string; label: string; path: string } +const totals: TotalProps[] = [ + { field: 'user.count', label: 'Community members', path: 'general/member-count' }, + { field: 'challenge.count', label: 'Completed challenges', path: 'general/completed-challenges' }, + { field: 'total', label: 'Total prizes paid', path: 'general/total-prizes' }, +] + +const Total: FC = (props: TotalProps) => { + const result = useSWR(props.path, fetchStatistics, reportOptions) + function retry(): void { result.mutate() } + return ( +
+ {props.label} + {result.error ? : ( + + {result.data + ? `${props.field === 'total' ? '$' : ''}${formatValue(result.data[0]?.[props.field])}` + : 'Loading…'} + + )} +
+ ) +} + +const StatisticsPage: FC = () => { + const location = useLocation() + const slug = location.pathname.replace(/^\/statistics(?=\/|$)/, '') + .replace(/^\/|\/$/g, '') + const section = sections.find(item => ( + item.id === (slug || 'general') || (slug === 'mm' && item.id === 'marathon-match') + )) + return ( +
+
+

THE TOPCODER COMMUNITY

+

Statistics

+

Explore the members, challenges, and achievements that shape our community.

+
+
{totals.map(total => )}
+ + {!section ? ( +

+ Statistics category not found. + {' '} + View general statistics +

+ ) : ( + <> + {(section.id === 'srm' || section.id === 'marathon-match') && ( +

These reports contain historical competition statistics.

+ )} +
+ {section.reports.map(report => )} +
+ + )} +
+ ) +} + +export default StatisticsPage diff --git a/src/apps/statistics/src/reports.ts b/src/apps/statistics/src/reports.ts new file mode 100644 index 000000000..675f790f9 --- /dev/null +++ b/src/apps/statistics/src/reports.ts @@ -0,0 +1,96 @@ +export type ReportRow = Record +export interface Column { field: string; label: string; member?: boolean } +export interface Report { path: string; title: string; columns: Column[] } +export interface StatisticsSection { id: string; title: string; reports: Report[] } + +const country: Column = { field: 'country.country_name', label: 'Country' } +const count: Column = { field: 'challenge_stats.count', label: 'Wins' } +const member = (field: string): Column => ({ field, label: 'Member', member: true }) +const winners = (path: string, title: string, field: string = 'challenge_stats.winner_handle'): Report => ({ + columns: [member(field), count], path, title, +}) +const countries = (track: string): Report => ({ + columns: [country, { field: 'user.count', label: 'Members' }], + path: `${track}/countries-represented`, + title: 'Countries represented', +}) +const firstSubmitters = (track: string): Report => ({ + columns: [member('user.handle'), { field: 'challenge.challenge_name', label: 'Challenge' }, + { field: 'newest_submitters.submit_date_date', label: 'Submitted' }], + path: `${track}/first-time-submitters`, + title: 'First-time submitters in the last three months', +}) +const placements = (type: string): Report => ({ + columns: [member('submitter.handle'), { field: 'challenge.count', label: 'Placements' }], + path: `design/${type}-placements`, + title: `${type.toUpperCase()} placements`, +}) +const rated = (track: string): Report[] => [ + { columns: [member('member_profile_basic.handle'), { field: 'member_stats.rating', label: 'Rating' }], + path: `${track}/top-rated`, + title: 'Highest rated members' }, + { columns: [member('member_profile_basic.handle'), { field: 'member_stats.competitions', label: 'Competitions' }], + path: `${track}/competitions-count`, + title: 'Number of competitions' }, + { columns: [country, { field: 'member_stats.rating', label: 'Rating' }], + path: `${track}/country-ratings`, + title: 'Country ratings' }, +] + +/** Public report contracts shared with the retired community statistics page. */ +export const sections: StatisticsSection[] = [ + { id: 'general', + reports: [ + countries('general'), + { columns: [country, count], path: 'general/first-place-by-country', title: 'First-place wins by country' }, + { columns: [member('copilot.handle'), { field: 'challenge.count', label: 'Challenges' }], + path: 'general/copiloted-challenges', + title: 'Copiloted challenges' }, + { columns: [member('reviewer.handle'), { field: 'challenge.count', label: 'Reviews' }], + path: 'general/reviews-by-member', + title: 'Reviews by member' }, + ], + title: 'General' }, + { id: 'development', + reports: [ + winners('development/first-place-wins', 'First-place wins', 'challenge_stats.registrant_handle'), + winners('development/prototype-wins', 'Prototype wins'), + winners('development/code-wins', 'Code wins'), + winners('development/f2f-wins', 'First2Finish wins'), + countries('development'), firstSubmitters('development'), + { columns: [{ field: 'challenge_technology.name', label: 'Technology' }, + { field: 'challenge_stats.count', label: 'Challenges' }], + path: 'development/challenges-technology', + title: 'Challenges by technology' }, + ], + title: 'Development' }, + { id: 'design', + reports: [ + winners('design/first-place-by-country', 'First-place wins', 'challenge_stats.registrant_handle'), + winners('design/ui-design-wins', 'UI design wins'), + winners('design/wireframe-wins', 'Wireframe wins'), + winners('design/f2f-wins', 'First2Finish wins'), + winners('design/lux-first-place-wins', 'LUX first-place wins'), placements('lux'), + winners('design/rux-first-place-wins', 'RUX first-place wins'), placements('rux'), + countries('design'), firstSubmitters('design'), + ], + title: 'Design' }, + { id: 'qa', + reports: [ + { columns: [member('challenge_stats.registrant_handle'), + { field: 'first_place_winner_count', label: 'Wins' }], + path: 'qa/wins', + title: 'First-place wins' }, + ], + title: 'QA' }, + { id: 'srm', reports: rated('srm'), title: 'SRM' }, + { id: 'marathon-match', + reports: [ + ...rated('mm'), + { columns: [member('member_profile_basic.handle'), + { field: 'member_stats.top_ten_finishes', label: 'Finishes' }], + path: 'mm/top-10-finishes', + title: 'Top 10 finishes' }, + ], + title: 'Marathon Match' }, +] diff --git a/src/apps/statistics/src/statistics.routes.spec.tsx b/src/apps/statistics/src/statistics.routes.spec.tsx new file mode 100644 index 000000000..22cd56b25 --- /dev/null +++ b/src/apps/statistics/src/statistics.routes.spec.tsx @@ -0,0 +1,34 @@ +import { AppSubdomain, ToolTitle } from '~/config' + +jest.mock('~/config', () => ({ + AppSubdomain: { statistics: 'statistics' }, + EnvironmentConfig: { SUBDOMAIN: 'www' }, + ToolTitle: { statistics: 'Statistics' }, +}), { virtual: true }) +jest.mock('~/libs/core', () => ({ + getRoutesContainer: () =>
, + lazyLoad: () => () =>
, +}), { virtual: true }) +jest.mock('react-router-dom', () => ({ Navigate: () =>
, useLocation: () => ({}) })) + +it.each(['www', 'topcoder-dev', 'topcoder', 'statistics', 'localhost'])('registers public routes for %s', host => { + jest.resetModules() + jest.doMock('~/config', () => ({ + AppSubdomain, + EnvironmentConfig: { SUBDOMAIN: host }, + ToolTitle, + }), { virtual: true }) + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + const routes = require('./statistics.routes').statisticsRoutes + + expect(routes[0].route) + .toBe(host === 'statistics' ? '' : '/statistics') + expect(routes[0].domain) + .toBe('statistics') + expect(routes[0].authRequired) + .toBeUndefined() + expect(routes[0].children[0].route) + .toBe('*') + expect(routes[1].route) + .toBe('/community/statistics/*') +}) diff --git a/src/apps/statistics/src/statistics.routes.tsx b/src/apps/statistics/src/statistics.routes.tsx new file mode 100644 index 000000000..ca7b82818 --- /dev/null +++ b/src/apps/statistics/src/statistics.routes.tsx @@ -0,0 +1,32 @@ +import { FC } from 'react' +import { Navigate, useLocation } from 'react-router-dom' + +import { AppSubdomain, EnvironmentConfig, ToolTitle } from '~/config' +import { getRoutesContainer, lazyLoad, LazyLoadedComponent, PlatformRoute } from '~/libs/core' + +const StatisticsPage: LazyLoadedComponent = lazyLoad(() => import('./StatisticsPage')) +export const statisticsRoot = EnvironmentConfig.SUBDOMAIN === AppSubdomain.statistics ? '' : '/statistics' + +const LegacyStatisticsRedirect: FC = () => { + const location = useLocation() + const path = location.pathname.replace(/^\/community\/statistics/, '/statistics') + return +} + +const children: PlatformRoute[] = [{ element: , id: 'Statistics page', route: '*' }] + +export const statisticsRoutes: ReadonlyArray = [ + { + children, + domain: AppSubdomain.statistics, + element: getRoutesContainer(children), + id: ToolTitle.statistics, + route: statisticsRoot, + title: ToolTitle.statistics, + }, + { + element: , + id: 'Legacy statistics', + route: '/community/statistics/*', + }, +] diff --git a/src/apps/statistics/src/statistics.service.ts b/src/apps/statistics/src/statistics.service.ts new file mode 100644 index 000000000..21f9fec71 --- /dev/null +++ b/src/apps/statistics/src/statistics.service.ts @@ -0,0 +1,29 @@ +import { EnvironmentConfig } from '~/config' + +import { ReportRow } from './reports' + +/** Read public reports without requiring a member session. */ +export async function fetchStatistics(path: string): Promise { + const response = await fetch(`${EnvironmentConfig.REPORTS_API}/statistics/${path}`) + if (!response.ok) throw new Error('Statistics could not be loaded. Please try again.') + const data: unknown = await response.json() + const rows = Array.isArray(data) ? data : [data] + if (!rows.every(row => row !== null && typeof row === 'object' && !Array.isArray(row))) { + throw new Error('The statistics report returned an unexpected response.') + } + + return rows as ReportRow[] +} + +/** Format zero and numeric strings without changing member handles or dates. */ +export function formatValue(value: string | number | null | undefined, isMember: boolean = false): string { + if (value === null || value === undefined) return '—' + if (!isMember && /^-?\d+(\.\d+)?$/.test(String(value))) { + return Number(value) + .toLocaleString('en-US', { maximumFractionDigits: 2 }) + } + + return String(value) +} + +export const reportOptions = { revalidateOnFocus: false, shouldRetryOnError: false } diff --git a/src/config/constants.ts b/src/config/constants.ts index 0c74a02ff..837b7235d 100644 --- a/src/config/constants.ts +++ b/src/config/constants.ts @@ -1,4 +1,5 @@ export enum AppSubdomain { + statistics = 'statistics', accounts = 'account-settings', analytics = 'analytics', contact = 'contact', @@ -30,6 +31,7 @@ export enum AppSubdomain { } export enum ToolTitle { + statistics = 'Statistics', accounts = 'Account Settings', analytics = 'Analytics', contact = 'Contact',