Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | - | ❌ | ❌ |
Expand Down
23 changes: 19 additions & 4 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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';
Expand Down Expand Up @@ -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);
}

/**
Expand All @@ -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<StatementResponse> {
async getCreditCardStatements(
account: AccountRef,
from?: Date,
to?: Date,
): Promise<StatementResponse> {
// 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;
Expand All @@ -283,7 +298,7 @@ export class FinTSClient {
tan?: string,
): Promise<StatementResponse> {
return (await this.continueCustomerInteractionWithTan(
[DKKKU.Id],
[HKKKU.Id, DKKKU.Id],
tanReference,
tan,
)) as StatementResponse;
Expand Down
17 changes: 14 additions & 3 deletions src/creditCardStatement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
163 changes: 163 additions & 0 deletions src/interactions/creditcardStatementInteractionHKKKU.ts
Original file line number Diff line number Diff line change
@@ -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<HIKKUSParameter>(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<HIKKUSegment>(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);
}
}
}
}
35 changes: 35 additions & 0 deletions src/segments/HIKKU.ts
Original file line number Diff line number Diff line change
@@ -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),
];
}
36 changes: 36 additions & 0 deletions src/segments/HIKKUS.ts
Original file line number Diff line number Diff line change
@@ -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<HIKKUSParameter>;

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),
]);
}
}
41 changes: 41 additions & 0 deletions src/segments/HKKKU.ts
Original file line number Diff line number Diff line change
@@ -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),
];
}
Loading
Loading