Skip to content
Open
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,18 @@ The property `activeTanMedia` contains a list of the TAN media names you can use

The `bankingInformation` is primarily obtained through the `synchronize()` calls as demonstrated above. However, it is possible that the banking information may have changed since the last synchronization call. To address this, the BPD and UPD are versioned, and with every transaction made, not just synchronizations, the currently used versions are provided to the bank. If any changes have occurred, the bank will send back new versions of the BPD and UPD respectively. This process is managed by the client, but it is essential to check the `bankingInformationUpdated` property, which is available in every response. This property indicates if there have been any changes, and it is important to persist the new version for future sessions. The most up-to-date version of the `bankingInformation` object can always be retrieved using `config.bankingInformation`.

### Statements as the bank sent them

Besides the parsed `statements`, a statement response carries `rawDocuments`: the documents exactly as the bank sent them. For CAMT that is one XML document per booking day (already decoded to a string), for MT940 the whole stream as one document. Use them to run your own parser, to archive the original, or to treat downloaded and uploaded statements alike. All CAMT documents are present even when the built-in parser fails on one of them.

```typescript
const response = await client.getAccountStatements(account, from, to);
for (const document of response.rawDocuments ?? []) {
// document.format is 'camt' or 'mt940', document.content the text as the bank sent it
archive(document.format, document.content);
}
```

### Debugging

If you need to debug issues and the `response.bankAnswers` don't provide enough information, you can enable debugging of messages with:
Expand Down
7 changes: 7 additions & 0 deletions src/interactions/customerInteraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ export interface ClientResponse {

export interface StatementResponse extends ClientResponse {
statements: Statement[];
/**
* The statement documents exactly as the bank sent them: one CAMT XML document per
* booking day (already decoded to a string), or the MT940 stream as one document.
* Lets callers run their own parser, e.g. to read fields the built-in parsers skip
* or to treat downloaded and uploaded statements alike.
*/
rawDocuments?: { format: 'camt' | 'mt940'; content: string }[];
}

export abstract class CustomerInteraction {
Expand Down
33 changes: 18 additions & 15 deletions src/interactions/statementInteractionCAMT.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,24 +56,27 @@ export class StatementInteractionCAMT extends CustomerOrderInteraction {
.findAllSegments<HICAZSegment>(HICAZ.Id)
.flatMap((segment) => segment.bookedTransactions ?? []);

if (camtMessages.length > 0) {
// Decode every document first, so callers get all of them as the bank sent them,
// even when the built-in parser fails on one
const xmlStrings = camtMessages.map((camtMessage) => {
// The regex looks for the XML declaration `<?xml ... ?>`
// and checks if it contains the attribute encoding="UTF-8".
// The 'i' flag makes the match case-insensitive (e.g., for "utf-8").
const isUtf8Encoded = /<\?xml[^>]*encoding="UTF-8"[^>]*\?>/i.test(camtMessage);
// camtMessage is initially encoded as 'latin1' (ISO-8859-1), but actually contains UTF-8 data.
// Therefore, we need to first convert it back to a buffer using 'latin1', and then decode it as 'utf8'.
return isUtf8Encoded ? Buffer.from(camtMessage, 'latin1').toString('utf8') : camtMessage;
});
clientResponse.rawDocuments = xmlStrings.map((content) => ({
format: 'camt' as const,
content,
}));

if (xmlStrings.length > 0) {
try {
// Parse all CAMT messages (one per booking day) and combine statements
const allStatements: Statement[] = [];
for (const camtMessage of camtMessages) {
// The regex looks for the XML declaration `<?xml ... ?>`
// and checks if it contains the attribute encoding="UTF-8".
// The 'i' flag makes the match case-insensitive (e.g., for "utf-8").
const isUtf8Encoded = /<\?xml[^>]*encoding="UTF-8"[^>]*\?>/i.test(camtMessage);

let xmlString: string = camtMessage;
if (isUtf8Encoded) {
// camtMessage is initially encoded as 'latin1' (ISO-8859-1), but actually contains UTF-8 data.
// Therefore, we need to first convert it back to a buffer using 'latin1', and then decode it as 'utf8'.
const intermediateBuffer = Buffer.from(camtMessage, 'latin1');
xmlString = intermediateBuffer.toString('utf8');
}

for (const xmlString of xmlStrings) {
const parser = new CamtParser(xmlString);
const statements = parser.parse();
allStatements.push(...statements);
Expand Down
4 changes: 4 additions & 0 deletions src/interactions/statementInteractionMT940.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ export class StatementInteractionMT940 extends CustomerOrderInteraction {
.filter((booked) => !!booked)
.join('');

clientResponse.rawDocuments = bookedTransactions
? [{ format: 'mt940', content: bookedTransactions }]
: [];

if (bookedTransactions) {
try {
const parser = new Mt940Parser(bookedTransactions);
Expand Down
56 changes: 56 additions & 0 deletions src/tests/rawStatementDocuments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { describe, expect, it } from 'vitest';
import { StatementInteractionCAMT } from '../interactions/statementInteractionCAMT.js';
import { StatementInteractionMT940 } from '../interactions/statementInteractionMT940.js';
import { Message } from '../message.js';
import { registerSegments } from '../segments/registry.js';

registerSegments();

const CAMT_DESCRIPTOR = 'urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.08';

const camt = (id: string) =>
`<?xml version="1.0"?><Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.052.001.08">` +
`<BkToCstmrAcctRpt><GrpHdr><MsgId>${id}</MsgId><CreDtTm>2026-07-01T10:00:00+02:00</CreDtTm></GrpHdr>` +
`<Rpt><Id>${id}</Id><Acct><Id><IBAN>DE991234567123456</IBAN></Id><Ccy>EUR</Ccy></Acct>` +
`<Ntry><Amt>10.00</Amt><CdtDbtInd>DBIT</CdtDbtInd>` +
`<BookgDt><Dt>2026-07-01</Dt></BookgDt><ValDt><Dt>2026-07-01</Dt></ValDt>` +
`<AcctSvcrRef>TXN${id}</AcctSvcrRef></Ntry></Rpt></BkToCstmrAcctRpt></Document>`;

const hicaz = (...docs: string[]) =>
`HICAZ:5:1+DE991234567123456:BANK12+${CAMT_DESCRIPTOR}+${docs.map((d) => `@${d.length}@${d}`).join(':')}'`;

const MT940 =
':20:STARTUMS\r\n:25:12030000/1234567890\r\n:28C:00001/001\r\n:60F:C260701EUR100,00\r\n' +
':61:2607010701DR10,00NMSCNONREF\r\n:86:166?00GUTSCHRIFT?20SVWZ+Test\r\n:62F:C260701EUR90,00\r\n-\r\n';

type Response = { statements: unknown[]; rawDocuments?: { format: string; content: string }[] };

describe('rawDocuments: statements as the bank sent them', () => {
it('CAMT: one document per booking day, in order, even when the built-in parser fails', () => {
const message = Message.decode(`${hicaz(camt('A'))}${hicaz(camt('B'))}`);
const clientResponse: Response = { statements: [] };
new StatementInteractionCAMT('123').handleResponse(message, clientResponse as never);

expect(clientResponse.rawDocuments).toEqual([
{ format: 'camt', content: camt('A') },
{ format: 'camt', content: camt('B') },
]);
// These minimal documents have no balances, which the built-in parser rejects
expect(clientResponse.statements).toEqual([]);
});

it('CAMT: an empty list when the bank sent no bookings', () => {
const message = Message.decode(`HIRMG:3:2+0010::Entgegengenommen.'`);
const clientResponse: Response = { statements: [] };
new StatementInteractionCAMT('123').handleResponse(message, clientResponse as never);
expect(clientResponse.rawDocuments).toEqual([]);
});

it('MT940: the stream as one document', () => {
const message = Message.decode(`HIKAZ:5:7+@${MT940.length}@${MT940}'`);
const clientResponse: Response = { statements: [] };
new StatementInteractionMT940('123').handleResponse(message, clientResponse as never);
expect(clientResponse.rawDocuments).toEqual([{ format: 'mt940', content: MT940 }]);
expect(clientResponse.statements.length).toBeGreaterThan(0);
});
});