feat(financials-v2): add financial statements endpoint and query plumbing
This commit is contained in:
@@ -1,9 +1,19 @@
|
||||
import { Elysia, t } from 'elysia';
|
||||
import type { Filing, TaskStatus } from '@/lib/types';
|
||||
import type {
|
||||
Filing,
|
||||
FinancialHistoryWindow,
|
||||
FinancialStatementKind,
|
||||
FinancialStatementMode,
|
||||
TaskStatus
|
||||
} from '@/lib/types';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { buildPortfolioSummary } from '@/lib/server/portfolio';
|
||||
import {
|
||||
defaultFinancialSyncLimit,
|
||||
getCompanyFinancialStatements
|
||||
} from '@/lib/server/financial-statements';
|
||||
import { redactInternalFilingAnalysisFields } from '@/lib/server/api/filing-redaction';
|
||||
import { getFilingByAccession, listFilingsRecords } from '@/lib/server/repos/filings';
|
||||
import {
|
||||
@@ -29,6 +39,16 @@ import {
|
||||
const ALLOWED_STATUSES: TaskStatus[] = ['queued', 'running', 'completed', 'failed'];
|
||||
const FINANCIAL_FORMS: ReadonlySet<Filing['filing_type']> = new Set(['10-K', '10-Q']);
|
||||
const AUTO_FILING_SYNC_LIMIT = 20;
|
||||
const FINANCIALS_V2_ENABLED = process.env.FINANCIALS_V2?.trim().toLowerCase() !== 'false';
|
||||
const FINANCIAL_STATEMENT_MODES: FinancialStatementMode[] = ['standardized', 'filing_faithful'];
|
||||
const FINANCIAL_STATEMENT_KINDS: FinancialStatementKind[] = [
|
||||
'income',
|
||||
'balance',
|
||||
'cash_flow',
|
||||
'equity',
|
||||
'comprehensive_income'
|
||||
];
|
||||
const FINANCIAL_HISTORY_WINDOWS: FinancialHistoryWindow[] = ['10y', 'all'];
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
@@ -43,6 +63,43 @@ function asPositiveNumber(value: unknown) {
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function asBoolean(value: unknown, fallback = false) {
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (normalized === 'true' || normalized === '1' || normalized === 'yes') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized === 'false' || normalized === '0' || normalized === 'no') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function asStatementMode(value: unknown): FinancialStatementMode {
|
||||
return FINANCIAL_STATEMENT_MODES.includes(value as FinancialStatementMode)
|
||||
? value as FinancialStatementMode
|
||||
: 'standardized';
|
||||
}
|
||||
|
||||
function asStatementKind(value: unknown): FinancialStatementKind {
|
||||
return FINANCIAL_STATEMENT_KINDS.includes(value as FinancialStatementKind)
|
||||
? value as FinancialStatementKind
|
||||
: 'income';
|
||||
}
|
||||
|
||||
function asHistoryWindow(value: unknown): FinancialHistoryWindow {
|
||||
return FINANCIAL_HISTORY_WINDOWS.includes(value as FinancialHistoryWindow)
|
||||
? value as FinancialHistoryWindow
|
||||
: '10y';
|
||||
}
|
||||
|
||||
function withFinancialMetricsPolicy(filing: Filing): Filing {
|
||||
if (FINANCIAL_FORMS.has(filing.filing_type)) {
|
||||
return filing;
|
||||
@@ -430,6 +487,98 @@ export const app = new Elysia({ prefix: '/api' })
|
||||
ticker: t.String({ minLength: 1 })
|
||||
})
|
||||
})
|
||||
.get('/financials/company', async ({ query }) => {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
if (!FINANCIALS_V2_ENABLED) {
|
||||
return jsonError('Financial statements v2 is disabled', 404);
|
||||
}
|
||||
|
||||
const ticker = typeof query.ticker === 'string'
|
||||
? query.ticker.trim().toUpperCase()
|
||||
: '';
|
||||
if (!ticker) {
|
||||
return jsonError('ticker is required');
|
||||
}
|
||||
|
||||
const mode = asStatementMode(query.mode);
|
||||
const statement = asStatementKind(query.statement);
|
||||
const window = asHistoryWindow(query.window);
|
||||
const includeDimensions = asBoolean(query.includeDimensions, false);
|
||||
const cursor = typeof query.cursor === 'string' && query.cursor.trim().length > 0
|
||||
? query.cursor.trim()
|
||||
: null;
|
||||
const limit = Number.isFinite(Number(query.limit))
|
||||
? Number(query.limit)
|
||||
: undefined;
|
||||
|
||||
let payload = await getCompanyFinancialStatements({
|
||||
ticker,
|
||||
mode,
|
||||
statement,
|
||||
window,
|
||||
includeDimensions,
|
||||
cursor,
|
||||
limit,
|
||||
v2Enabled: FINANCIALS_V2_ENABLED,
|
||||
queuedSync: false
|
||||
});
|
||||
|
||||
let queuedSync = false;
|
||||
const shouldQueueSync = cursor === null && (
|
||||
payload.dataSourceStatus.pendingFilings > 0
|
||||
|| payload.coverage.filings === 0
|
||||
|| (window === 'all' && payload.nextCursor !== null)
|
||||
);
|
||||
|
||||
if (shouldQueueSync) {
|
||||
try {
|
||||
await enqueueTask({
|
||||
userId: session.user.id,
|
||||
taskType: 'sync_filings',
|
||||
payload: {
|
||||
ticker,
|
||||
limit: defaultFinancialSyncLimit(window)
|
||||
},
|
||||
priority: 88
|
||||
});
|
||||
queuedSync = true;
|
||||
} catch (error) {
|
||||
console.error(`[financials-v2-sync] failed for ${ticker}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (queuedSync) {
|
||||
payload = {
|
||||
...payload,
|
||||
dataSourceStatus: {
|
||||
...payload.dataSourceStatus,
|
||||
queuedSync: true
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return Response.json({ financials: payload });
|
||||
}, {
|
||||
query: t.Object({
|
||||
ticker: t.String({ minLength: 1 }),
|
||||
mode: t.Optional(t.Union([t.Literal('standardized'), t.Literal('filing_faithful')])),
|
||||
statement: t.Optional(t.Union([
|
||||
t.Literal('income'),
|
||||
t.Literal('balance'),
|
||||
t.Literal('cash_flow'),
|
||||
t.Literal('equity'),
|
||||
t.Literal('comprehensive_income')
|
||||
])),
|
||||
window: t.Optional(t.Union([t.Literal('10y'), t.Literal('all')])),
|
||||
includeDimensions: t.Optional(t.Union([t.String(), t.Boolean()])),
|
||||
cursor: t.Optional(t.String()),
|
||||
limit: t.Optional(t.Numeric())
|
||||
})
|
||||
})
|
||||
.get('/analysis/reports/:accessionNumber', async ({ params }) => {
|
||||
const { response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
|
||||
Reference in New Issue
Block a user