# 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.