mirror of https://github.com/ghostfolio/ghostfolio
4 changed files with 434 additions and 0 deletions
@ -0,0 +1,13 @@ |
|||||
|
# Upstream broker import assessment |
||||
|
|
||||
|
Base: official `ghostfolio/ghostfolio` main at `23312d192`. The NG integration worktree and its commits remain untouched. No root CONTRIBUTING.md, PR template or governing AGENTS.md exists in this checkout; DEVELOPMENT.md and the existing NestJS import/validation/security patterns were reviewed. |
||||
|
|
||||
|
The existing `/import` endpoint accepts Ghostfolio accounts, activities, profiles, tags and platforms and offers `dryRun`. Activity creation uses `Order` with BUY, SELL, DIVIDEND, FEE, INTEREST and LIABILITY. Commission is `fee`; **there is no tax field, deposit/withdrawal activity or NG cash ledger**. Account balances are separate checkpoints. The existing importer validates before writes but does not provide an atomic broker provenance transaction. Its heuristic duplicate matching cannot replace stable account-scoped broker identities. |
||||
|
|
||||
|
Reuse the NG Directa parser, anonymous fixtures and strict compatible-cost rules. Reuse only small listing-proof helpers and the existing Yahoo provider for discovery/quotes, without importing the NG ETF-enrichment system. Add a generic broker registry, planner, preview digest and a dedicated atomic writer, preserving future-dated activity tagging and portfolio invalidation. New broker parsers will implement the adapter contract rather than edit persistence. |
||||
|
|
||||
|
An additive broker provenance table is justified for overlapping-file deduplication, corrected sources and edited/deleted output detection. It will store hashes, source dates and references to activities, never the raw statement, account name or transaction references. It is not a cash ledger. Account deletion removes provenance; activity deletion retains a tombstone so reimport cannot silently recreate it. Generic Ghostfolio JSON backups do not carry this table, a documented cross-installation limitation. |
||||
|
|
||||
|
Supported scope: tax-free BUY/SELL with reliably attached trading commissions, and dividends without withholding. Taxes are not fees: any group with withholding is blocked as a complete group. Deposits, withdrawals, stamp duties and standalone taxes are explicitly unsupported. A partial import requires explicit whole-group exclusions and separate acknowledgement. It will not update account balances or claim a complete cash reconciliation. |
||||
|
|
||||
|
Open PR searches for Directa and import adapters found no matching active implementation. The broad broker-import search found #8462 (numeric-symbol validation), which this work does not duplicate. Related issues #4139 (listing/source currency) and #7728 (account-scoped duplicates) inform currency and identity safeguards. Related discussion [#6004](https://github.com/ghostfolio/ghostfolio/discussions/6004) requests an extensible native CSV importer; [#6714](https://github.com/ghostfolio/ghostfolio/discussions/6714) discusses broker plugins. This implementation offers an initial adapter contract, not a runtime plugin loader. NG's successful 356-row qualification is prior art, not proof that this upstream implementation passes; validation will run separately against upstream's schema and model. |
||||
@ -0,0 +1,70 @@ |
|||||
|
# Upstream Directa import validation |
||||
|
|
||||
|
Validated locally on the dedicated `feat/broker-import-directa` worktree, based on official main `23312d192`. The NG integration branch is preserved. Its earlier success is not counted as upstream validation. |
||||
|
|
||||
|
## Real source qualification |
||||
|
|
||||
|
Two private samples were evaluated separately. The currently supplied CSV has 239 movements after the owner intentionally removed rows for a reimport test. The original XLSX retains 356 movements; those twelve source columns were normalized to a private temporary CSV solely for the adapter qualification. No source amounts were rounded or adjusted. This does not add an XLSX upload feature. |
||||
|
|
||||
|
Both runs used the actual upstream-adapted parser, planner, verified listing resolver, Yahoo quote service, upstream data-provider validation method, Prisma transaction and PostgreSQL schema. The qualification harness supplies direct transport and free-Yahoo configuration, without seed mappings or mocked market responses. Production provider configuration and activity limits are separately exercised by the application and tests. Tests run against disposable `broker_test_directa` PostgreSQL on a separate local port and an isolated temporary Redis instance for application-module checks. |
||||
|
|
||||
|
| Check | Reduced CSV | Complete source | |
||||
|
| -------------------------------------------------------- | ----------: | --------------: | |
||||
|
| Source movements recognized | 239 | 356 | |
||||
|
| Distinct instruments automatically resolved | 6 | 7 | |
||||
|
| Verified instrument choices requiring confirmation | 2 | 4 | |
||||
|
| Instruments lacking reliable evidence after confirmation | 0 | 0 | |
||||
|
| Activities persisted | 88 | 136 | |
||||
|
| Whole unsupported groups explicitly excluded | 111 | 162 | |
||||
|
| Source provenance records persisted | 111 | 166 | |
||||
|
| Reimported rows recognized as duplicates | 111 | 166 | |
||||
|
|
||||
|
Confirmation choices are explicitly simulated by the qualification harness selecting the sole verified EUR candidate on Borsa Italiana. They are **not automatic resolutions or actual end-user GUI confirmations**. The fresh-catalog complete run does not rely on an existing portfolio mapping. Additional valid alternatives remain available in the preview. |
||||
|
|
||||
|
The complete-source import persists the tax-free BUY/SELL activity groups. All 24 dividend-withholding relationships can be identified, but their complete dividend groups remain unsupported upstream. Two taxed sale groups, standalone taxes, cash transfers and stamp duties are also excluded explicitly. The 162 excluded groups contain 190 source rows. No unsupported tax is converted to a fee and no gross amount or balancing entry is invented. These results do **not** claim NG's 162 activities/298 cash movements/356 provenance parity. |
||||
|
|
||||
|
Source amount coverage balances after attribution to imported and explicitly omitted movements; there is no upstream cash-ledger reconciliation or cash update. A synthetic existing balance checkpoint remains unchanged. Preview writes no profiles, activities, provenance, account settings or balances. A failure injected on the final provenance write rolls back the entire batch, including newly created profiles. A subsequent confirmed import succeeds, and reimport writes nothing. |
||||
|
|
||||
|
### Overlapping real files |
||||
|
|
||||
|
The reduced CSV was also imported first, followed by the complete source **in the same disposable account**. The second preview recognizes 111 source rows already imported and adds only 48 activities, resulting in 136 activities total. Reimport of the complete file recognizes all 166 supported source rows and adds none. The excluded movements remain explicitly omitted rather than being falsely marked imported. |
||||
|
|
||||
|
Original financial files, source-account identifiers, personal names, transaction references and portfolio-specific ISIN mappings are absent from this repository. The private temporary CSV is not committed. Only anonymous fixtures are versioned. |
||||
|
|
||||
|
## Automated checks |
||||
|
|
||||
|
The relevant backend regression assertions passed: **10 suites, 120 tests and the route-security snapshot**. They cover parsing, decimal/date/header validation, symbol proof and alternatives, provider failures, cost families, unsupported accounting, explicit partial consent, preview purity, atomic rollback, corrected/deleted output, repeated references, overlapping imports, concurrent confirmations, late costs, ownership and configured limits, plus existing Ghostfolio import regressions. The final run used the repository Nx test runner and exited successfully. The original upstream application-module test remains unchanged; its route-security snapshot adds only the two authenticated broker endpoints. A direct Jest CLI invocation retained a cache connection after assertions, so that invocation is not used as process-exit evidence. |
||||
|
|
||||
|
All **9 client tests** pass, covering final confirmation, partial consent, bulk exclusions, invalidation, restricted error display, UTF-8 input, real Material-dialog rendering and all new message targets. There are 74 source messages with translations in every one of the 13 supported non-English locales; all 14 XLF catalogs are XML-validated. API and client TypeScript checks pass. Final checks passed: |
||||
|
|
||||
|
| Check | Result | |
||||
|
| ------------------------------------------------------------------- | ---------------------------------------------------------- | |
||||
|
| API regression suite | 10 suites, 120 tests, 1 security snapshot; successful exit | |
||||
|
| PostgreSQL integration in Europe/Rome | 12 tests passed | |
||||
|
| Client dialog | 9 tests passed | |
||||
|
| API and client TypeScript | Passed | |
||||
|
| Affected quiet lint | All 4 projects passed | |
||||
|
| Formatting / whitespace | Passed | |
||||
|
| English and Italian frontend builds | Passed sequentially | |
||||
|
| Prisma schema drift against the migrated disposable database | No difference | |
||||
|
| Fresh complete-source qualification and reduced-to-complete overlap | Passed again after final implementation changes | |
||||
|
|
||||
|
Git hooks remain enabled and run on each commit. Existing Sass deprecation warnings are outside this change. Counts overlap across suites and are not additive coverage. |
||||
|
|
||||
|
No manual browser acceptance, full repository-wide test run, hosted CI result or performance SLA is claimed. Provider availability and public listing tables can change. The PR is proposed as a draft for review of scope, accounting exclusions and generic provenance design. |
||||
|
|
||||
|
## Reproduce |
||||
|
|
||||
|
Use the documented Node version and `npm ci`, then migrate only a disposable local database named `broker_test_*`. Set `DATABASE_URL`/`DIRECT_URL` for Prisma, and `BROKER_TEST_DATABASE_URL` for the integration suite. Load `.env.example` for configuration-dependent tests and use a temporary Redis host/port; never point integration checks at production. |
||||
|
|
||||
|
```sh |
||||
|
NODE_OPTIONS='--max-old-space-size=3072 -r dotenv/config' \ |
||||
|
DOTENV_CONFIG_PATH=.env.example npx nx test api --runInBand \ |
||||
|
--testFile=broker-import.integration.spec.ts --skip-nx-cache |
||||
|
``` |
||||
|
|
||||
|
`tools/qualify-broker-import.ts` is an opt-in private-source check. Set `BROKER_TEST_CSV_PATH`, `BROKER_TEST_REPORT_PATH` (outside the repository) and the disposable database URL, then bundle it with esbuild using `apps/api/tsconfig.app.json`. Set `NODE_PATH` to this worktree's `node_modules` when running an output bundle in `/tmp`. Default behavior is read-only preview. `BROKER_TEST_PARTIAL=true` explicitly enables test exclusions, partial consent, injected rollback, persistence and reimport; `BROKER_TEST_CONFIRM_MARKET='Borsa Italiana'` simulates the qualified market choices. `BROKER_TEST_OVERLAP_CSV_PATH` optionally exercises the subsequent complete-file import. The runner removes its own test user and newly created profiles. |
||||
|
|
||||
|
## Migration and remaining limits |
||||
|
|
||||
|
The single additive migration creates generic `BrokerImportRecord`; all upstream migrations were applied successfully to the temporary PostgreSQL database. No existing data is rewritten and no NG migrations or cash services are included. Activity deletion retains a provenance tombstone; account deletion removes its records. Standard JSON export/restore does not transport this provenance across installations, so restored similar activities require manual review. EUR monetary legs and the documented twelve-column layout are the supported initial scope. Taxes and transfers require separate upstream accounting work. |
||||
@ -0,0 +1,66 @@ |
|||||
|
# Broker CSV imports: Directa |
||||
|
|
||||
|
The activities toolbar keeps the existing **Import Activities** action. The adjacent source menu offers **Import from Ghostfolio** (the existing JSON/CSV workflow) and **Import from Directa**. Existing export and dividend-import menu actions are preserved. |
||||
|
|
||||
|
## Supported source format |
||||
|
|
||||
|
Use the UTF-8 **Movimenti** export from Directa, with semicolon delimiters, optional BOM, source-account metadata and the original twelve columns: |
||||
|
|
||||
|
``` |
||||
|
Data operazione;Data valuta;Tipo operazione;Ticker;Isin;Protocollo;Descrizione;Quantità;Importo euro;Importo Divisa;Divisa;Riferimento ordine |
||||
|
``` |
||||
|
|
||||
|
Italian decimal commas and grouping separators are normalized with decimal arithmetic. Operation and settlement dates remain distinct. Incompatible layouts, malformed numbers, missing identities and ambiguous multiple executions are rejected. Current limits are 2 MB and 5,000 source rows. XLSX is not a supported upload format. This adapter deliberately does not guess column layouts of other historical exports. |
||||
|
|
||||
|
## Accounting mapping |
||||
|
|
||||
|
This implementation targets **upstream Ghostfolio**, without Ghostfolio-NG Cash Management or its tax field. |
||||
|
|
||||
|
| Directa movement | Behavior | |
||||
|
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
||||
|
| BUY / SELL without associated tax | Creates the corresponding upstream activity at gross consideration and reported quantity. | |
||||
|
| Uniquely attributable trading commission | Attached once as the activity fee; no duplicate FEE activity. Otherwise requires a compatible target selection. | |
||||
|
| Dividend without withholding | DIVIDEND at gross income, using one income unit because the source lacks a share quantity; preview warns explicitly. | |
||||
|
| Dividend withholding | Relationship is evaluated using identity, income family, operation and settlement dates, currency, signs and amount bounds. The entire taxed dividend group is unsupported because upstream lacks tax representation. | |
||||
|
| ETF-sale withholding / attributable transaction tax | Entire associated trade group unsupported, including its commissions. | |
||||
|
| Capital-gains withholding, standalone Tobin tax, stamp duty | Unsupported; never converted into trading fees. | |
||||
|
| Deposits / withdrawals | Unsupported; no artificial activities or cash ledger is introduced. | |
||||
|
| Orphan / ambiguous costs | Blocked with candidate selection where reliable eligibility exists; potentially affected activities cannot bypass an unassociated cost. | |
||||
|
| Corrections, unsupported currency legs, edited previous output | Blocked; no silent financial overwrite. | |
||||
|
|
||||
|
Only EUR source amounts with no separate foreign monetary leg are supported. A verified listing in another currency requires explicit selection; the existing upstream `Order.currency` field retains the original EUR activity amounts, and upstream handles valuation conversion. No FX cash movement or rate is invented. The destination account already exists and belongs to the caller. Its balance checkpoints, currency and preferences are never changed. Activity currency follows the verified profile as in upstream's activity creation model. Future activities use upstream's draft-tag helper. |
||||
|
|
||||
|
## Preview and partial import |
||||
|
|
||||
|
1. Select the CSV and an existing destination account. |
||||
|
2. Explicitly accept activity booking on the operation date; retain settlement dates for source inspection. |
||||
|
3. Review verified instrument alternatives and any compatible cost choices. |
||||
|
4. Review every unsupported group. Exclude complete groups using their inclusion checkbox or **Exclude unsupported groups**. All groups remain visible for review; attached costs are excluded with their activity. |
||||
|
5. Separately confirm that the import is partial when anything is excluded. |
||||
|
6. Review source amount coverage and give the final import confirmation. |
||||
|
|
||||
|
The preview refreshes after choices and exclusions and invalidates confirmation. **Source amount coverage is not a cash ledger or portfolio cash reconciliation**: it separates amounts attributed to importable, duplicate, excluded and unresolved groups. Amounts are totaled once per stable source reference; identical repeated rows are reported as duplicates. A zero difference never overrides blocked/unsupported rows. Exclusions are neither written nor marked imported, and no balancing entries are created. A later file can make a previously omitted group importable, but cannot modify an existing imported activity to add a late cost. |
||||
|
|
||||
|
Unsupported withholding cannot be excluded separately to import its gross dividend. Ambiguous unattached costs keep plausible target activities blocked until the association is resolved or all affected groups are explicitly excluded. The importer never alters gross transaction amounts to hide tax. |
||||
|
|
||||
|
## Instrument resolution |
||||
|
|
||||
|
Existing profiles and Yahoo search provide candidate hints, not sufficient identity proof. Exact labeled ISIN/ticker fields from Borsa Italiana, canonical-ISIN justETF listing tables, or OpenFIGI ISIN/MIC/currency mapping establish listing identity. Existing Yahoo quote services verify ticker, exchange and currency. The `.MI` suffix is formed only after an actual ticker is published by the Italian exchange. No portfolio-specific instrument mapping is included. |
||||
|
|
||||
|
A unique verified candidate consistent with the broker ticker and source currency is automatic. Genuine alternative listings require explicit selection. Provider failures, catalog conflicts and insufficient identity proof remain blocked. The known market registry intentionally limits coverage instead of guessing unsupported exchanges. Public evidence is cached for five minutes with a bounded cache, two instrument workers, at most 24 candidates and eight-second per-request abort signals. Original provider bytes are required; optional AI web-fetch substitutions cannot establish identity. Only instrument identifiers are sent to providers, never the source account, raw file or transaction references. |
||||
|
|
||||
|
## Modular design and persistence |
||||
|
|
||||
|
`BrokerAdapter` owns recognition, validation, parsing, normalization, source identity and broker-specific income classification. A registry in `BrokerImportService` selects the adapter. The shared planner handles accounts, verified instruments, compatible costs, whole-group exclusions, upstream provider validation, configured activity limits, preview digests and persistence. Add a normalized adapter and register its format/source-menu entry to support another broker; do not add broker-specific branches to the writer. |
||||
|
|
||||
|
A single serializable PostgreSQL transaction locks the destination account and writes profiles, activities and `BrokerImportRecord` together. Preview writes none of these. Provider work occurs before financial locks. The digest binds source, choices, exclusions, activity limit, account state, existing output/provenance and selected listing evidence. Stale or competing commits require a new preview. Portfolio and asset-profile events and historical-data jobs run only after commit, following upstream conventions. |
||||
|
|
||||
|
The additive provenance table is generic, account/user scoped and contains hashed source-account/protocol identity, normalized-content fingerprint, hashed order identity, operation/settlement dates, operation kind and output references. It stores no original file, source-account name, raw description or transaction references. Output fingerprints bind financial fields and effective listing identity/currency. Repeated files, overlapping periods and repeated identical references are idempotent. Modified references, deleted/edited output, changed identity formats and similar legacy activities without provenance require manual reconciliation. Distinct source protocols remain distinct even for identical trades. |
||||
|
|
||||
|
Account deletion cascades provenance. Activity deletion sets `orderId` to null, retaining a tombstone that blocks silent recreation. No backfill or data rewrite accompanies the migration. Generic Ghostfolio JSON export/restore remains unchanged and **does not preserve broker provenance across installations**. After restore, comparable legacy activities are blocked for manual review instead of being silently adopted or duplicated. There is no automated provenance reset endpoint. |
||||
|
|
||||
|
## Verification and scope |
||||
|
|
||||
|
See [the upstream audit](broker-import-audit.md) and [validation report](broker-import-validation.md). The original NG qualification is prior art, not upstream test evidence. Synthetic fixtures reproduce parsing, withholding, ambiguous/late costs and duplicate cases without exposing financial exports. Opt-in PostgreSQL tests require `BROKER_TEST_DATABASE_URL` pointing at a disposable local `broker_test_` database. Run Jest with `--runInBand`; run builds and other memory-intensive checks sequentially on an 8 GB machine. |
||||
|
|
||||
|
A future broker can reuse this engine. Tax-aware upstream activity modeling, additional markets/providers, alternative historical layouts and provenance-aware backup portability are separate follow-up topics. This PR does not introduce those subsystems or claim NG accounting parity. |
||||
@ -0,0 +1,285 @@ |
|||||
|
/** Opt-in private-file qualification. Reports contain aggregates, never source account data or references. */ |
||||
|
import { YahooFinanceDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/yahoo-finance/yahoo-finance.service'; |
||||
|
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; |
||||
|
import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service'; |
||||
|
import { BrokerImportService } from '@ghostfolio/api/services/import/broker/broker-import.service'; |
||||
|
import { BrokerInstrumentResolver } from '@ghostfolio/api/services/import/broker/broker-instrument-resolver.service'; |
||||
|
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
||||
|
import { getAssetProfileIdentifier } from '@ghostfolio/common/helper'; |
||||
|
import { BrokerImportInput } from '@ghostfolio/common/interfaces/broker-import.interface'; |
||||
|
import { UserWithSettings } from '@ghostfolio/common/types'; |
||||
|
|
||||
|
import { ConfigService } from '@nestjs/config'; |
||||
|
import { EventEmitter2 } from '@nestjs/event-emitter'; |
||||
|
import { randomUUID } from 'node:crypto'; |
||||
|
import { readFile, writeFile } from 'node:fs/promises'; |
||||
|
|
||||
|
async function main() { |
||||
|
const url = process.env.BROKER_TEST_DATABASE_URL, |
||||
|
path = process.env.BROKER_TEST_CSV_PATH, |
||||
|
reportPath = process.env.BROKER_TEST_REPORT_PATH; |
||||
|
if ( |
||||
|
!url || |
||||
|
new URL(url).hostname !== '127.0.0.1' || |
||||
|
!new URL(url).pathname.startsWith('/broker_test_') || |
||||
|
!path || |
||||
|
!reportPath |
||||
|
) |
||||
|
throw Error('DISPOSABLE_DATABASE_AND_PRIVATE_INPUT_REQUIRED'); |
||||
|
const prisma = new PrismaService( |
||||
|
new ConfigService({ DATABASE_URL: url, LOG_LEVELS: '[]' }) |
||||
|
); |
||||
|
await prisma.$connect(); |
||||
|
const userId = randomUUID(), |
||||
|
newProfiles: string[] = []; |
||||
|
try { |
||||
|
const initial = new Set( |
||||
|
(await prisma.symbolProfile.findMany({ select: { id: true } })).map( |
||||
|
(profile) => profile.id |
||||
|
) |
||||
|
); |
||||
|
await prisma.user.create({ data: { id: userId } }); |
||||
|
const account = await prisma.account.create({ |
||||
|
data: { |
||||
|
userId, |
||||
|
currency: 'EUR', |
||||
|
name: 'Disposable broker qualification', |
||||
|
balances: { create: { date: new Date('2020-01-01'), value: 123 } } |
||||
|
} |
||||
|
}); |
||||
|
const crypto = { isCryptocurrency: () => false }, |
||||
|
yahoo = new YahooFinanceService( |
||||
|
crypto as never, |
||||
|
new YahooFinanceDataEnhancerService(crypto as never) |
||||
|
); |
||||
|
const providers = { |
||||
|
getDataProvider: () => yahoo, |
||||
|
validateActivities: async (params) => |
||||
|
DataProviderService.prototype.validateActivities.call( |
||||
|
{ |
||||
|
configurationService: { get: () => [] }, |
||||
|
getDataSources: async () => ['YAHOO'], |
||||
|
isPremiumRequired: () => false, |
||||
|
getAssetProfiles: async (items) => |
||||
|
Object.fromEntries( |
||||
|
await Promise.all( |
||||
|
items.map(async (item) => [ |
||||
|
getAssetProfileIdentifier(item), |
||||
|
await yahoo.getListingQuote({ symbol: item.symbol }) |
||||
|
]) |
||||
|
) |
||||
|
) |
||||
|
} as never, |
||||
|
params |
||||
|
) |
||||
|
}; |
||||
|
const resolver = new BrokerInstrumentResolver( |
||||
|
prisma, |
||||
|
providers as never, |
||||
|
{ fetch: (...args: Parameters<typeof fetch>) => fetch(...args) } as never |
||||
|
); |
||||
|
let failAt = 0, |
||||
|
writes = 0; |
||||
|
const database = new Proxy(prisma, { |
||||
|
get(target, property) { |
||||
|
if (property === '$transaction') |
||||
|
return (callback, options) => |
||||
|
prisma.$transaction( |
||||
|
(tx) => |
||||
|
callback( |
||||
|
new Proxy(tx, { |
||||
|
get(client, key) { |
||||
|
if (key === 'brokerImportRecord') |
||||
|
return new Proxy(client.brokerImportRecord, { |
||||
|
get(delegate, method) { |
||||
|
if (method === 'create') |
||||
|
return async (args) => { |
||||
|
if (failAt && ++writes === failAt) |
||||
|
throw Error('INJECTED_QUALIFICATION_FAILURE'); |
||||
|
return delegate.create(args); |
||||
|
}; |
||||
|
return Reflect.get(delegate, method); |
||||
|
} |
||||
|
}); |
||||
|
return Reflect.get(client, key); |
||||
|
} |
||||
|
}) |
||||
|
), |
||||
|
options |
||||
|
); |
||||
|
return Reflect.get(target, property); |
||||
|
} |
||||
|
}); |
||||
|
const service = new BrokerImportService( |
||||
|
database, |
||||
|
resolver, |
||||
|
providers as never, |
||||
|
new EventEmitter2() |
||||
|
); |
||||
|
const input: BrokerImportInput = { |
||||
|
format: 'DIRECTA', |
||||
|
accountId: account.id, |
||||
|
csv: await readFile(path, 'utf8'), |
||||
|
symbols: {}, |
||||
|
useOperationDate: true |
||||
|
}; |
||||
|
const user = { |
||||
|
id: userId, |
||||
|
subscription: { type: 'Basic' } |
||||
|
} as UserWithSettings; |
||||
|
const scope = { accountId: account.id, userId }; |
||||
|
const snapshot = async () => |
||||
|
JSON.stringify( |
||||
|
await Promise.all([ |
||||
|
prisma.order.count({ where: { userId } }), |
||||
|
prisma.brokerImportRecord.count({ where: { userId } }), |
||||
|
prisma.symbolProfile.count(), |
||||
|
prisma.account.findUnique({ |
||||
|
where: { id_userId: { id: account.id, userId } } |
||||
|
}), |
||||
|
prisma.accountBalance.findMany({ |
||||
|
where: scope, |
||||
|
orderBy: { date: 'asc' } |
||||
|
}) |
||||
|
]) |
||||
|
); |
||||
|
const before = await snapshot(), |
||||
|
first = await service.run(input, user, true, 5000); |
||||
|
if ((await snapshot()) !== before) throw Error('PREVIEW_WROTE_DATA'); |
||||
|
const report = { |
||||
|
rows: first.rowsRead, |
||||
|
initial: first.summary, |
||||
|
previewNoWrites: true, |
||||
|
afterChoices: undefined as typeof first.summary, |
||||
|
reconciliation: undefined as typeof first.reconciliation, |
||||
|
persistence: undefined as unknown, |
||||
|
rollbackVerified: false, |
||||
|
simulatedConfirmationMarket: |
||||
|
process.env.BROKER_TEST_CONFIRM_MARKET ?? null |
||||
|
}; |
||||
|
if (process.env.BROKER_TEST_PARTIAL !== 'true') { |
||||
|
await writeFile(reportPath, JSON.stringify(report, null, 2)); |
||||
|
console.log(JSON.stringify(report)); |
||||
|
return; |
||||
|
} |
||||
|
input.excluded = first.operations |
||||
|
.filter((op) => op.status === 'UNSUPPORTED') |
||||
|
.map((op) => op.id); |
||||
|
input.confirmPartial = true; |
||||
|
for (const item of first.instruments) |
||||
|
if (item.status === 'CONFIRMATION_REQUIRED') { |
||||
|
const choices = item.candidates.filter( |
||||
|
(candidate) => |
||||
|
candidate.exchange === process.env.BROKER_TEST_CONFIRM_MARKET && |
||||
|
candidate.currency === 'EUR' |
||||
|
); |
||||
|
if (choices.length === 1) input.symbols[item.isin] = choices[0].key; |
||||
|
} |
||||
|
const plan = await service.run(input, user, true, 5000); |
||||
|
report.afterChoices = plan.summary; |
||||
|
report.reconciliation = plan.reconciliation; |
||||
|
if (plan.errors.length) throw Error('UNRESOLVED_QUALIFICATION_PREVIEW'); |
||||
|
const beforeFailure = await snapshot(); |
||||
|
failAt = plan.operations |
||||
|
.filter((op) => op.status === 'IMPORTABLE') |
||||
|
.reduce((sum, op) => sum + op.lines.length, 0); |
||||
|
let failed = false; |
||||
|
try { |
||||
|
await service.run({ ...input, digest: plan.digest }, user, false, 5000); |
||||
|
} catch (error) { |
||||
|
if (error.message === 'INJECTED_QUALIFICATION_FAILURE') failed = true; |
||||
|
else throw error; |
||||
|
} |
||||
|
if (!failed || (await snapshot()) !== beforeFailure) |
||||
|
throw Error('ROLLBACK_FAILED'); |
||||
|
report.rollbackVerified = true; |
||||
|
failAt = 0; |
||||
|
await service.run({ ...input, digest: plan.digest }, user, false, 5000); |
||||
|
const orderProfiles = await prisma.order.findMany({ |
||||
|
where: { userId }, |
||||
|
select: { symbolProfileId: true } |
||||
|
}); |
||||
|
newProfiles.push( |
||||
|
...orderProfiles |
||||
|
.map((order) => order.symbolProfileId) |
||||
|
.filter((id) => !initial.has(id)) |
||||
|
); |
||||
|
const after = await snapshot(), |
||||
|
again = await service.run(input, user, true, 5000); |
||||
|
if (again.errors.length || again.summary.importable) |
||||
|
throw Error('REIMPORT_NOT_IDEMPOTENT'); |
||||
|
await service.run({ ...input, digest: again.digest }, user, false, 5000); |
||||
|
if ((await snapshot()) !== after) throw Error('REIMPORT_WROTE_DATA'); |
||||
|
report.persistence = { |
||||
|
activities: await prisma.order.count({ where: { userId } }), |
||||
|
provenance: await prisma.brokerImportRecord.count({ where: { userId } }), |
||||
|
reimportDuplicates: again.duplicates, |
||||
|
balanceUnchanged: |
||||
|
(await prisma.accountBalance.findFirst({ where: scope })).value === 123 |
||||
|
}; |
||||
|
if (process.env.BROKER_TEST_OVERLAP_CSV_PATH) { |
||||
|
const overlapping: BrokerImportInput = { |
||||
|
...input, |
||||
|
csv: await readFile(process.env.BROKER_TEST_OVERLAP_CSV_PATH, 'utf8'), |
||||
|
symbols: {}, |
||||
|
excluded: [], |
||||
|
confirmPartial: false |
||||
|
}; |
||||
|
const preview = await service.run(overlapping, user, true, 5000); |
||||
|
overlapping.excluded = preview.operations |
||||
|
.filter((op) => op.status === 'UNSUPPORTED') |
||||
|
.map((op) => op.id); |
||||
|
overlapping.confirmPartial = true; |
||||
|
for (const instrument of preview.instruments) |
||||
|
if (instrument.status === 'CONFIRMATION_REQUIRED') { |
||||
|
const choices = instrument.candidates.filter( |
||||
|
(candidate) => |
||||
|
candidate.exchange === process.env.BROKER_TEST_CONFIRM_MARKET && |
||||
|
candidate.currency === 'EUR' |
||||
|
); |
||||
|
if (choices.length === 1) |
||||
|
overlapping.symbols[instrument.isin] = choices[0].key; |
||||
|
} |
||||
|
const accepted = await service.run(overlapping, user, true, 5000); |
||||
|
if (accepted.errors.length) throw Error('OVERLAP_PREVIEW_FAILED'); |
||||
|
await service.run( |
||||
|
{ ...overlapping, digest: accepted.digest }, |
||||
|
user, |
||||
|
false, |
||||
|
5000 |
||||
|
); |
||||
|
const check = await service.run(overlapping, user, true, 5000); |
||||
|
if (check.summary.importable || check.errors.length) |
||||
|
throw Error('OVERLAP_NOT_IDEMPOTENT'); |
||||
|
(report as typeof report & { overlap: unknown }).overlap = { |
||||
|
rows: accepted.rowsRead, |
||||
|
previouslyImportedRows: accepted.duplicates, |
||||
|
additionalActivities: accepted.summary.importable, |
||||
|
totalActivities: await prisma.order.count({ where: { userId } }), |
||||
|
reimportDuplicates: check.duplicates |
||||
|
}; |
||||
|
newProfiles.push( |
||||
|
...( |
||||
|
await prisma.order.findMany({ |
||||
|
where: { userId }, |
||||
|
select: { symbolProfileId: true } |
||||
|
}) |
||||
|
) |
||||
|
.map((order) => order.symbolProfileId) |
||||
|
.filter((id) => !initial.has(id)) |
||||
|
); |
||||
|
} |
||||
|
await writeFile(reportPath, JSON.stringify(report, null, 2)); |
||||
|
console.log(JSON.stringify(report)); |
||||
|
} finally { |
||||
|
await prisma.user.deleteMany({ where: { id: userId } }); |
||||
|
await prisma.symbolProfile.deleteMany({ |
||||
|
where: { id: { in: [...new Set(newProfiles)] } } |
||||
|
}); |
||||
|
await prisma.$disconnect(); |
||||
|
} |
||||
|
} |
||||
|
main().catch((error) => { |
||||
|
console.error('BROKER_QUALIFICATION_FAILED', error.name); |
||||
|
process.exitCode = 1; |
||||
|
}); |
||||
Loading…
Reference in new issue