From 256142454591fa1fc316b917a1f05826a31f978f Mon Sep 17 00:00:00 2001 From: Theo Vassiliou Date: Mon, 12 Oct 2026 00:21:55 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20HKKKU=20=E2=80=94=20credit=20card=20tra?= =?UTF-8?q?nsactions=20(DK=20G112,=20successor=20of=20DKKKU)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some banks (e.g. Postbank) no longer offer DKKKU for credit card accounts, only the standardized HKKKU. Adds HKKKU/HIKKU/HIKKUS v1 and CreditCardStatementInteractionHKKKU; the client prefers HKKKU where the account offers it and falls back to DKKKU. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/client.ts | 23 +- src/creditCardStatement.ts | 17 +- src/index.ts | 2 + .../creditcardStatementInteractionHKKKU.ts | 163 ++++++++++++ src/segments/HIKKU.ts | 35 +++ src/segments/HIKKUS.ts | 36 +++ src/segments/HKKKU.ts | 41 +++ src/segments/registry.ts | 6 + src/tests/HKKKU.test.ts | 248 ++++++++++++++++++ src/tests/client.test.ts | 48 ++++ 11 files changed, 613 insertions(+), 8 deletions(-) create mode 100644 src/interactions/creditcardStatementInteractionHKKKU.ts create mode 100644 src/segments/HIKKU.ts create mode 100644 src/segments/HIKKUS.ts create mode 100644 src/segments/HKKKU.ts create mode 100644 src/tests/HKKKU.test.ts diff --git a/README.md b/README.md index 60ebb5b..57b1f00 100644 --- a/README.md +++ b/README.md @@ -203,7 +203,7 @@ The following table shows all transactions supported by the FinTSClient interfac | **Account Balance** | `getAccountBalance(account: AccountRef)` | Fetches the current balance for a specific account | HKSAL | ✓ | ✓ | | **Account Statements** | `getAccountStatements(account: AccountRef, from?, to?)` | Fetches account transactions/statements for a date range (MT940 or CAMT format) | HKKAZ, HKCAZ | ✓ | ✓ | | **Portfolio** | `getPortfolio(account: AccountRef, currency?, priceQuality?, maxEntries?)` | Fetches securities portfolio information for depot accounts | HKWPD | ✓ | ✓ | -| **Credit Card Statements** | `getCreditCardStatements(account: AccountRef, from?)` | Fetches credit card statements for credit card accounts | DKKKU | ✓ | ✓ | +| **Credit Card Statements** | `getCreditCardStatements(account: AccountRef, from?, to?)` | Fetches credit card statements for credit card accounts | HKKKU, DKKKU | ✓ | ✓ | | **Electronic Statements** | `getElectronicStatements(account: AccountRef, options?)` | Fetches the statement document from the electronic mailbox, usually a PDF | HKEKA | ✓ | ✓ | | **TAN Method Selection** | `selectTanMethod(tanMethodId)` | Selects a TAN method by ID from available methods | - | ❌ | ❌ | | **TAN Media Selection** | `selectTanMedia(tanMediaName)` | Selects a specific TAN media device by name | - | ❌ | ❌ | diff --git a/src/client.ts b/src/client.ts index bafffb9..678de24 100644 --- a/src/client.ts +++ b/src/client.ts @@ -6,6 +6,7 @@ import { BalanceInteraction, } from './interactions/balanceInteraction.js'; import { CreditCardStatementInteraction } from './interactions/creditcardStatementInteraction.js'; +import { CreditCardStatementInteractionHKKKU } from './interactions/creditcardStatementInteractionHKKKU.js'; import type { ClientResponse, CustomerOrderInteraction, @@ -28,6 +29,7 @@ import { HKCAZ } from './segments/HKCAZ.js'; import { HKEKA } from './segments/HKEKA.js'; import { HKIDN } from './segments/HKIDN.js'; import { HKKAZ } from './segments/HKKAZ.js'; +import { HKKKU } from './segments/HKKKU.js'; import { HKSAL } from './segments/HKSAL.js'; import { HKWPD } from './segments/HKWPD.js'; import type { TanMethod } from './tanMethod.js'; @@ -253,9 +255,12 @@ export class FinTSClient { * @returns true if the bank (and account) supports fetching credit card statements */ canGetCreditCardStatements(account?: AccountRef): boolean { + // HKKKU is the standardized successor of DKKKU; some banks (e.g. Postbank) only offer HKKKU return account - ? this.config.isAccountTransactionSupported(account, DKKKU.Id) - : this.config.isTransactionSupported(DKKKU.Id); + ? this.config.isAccountTransactionSupported(account, HKKKU.Id) || + this.config.isAccountTransactionSupported(account, DKKKU.Id) + : this.config.isTransactionSupported(HKKKU.Id) || + this.config.isTransactionSupported(DKKKU.Id); } /** @@ -266,7 +271,17 @@ export class FinTSClient { * @param to - an optional end date of the period to fetch the statements for * @returns an account statements response containing an array of statements */ - async getCreditCardStatements(account: AccountRef, from?: Date): Promise { + async getCreditCardStatements( + account: AccountRef, + from?: Date, + to?: Date, + ): Promise { + // Prefer HKKKU where the bank offers it for this account; DKKKU has no end date + if (this.config.isAccountTransactionSupported(account, HKKKU.Id)) { + return (await this.startCustomerOrderInteraction( + new CreditCardStatementInteractionHKKKU(account, from, to), + )) as StatementResponse; + } return (await this.startCustomerOrderInteraction( new CreditCardStatementInteraction(account, from), )) as StatementResponse; @@ -283,7 +298,7 @@ export class FinTSClient { tan?: string, ): Promise { return (await this.continueCustomerInteractionWithTan( - [DKKKU.Id], + [HKKKU.Id, DKKKU.Id], tanReference, tan, )) as StatementResponse; diff --git a/src/creditCardStatement.ts b/src/creditCardStatement.ts index 95ceaca..63b996c 100644 --- a/src/creditCardStatement.ts +++ b/src/creditCardStatement.ts @@ -9,7 +9,18 @@ export type CreditCardStatement = { currency: string; amount: number; purpose: string; - originalCurrency: string; - originalAmount: number; - exchangeRate: number; + // Not every bank reports the original amount, e.g. for payments in the account currency (HKKKU) + originalCurrency?: string; + originalAmount?: number; + exchangeRate?: number; + + // Only reported via HKKKU + // Date on which the merchant submitted the transaction + receiptDate?: Date; + // Merchant name + remoteName?: string; + country?: string; + // Whether the transaction is already part of a credit card statement + billed?: boolean; + reference?: string; }; diff --git a/src/index.ts b/src/index.ts index 2432880..bb330b0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,10 +9,12 @@ export * from './bankingInformation.js'; export * from './bpd.js'; export * from './client.js'; export * from './config.js'; +export type { CreditCardStatement } from './creditCardStatement.js'; export * from './dialog.js'; export * from './electronicStatement.js'; export * from './httpClient.js'; export type { AccountBalanceResponse } from './interactions/balanceInteraction.js'; +export type { CreditCardStatementResponse } from './interactions/creditcardStatementInteraction.js'; export type { ClientResponse, StatementResponse } from './interactions/customerInteraction.js'; export type { ElectronicStatementOptions, diff --git a/src/interactions/creditcardStatementInteractionHKKKU.ts b/src/interactions/creditcardStatementInteractionHKKKU.ts new file mode 100644 index 0000000..5b20e2b --- /dev/null +++ b/src/interactions/creditcardStatementInteractionHKKKU.ts @@ -0,0 +1,163 @@ +import { type AccountRef, describeAccount } from '../bankAccount.js'; +import type { FinTSConfig } from '../config.js'; +import type { CreditCardStatement } from '../creditCardStatement.js'; +import type { Message } from '../message.js'; +import type { Segment } from '../segment.js'; +import { HIKKU, type HIKKUSegment } from '../segments/HIKKU.js'; +import type { HIKKUSParameter } from '../segments/HIKKUS.js'; +import { HKKKU, type HKKKUSegment } from '../segments/HKKKU.js'; +import type { CreditCardStatementResponse } from './creditcardStatementInteraction.js'; +import { CustomerOrderInteraction } from './customerInteraction.js'; + +/** + * Splits one raw data element group at unescaped ':' and resolves the escape character '?' + */ +function splitGroup(raw: string): string[] { + const parts: string[] = []; + let current = ''; + for (let i = 0; i < raw.length; i++) { + const c = raw[i]; + if (c === '?' && i + 1 < raw.length) { + current += raw[i + 1]; + i++; + } else if (c === ':') { + parts.push(current); + current = ''; + } else { + current += c; + } + } + parts.push(current); + return parts; +} + +function parseGermanFloat(value: string): number { + return Number.parseFloat(value.replaceAll('.', '').replaceAll(',', '.')); +} + +function parseDate(value: string | undefined): Date | undefined { + if (!value || value.length < 8) { + return undefined; + } + return new Date( + Number.parseInt(value.substring(0, 4), 10), + Number.parseInt(value.substring(4, 6), 10) - 1, + Number.parseInt(value.substring(6, 8), 10), + ); +} + +function signed(value: string, creditDebit: string): number { + const amount = parseGermanFloat(value); + return creditDebit === 'D' ? -amount : amount; +} + +/** + * Credit card transactions via HKKKU/HIKKU (DK G112 / CR 538), the successor of DKKKU. + * + * Entry layout ("Umsatz Kreditkartenkonto"): 0 card number, 1 receipt date, 2 booking date, + * 3 statement date, 4 value date, 5..7 original amount (value, currency, D/C), 8 exchange rate, + * 9..11 booking amount (value, currency, D/C), 12..19 description lines, 20 country, + * 21 merchant name, 22 terminal, 23 billed (J/N), 24 booking reference. + */ +export class CreditCardStatementInteractionHKKKU extends CustomerOrderInteraction { + constructor( + public account: AccountRef, + public from?: Date, + public to?: Date, + ) { + super(HKKKU.Id, HIKKU.Id); + } + + createSegments(init: FinTSConfig): Segment[] { + const bankAccount = init.getBankAccount(this.account); + if (!init.isAccountTransactionSupported(this.account, this.segId)) { + throw Error( + `Account ${describeAccount(this.account)} does not support business transaction '${this.segId}'`, + ); + } + + // Without parameters send the account and the period, which is what banks allow most often + const params = init.getTransactionParameters(HKKKU.Id); + const accountRequired = params?.accountRequired ?? true; + const dateRangeAllowed = params?.dateRangeAllowed ?? true; + + const hkkku: HKKKUSegment = { + header: { segId: HKKKU.Id, segNr: 0, version: HKKKU.Version }, + account: accountRequired + ? { + iban: bankAccount.iban, + bic: bankAccount.bic, + accountNumber: bankAccount.accountNumber, + subAccountId: bankAccount.subAccountId, + bank: bankAccount.bank, + } + : undefined, + cardNumber: bankAccount.accountNumber, + subAccountId: bankAccount.subAccountId, + from: dateRangeAllowed ? this.from : undefined, + to: dateRangeAllowed ? this.to : undefined, + }; + + return [hkkku]; + } + + handleResponse(response: Message, clientResponse: CreditCardStatementResponse) { + // A response the bank spread over several messages arrives as several HIKKU segments. + // The balance is the same in each, the entries are not. + const segments = response.findAllSegments(HIKKU.Id); + clientResponse.statements = []; + + const first = segments[0]; + if (!first) { + return; + } + + // HKSAL is often not offered for credit card accounts, so the balance from HIKKU matters + if (first.balance) { + const date = first.balance.date; + if (first.balance.time) { + date.setUTCHours(first.balance.time.getUTCHours()); + date.setUTCMinutes(first.balance.time.getUTCMinutes()); + date.setUTCSeconds(first.balance.time.getUTCSeconds()); + } + clientResponse.balance = { + balance: first.balance.amount.value * (first.balance.creditDebit === 'D' ? -1 : 1), + date, + currency: first.balance.amount.currency, + }; + } + + for (const segment of segments) { + for (const raw of segment.entries ?? []) { + const p = splitGroup(raw); + const bookingDate = parseDate(p[2]); + const receiptDate = parseDate(p[1]); + const transactionDate = bookingDate ?? receiptDate; + if (!transactionDate) { + continue; + } + + const statement: CreditCardStatement = { + transactionDate, + receiptDate, + valueDate: parseDate(p[4]) ?? transactionDate, + currency: p[10], + amount: signed(p[9], p[11]), + purpose: p + .slice(12, 20) + .map((x) => x.trim()) + .filter((x) => x) + .join(' '), + remoteName: p[21]?.trim() || undefined, + country: p[20]?.trim() || undefined, + originalCurrency: p[6] || undefined, + originalAmount: p[5] ? signed(p[5], p[7]) : undefined, + exchangeRate: p[8] ? parseGermanFloat(p[8]) : undefined, + billed: p[23] === 'J' ? true : p[23] === 'N' ? false : undefined, + reference: p[24] || undefined, + }; + clientResponse.statements.push(statement); + } + } + } +} diff --git a/src/segments/HIKKU.ts b/src/segments/HIKKU.ts new file mode 100644 index 0000000..0e4640f --- /dev/null +++ b/src/segments/HIKKU.ts @@ -0,0 +1,35 @@ +import { Binary } from '../dataElements/Binary.js'; +import { Dat } from '../dataElements/Dat.js'; +import { Text } from '../dataElements/Text.js'; +import { type Balance, BalanceGroup } from '../dataGroups/Balance.js'; +import type { Segment } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +export type HIKKUSegment = Segment & { + cardNumber: string; + accountId?: string; + balance?: Balance; + lastStatementDate?: Date; + nextStatementDate?: Date; + /** One raw data element group "Umsatz Kreditkartenkonto" per entry, split by the interaction */ + entries?: string[]; +}; + +/** + * Credit card transactions response (DK G112 / CR 538) + */ +export class HIKKU extends SegmentDefinition { + static Id = 'HIKKU'; + version = 1; + constructor() { + super(HIKKU.Id); + } + elements = [ + new Text('cardNumber', 1, 1), + new Text('accountId', 0, 1), + new BalanceGroup('balance', 0, 1), + new Dat('lastStatementDate', 0, 1), + new Dat('nextStatementDate', 0, 1), + new Binary('entries', 0, 10000, Number.MAX_SAFE_INTEGER), + ]; +} diff --git a/src/segments/HIKKUS.ts b/src/segments/HIKKUS.ts new file mode 100644 index 0000000..4e6ee0b --- /dev/null +++ b/src/segments/HIKKUS.ts @@ -0,0 +1,36 @@ +import { Numeric } from '../dataElements/Numeric.js'; +import { YesNo } from '../dataElements/YesNo.js'; +import { + BusinessTransactionParameter, + type BusinessTransactionParameterSegment, +} from './businessTransactionParameter.js'; + +export type HIKKUSSegment = BusinessTransactionParameterSegment; + +export type HIKKUSParameter = { + /** How many days back the bank keeps credit card transactions */ + storagePeriodDays: number; + /** Whether the number of entries may be limited */ + maxEntriesAllowed: boolean; + /** Whether a period (from/to) may be requested */ + dateRangeAllowed: boolean; + /** Whether the request must carry the account connection in addition to the card number */ + accountRequired: boolean; +}; + +/** + * Parameters for the HKKKU business transaction (credit card transactions) + */ +export class HIKKUS extends BusinessTransactionParameter { + static Id = 'HIKKUS'; + version = 1; + + constructor() { + super(HIKKUS.Id, [ + new Numeric('storagePeriodDays', 1, 1, 4), + new YesNo('maxEntriesAllowed', 1, 1), + new YesNo('dateRangeAllowed', 1, 1), + new YesNo('accountRequired', 1, 1), + ]); + } +} diff --git a/src/segments/HKKKU.ts b/src/segments/HKKKU.ts new file mode 100644 index 0000000..6b32ba7 --- /dev/null +++ b/src/segments/HKKKU.ts @@ -0,0 +1,41 @@ +import { AlphaNumeric } from '../dataElements/AlphaNumeric.js'; +import { Dat } from '../dataElements/Dat.js'; +import { Identification } from '../dataElements/Identification.js'; +import { Numeric } from '../dataElements/Numeric.js'; +import { + type InternationalAccount, + InternationalAccountGroup, +} from '../dataGroups/InternationalAccount.js'; +import type { SegmentWithContinuationMark } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +export type HKKKUSegment = SegmentWithContinuationMark & { + /** Only sent when the bank sets `accountRequired` in its HIKKUS parameters */ + account?: InternationalAccount; + cardNumber: string; + subAccountId?: string; + from?: Date; + to?: Date; + maxEntries?: number; +}; + +/** + * Request credit card transactions (DK G112 / CR 538), the standardized successor of DKKKU + */ +export class HKKKU extends SegmentDefinition { + static Id = 'HKKKU'; + static Version = 1; + constructor() { + super(HKKKU.Id); + } + version = HKKKU.Version; + elements = [ + new InternationalAccountGroup('account', 0, 1), + new Identification('cardNumber', 1, 1), + new Identification('subAccountId', 0, 1), + new Dat('from', 0, 1), + new Dat('to', 0, 1), + new Numeric('maxEntries', 0, 1, 4), + new AlphaNumeric('continuationMark', 0, 1, 35), + ]; +} diff --git a/src/segments/registry.ts b/src/segments/registry.ts index 2c6cd83..a38c1b9 100644 --- a/src/segments/registry.ts +++ b/src/segments/registry.ts @@ -11,6 +11,8 @@ import { HIEKAS } from './HIEKAS.js'; import { HIKAZ } from './HIKAZ.js'; import { HIKAZS } from './HIKAZS.js'; import { HIKIM } from './HIKIM.js'; +import { HIKKU } from './HIKKU.js'; +import { HIKKUS } from './HIKKUS.js'; import { HIKOM } from './HIKOM.js'; import { HIPINS } from './HIPINS.js'; import { HIRMG } from './HIRMG.js'; @@ -30,6 +32,7 @@ import { HKEKA } from './HKEKA.js'; import { HKEND } from './HKEND.js'; import { HKIDN } from './HKIDN.js'; import { HKKAZ } from './HKKAZ.js'; +import { HKKKU } from './HKKKU.js'; import { HKSAL } from './HKSAL.js'; import { HKSPA } from './HKSPA.js'; import { HKSYN } from './HKSYN.js'; @@ -76,6 +79,9 @@ export function registerSegments() { registerSegmentDefinition(new HKKAZ()); registerSegmentDefinition(new DKKKU()); registerSegmentDefinition(new DIKKU()); + registerSegmentDefinition(new HKKKU()); + registerSegmentDefinition(new HIKKU()); + registerSegmentDefinition(new HIKKUS()); registerSegmentDefinition(new HIKAZ()); registerSegmentDefinition(new HIKAZS()); registerSegmentDefinition(new HKCAZ()); diff --git a/src/tests/HKKKU.test.ts b/src/tests/HKKKU.test.ts new file mode 100644 index 0000000..b976d49 --- /dev/null +++ b/src/tests/HKKKU.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from 'vitest'; +import { AccountType } from '../bankAccount.js'; +import { Language } from '../codes.js'; +import { FinTSConfig } from '../config.js'; +import type { CreditCardStatementResponse } from '../interactions/creditcardStatementInteraction.js'; +import { CreditCardStatementInteractionHKKKU } from '../interactions/creditcardStatementInteractionHKKKU.js'; +import { Message } from '../message.js'; +import { decode, encode } from '../segment.js'; +import type { HIKKUSegment } from '../segments/HIKKU.js'; +import type { HIKKUSSegment } from '../segments/HIKKUS.js'; +import { HKKKU, type HKKKUSegment } from '../segments/HKKKU.js'; +import { registerSegments } from '../segments/registry.js'; + +registerSegments(); + +const CARD = '5232000011112222'; + +/** One "Umsatz Kreditkartenkonto" group from its 25 positions */ +function entry(fields: Record): string { + return Array.from({ length: 25 }, (_, i) => fields[i] ?? '').join(':'); +} + +// A purchase in EUR, one in USD with exchange rate, and a refund. Escaped ':' in the description. +const PURCHASE = entry({ + 0: CARD, + 1: '20261001', + 2: '20261002', + 4: '20261002', + 9: '12,50', + 10: 'EUR', + 11: 'D', + 12: 'KAFFEEBAR AM MARKT', + 13: 'Filiale?: Mitte', + 20: 'DE', + 21: 'KAFFEEBAR', + 23: 'N', + 24: 'REF0001', +}); +const FOREIGN = entry({ + 0: CARD, + 1: '20260928', + 2: '20260930', + 3: '20261003', + 4: '20260930', + 5: '20,00', + 6: 'USD', + 7: 'D', + 8: '1,0852', + 9: '18,43', + 10: 'EUR', + 11: 'D', + 12: 'ONLINE SHOP INC', + 20: 'US', + 21: 'ONLINE SHOP', + 23: 'J', + 24: 'REF0002', +}); +const REFUND = entry({ + 0: CARD, + 2: '20261003', + 9: '1.234,00', + 10: 'EUR', + 11: 'C', + 12: 'GUTSCHRIFT', +}); + +const HIKKU_TEXT = `HIKKU:4:1:3+${CARD}++D:655,56:EUR:20261004+20261003+20261103+${PURCHASE}+${FOREIGN}'`; + +function config(params?: string) { + return FinTSConfig.fromBankingInformation('product', '1.0', { + systemId: 'SYSTEM01', + bpd: { + version: 1, + url: 'https://bank.example.com/fints', + countryCode: 280, + bankId: '10020030', + bankName: 'Example Bank', + allowedTransactions: [ + { + transId: 'HKKKU', + versions: [1], + tanRequired: false, + params: params ? (decode(params) as HIKKUSSegment).params : undefined, + }, + ], + maxTransactionsPerMessage: 1, + supportedLanguages: [Language.German], + supportedHbciVersions: [300], + supportedTanMethods: [], + availableTanMethodIds: [], + }, + upd: { + version: 1, + usage: 0, + bankAccounts: [ + { + accountNumber: CARD, + bank: { bankId: '10020030', country: 280 }, + iban: 'DE89370400440532013002', + customerId: 'customer1', + accountType: AccountType.CreditCardAccount, + currency: 'EUR', + holder1: 'Test User', + allowedTransactions: [{ transId: 'HKKKU', numSignatures: 1 }], + }, + ], + }, + bankMessages: [], + }); +} + +describe('HKKKU v1', () => { + it('encode with account and period', () => { + const segment: HKKKUSegment = { + header: { segId: HKKKU.Id, segNr: 3, version: 1 }, + account: { iban: 'DE89370400440532013002', bic: 'BANKDEFF' }, + cardNumber: CARD, + from: new Date('2026-09-01'), + to: new Date('2026-10-04'), + }; + + expect(encode(segment)).toBe( + `HKKKU:3:1+DE89370400440532013002:BANKDEFF+${CARD}++20260901+20261004'`, + ); + }); + + it('encode without account', () => { + const segment: HKKKUSegment = { + header: { segId: HKKKU.Id, segNr: 3, version: 1 }, + cardNumber: CARD, + }; + + expect(encode(segment)).toBe(`HKKKU:3:1++${CARD}'`); + }); + + it('decode and encode roundtrip matches', () => { + const text = `HKKKU:3:1+DE89370400440532013002:BANKDEFF+${CARD}++20260901+20261004++AUFSETZ1'`; + expect(encode(decode(text))).toBe(text); + }); +}); + +describe('HIKKU v1', () => { + it('decode', () => { + const segment = decode(HIKKU_TEXT) as HIKKUSegment; + + expect(segment.cardNumber).toBe(CARD); + expect(segment.balance?.creditDebit).toBe('D'); + expect(segment.balance?.amount.value).toBe(655.56); + expect(segment.lastStatementDate).toEqual(new Date('2026-10-03')); + expect(segment.nextStatementDate).toEqual(new Date('2026-11-03')); + expect(segment.entries).toHaveLength(2); + }); +}); + +describe('HIKKUS v1', () => { + it('decode and encode roundtrip matches', () => { + const text = "HIKKUS:12:1:4+1+1+0+180:N:J:J'"; + const segment = decode(text) as HIKKUSSegment; + + expect(segment.params.storagePeriodDays).toBe(180); + expect(segment.params.maxEntriesAllowed).toBe(false); + expect(segment.params.dateRangeAllowed).toBe(true); + expect(segment.params.accountRequired).toBe(true); + + expect(encode(segment)).toBe(text); + }); +}); + +describe('CreditCardStatementInteractionHKKKU', () => { + function handle(message: Message) { + const interaction = new CreditCardStatementInteractionHKKKU(CARD); + const clientResponse = { bankAnswers: message.getBankAnswers() } as never; + interaction.handleResponse(message, clientResponse); + return clientResponse as unknown as CreditCardStatementResponse; + } + + it('sends account and period by default', () => { + const [segment] = new CreditCardStatementInteractionHKKKU( + CARD, + new Date('2026-09-01'), + new Date('2026-10-04'), + ).createSegments(config()) as HKKKUSegment[]; + + expect(segment.cardNumber).toBe(CARD); + expect(segment.account?.iban).toBe('DE89370400440532013002'); + expect(segment.from).toEqual(new Date('2026-09-01')); + expect(segment.to).toEqual(new Date('2026-10-04')); + }); + + it('leaves out account and period when the parameters do not allow them', () => { + const [segment] = new CreditCardStatementInteractionHKKKU( + CARD, + new Date('2026-09-01'), + ).createSegments(config("HIKKUS:12:1:4+1+1+0+180:N:N:N'")) as HKKKUSegment[]; + + expect(segment.account).toBeUndefined(); + expect(segment.from).toBeUndefined(); + }); + + it('maps balance and entries', () => { + const response = handle(Message.decode(`HIRMG:3:2+0010::Entgegengenommen.'${HIKKU_TEXT}`)); + + expect(response.balance.balance).toBe(-655.56); + expect(response.balance.currency).toBe('EUR'); + expect(response.statements).toHaveLength(2); + + const [purchase, foreign] = response.statements; + expect(purchase).toEqual({ + transactionDate: new Date(2026, 9, 2), + receiptDate: new Date(2026, 9, 1), + valueDate: new Date(2026, 9, 2), + currency: 'EUR', + amount: -12.5, + purpose: 'KAFFEEBAR AM MARKT Filiale: Mitte', + remoteName: 'KAFFEEBAR', + country: 'DE', + originalCurrency: undefined, + originalAmount: undefined, + exchangeRate: undefined, + billed: false, + reference: 'REF0001', + }); + expect(foreign.amount).toBe(-18.43); + expect(foreign.originalAmount).toBe(-20); + expect(foreign.originalCurrency).toBe('USD'); + expect(foreign.exchangeRate).toBe(1.0852); + expect(foreign.billed).toBe(true); + }); + + it('merges the entries of several HIKKU segments', () => { + const second = `HIKKU:5:1:3+${CARD}++D:655,56:EUR:20261004+20261003+20261103+${REFUND}'`; + const response = handle( + Message.decode(`HIRMG:3:2+0010::Entgegengenommen.'${HIKKU_TEXT}${second}`), + ); + + expect(response.statements).toHaveLength(3); + const refund = response.statements[2]; + expect(refund.amount).toBe(1234); + expect(refund.transactionDate).toEqual(new Date(2026, 9, 3)); + expect(refund.receiptDate).toBeUndefined(); + expect(refund.valueDate).toEqual(new Date(2026, 9, 3)); + }); + + it('returns no statements without HIKKU', () => { + const response = handle(Message.decode("HIRMG:3:2+0010::Entgegengenommen.'")); + expect(response.statements).toEqual([]); + }); +}); diff --git a/src/tests/client.test.ts b/src/tests/client.test.ts index 38ed17d..af9248d 100644 --- a/src/tests/client.test.ts +++ b/src/tests/client.test.ts @@ -27,6 +27,7 @@ describe('FinTSClient', () => { { transId: 'HKKAZ', versions: [6], tanRequired: true }, { transId: 'HKWPD', versions: [7], tanRequired: true }, { transId: 'DKKKU', versions: [2], tanRequired: false }, + { transId: 'HKKKU', versions: [1], tanRequired: false }, ], maxTransactionsPerMessage: 1, supportedLanguages: [Language.German], @@ -100,6 +101,20 @@ describe('FinTSClient', () => { holder1: 'Test User', allowedTransactions: [{ transId: 'DKKKU', numSignatures: 1 }], }, + { + accountNumber: '4444555566', + bank: { + bankId: '10020030', + country: 280, + }, + iban: 'DE89370400440532013003', + customerId: 'customer1', + accountType: AccountType.CreditCardAccount, + currency: 'EUR', + holder1: 'Test User', + // Like Postbank: only the standardized HKKKU, no DKKKU + allowedTransactions: [{ transId: 'HKKKU', numSignatures: 1 }], + }, ], }, bankMessages: [], @@ -655,6 +670,35 @@ describe('FinTSClient', () => { expect(response.statements?.length).toBe(1); expect(response.statements?.[0].closingBalance?.value).toBe(-150.0); }); + + it('uses HKKKU for a card that offers it', async () => { + dialogStartMock.mockResolvedValueOnce( + new Map([ + [ + 'HKKKU', + { + dialogId: 'DIALOG1', + success: true, + requiresTan: false, + bankingInformationUpdated: false, + bankAnswers: [{ code: 20, text: 'Auftrag ausgeführt' }], + statements: [], + }, + ], + ]), + ); + + const addMock = vi.spyOn(Dialog.prototype, 'addCustomerInteraction'); + const response = await client.getCreditCardStatements( + '4444555566', + new Date('2026-09-01'), + new Date('2026-10-04'), + ); + + expect(response.success).toBe(true); + expect(addMock.mock.calls.at(-1)?.[0].segId).toBe('HKKKU'); + addMock.mockRestore(); + }); }); describe('getCreditCardStatementsWithTan', () => { @@ -741,6 +785,10 @@ describe('FinTSClient', () => { it('returns false for non-credit card account', () => { expect(client.canGetCreditCardStatements('1234567890')).toBe(false); }); + + it('returns true for a credit card account that only offers HKKKU', () => { + expect(client.canGetCreditCardStatements('4444555566')).toBe(true); + }); }); });