Compare commits
12 Commits
Author | SHA1 | Date | |
---|---|---|---|
40f9142d70 | |||
4c0ad95eb1 | |||
3144c9edbf | |||
b9317484bf | |||
9dd55543e9 | |||
dfbf66e339 | |||
cb6e79ba50 | |||
c9fab7def2 | |||
fb30c6f4e3 | |||
0e403e1584 | |||
16135cae02 | |||
1190500221 |
63
changelog.md
63
changelog.md
@@ -1,5 +1,68 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-07-29 - 4.4.0 - feat(export)
|
||||
Added buffer download methods to ExportBuilder for in-memory statement handling
|
||||
|
||||
- Added `download()` method to get statements as Buffer without saving to disk
|
||||
- Added `downloadAsArrayBuffer()` method for web API compatibility
|
||||
- Enhanced documentation for account's `getAccountStatement()` method with month-based selection
|
||||
- Updated README with comprehensive examples for all statement export options
|
||||
|
||||
## 2025-07-29 - 4.3.0 - feat(http)
|
||||
Enhanced HTTP client with automatic rate limit handling
|
||||
|
||||
- Added @push.rocks/smartrequest dependency for robust HTTP handling
|
||||
- Implemented automatic retry with exponential backoff for rate-limited requests
|
||||
- Built-in handling of HTTP 429 responses with intelligent waiting
|
||||
- Respects Retry-After headers when provided by the server
|
||||
- Maximum of 3 retry attempts with configurable backoff (1s, 2s, 4s)
|
||||
- Improved error handling and network resilience
|
||||
- Updated readme documentation with automatic rate limit handling examples
|
||||
|
||||
## 2025-07-27 - 4.2.1 - fix(tests)
|
||||
Fix test compatibility with breaking changes from v4.0.0
|
||||
|
||||
- Updated all tests to handle new API structure where methods return objects
|
||||
- Fixed destructuring for getAccounts() which now returns { accounts, sessionData? }
|
||||
- Ensures all 83 tests pass successfully with the stateless architecture
|
||||
|
||||
## 2025-07-27 - 4.2.0 - feat(core)
|
||||
Switch to native fetch API for all HTTP requests
|
||||
|
||||
- Replaced @push.rocks/smartrequest with native fetch API throughout the codebase
|
||||
- Updated HTTP client to use fetch with proper error handling
|
||||
- Updated attachment upload/download methods to use fetch
|
||||
- Updated export download method to use fetch
|
||||
- Updated sandbox user creation to use fetch
|
||||
- Removed smartrequest dependency from package.json and plugins
|
||||
- Improved error messages with HTTP status codes
|
||||
|
||||
## 2025-07-26 - 4.1.3 - fix(export)
|
||||
Fix PDF statement download to use direct content endpoint
|
||||
|
||||
- Changed `downloadContent()` method to use the `/content` endpoint directly for PDF statements
|
||||
- Removed unnecessary attachment lookup step that was causing issues
|
||||
- Simplified the download process for customer statement exports
|
||||
|
||||
## 2025-07-25 - 4.1.1 - fix(httpclient)
|
||||
Fix query parameter handling for smartrequest compatibility
|
||||
|
||||
- Changed query parameter handling to pass objects directly instead of URLSearchParams
|
||||
- Removed URLSearchParams usage and string conversion
|
||||
- Now passes queryParams as an object to smartrequest which handles URL encoding internally
|
||||
|
||||
## 2025-07-25 - 4.1.0 - feat(transactions)
|
||||
Enhanced transaction pagination support with full control over historical data retrieval
|
||||
|
||||
- Added full `IBunqPaginationOptions` support to `getTransactions()` method
|
||||
- Now supports `older_id` for paginating backwards through historical transactions
|
||||
- Supports custom `count` parameter (defaults to 200)
|
||||
- Maintains backward compatibility - passing a number is still treated as `newer_id`
|
||||
- Only includes pagination parameters that are explicitly set (not false/undefined)
|
||||
- Added `example.pagination.ts` demonstrating various pagination patterns
|
||||
|
||||
This enhancement allows banking applications to properly fetch and paginate through historical transaction data using both `newer_id` and `older_id` parameters.
|
||||
|
||||
## 2025-07-25 - 4.0.0 - BREAKING CHANGE(core)
|
||||
Complete stateless architecture - consumers now have full control over session persistence
|
||||
|
||||
|
128
example.pagination.ts
Normal file
128
example.pagination.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { BunqAccount, IBunqPaginationOptions } from './ts/index.js';
|
||||
|
||||
// Example demonstrating the enhanced pagination support in getTransactions
|
||||
|
||||
async function demonstratePagination() {
|
||||
const bunq = new BunqAccount({
|
||||
apiKey: 'your-api-key',
|
||||
deviceName: 'Pagination Demo',
|
||||
environment: 'PRODUCTION',
|
||||
});
|
||||
|
||||
// Initialize and get session
|
||||
const sessionData = await bunq.init();
|
||||
|
||||
// Get accounts
|
||||
const { accounts } = await bunq.getAccounts();
|
||||
const account = accounts[0];
|
||||
|
||||
// Example 1: Get most recent transactions (default behavior)
|
||||
const recentTransactions = await account.getTransactions();
|
||||
console.log(`Got ${recentTransactions.length} recent transactions`);
|
||||
|
||||
// Example 2: Get transactions with custom count
|
||||
const smallBatch = await account.getTransactions({ count: 10 });
|
||||
console.log(`Got ${smallBatch.length} transactions with custom count`);
|
||||
|
||||
// Example 3: Get older transactions using older_id
|
||||
if (recentTransactions.length > 0) {
|
||||
const oldestTransaction = recentTransactions[recentTransactions.length - 1];
|
||||
const olderTransactions = await account.getTransactions({
|
||||
count: 50,
|
||||
older_id: oldestTransaction.id
|
||||
});
|
||||
console.log(`Got ${olderTransactions.length} older transactions`);
|
||||
}
|
||||
|
||||
// Example 4: Get newer transactions using newer_id
|
||||
if (recentTransactions.length > 0) {
|
||||
const newestTransaction = recentTransactions[0];
|
||||
const newerTransactions = await account.getTransactions({
|
||||
count: 20,
|
||||
newer_id: newestTransaction.id
|
||||
});
|
||||
console.log(`Got ${newerTransactions.length} newer transactions`);
|
||||
}
|
||||
|
||||
// Example 5: Backward compatibility - using number as newer_id
|
||||
const backwardCompatible = await account.getTransactions(12345);
|
||||
console.log(`Backward compatible call returned ${backwardCompatible.length} transactions`);
|
||||
|
||||
// Example 6: Paginating through all historical transactions
|
||||
async function getAllTransactions(account: any): Promise<any[]> {
|
||||
const allTransactions: any[] = [];
|
||||
let lastTransactionId: number | false = false;
|
||||
let hasMore = true;
|
||||
|
||||
while (hasMore) {
|
||||
const options: IBunqPaginationOptions = {
|
||||
count: 200,
|
||||
older_id: lastTransactionId
|
||||
};
|
||||
|
||||
const batch = await account.getTransactions(options);
|
||||
|
||||
if (batch.length === 0) {
|
||||
hasMore = false;
|
||||
} else {
|
||||
allTransactions.push(...batch);
|
||||
lastTransactionId = batch[batch.length - 1].id;
|
||||
console.log(`Fetched ${batch.length} transactions, total: ${allTransactions.length}`);
|
||||
}
|
||||
}
|
||||
|
||||
return allTransactions;
|
||||
}
|
||||
|
||||
// Example 7: Getting transactions between two dates
|
||||
async function getTransactionsBetweenDates(
|
||||
account: any,
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<any[]> {
|
||||
const transactions: any[] = [];
|
||||
let olderId: number | false = false;
|
||||
let keepFetching = true;
|
||||
|
||||
while (keepFetching) {
|
||||
const batch = await account.getTransactions({
|
||||
count: 200,
|
||||
older_id: olderId
|
||||
});
|
||||
|
||||
if (batch.length === 0) {
|
||||
keepFetching = false;
|
||||
break;
|
||||
}
|
||||
|
||||
for (const transaction of batch) {
|
||||
const transactionDate = new Date(transaction.created);
|
||||
|
||||
if (transactionDate >= startDate && transactionDate <= endDate) {
|
||||
transactions.push(transaction);
|
||||
} else if (transactionDate < startDate) {
|
||||
// We've gone past our date range
|
||||
keepFetching = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
olderId = batch[batch.length - 1].id;
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
// Usage
|
||||
const lastMonth = new Date();
|
||||
lastMonth.setMonth(lastMonth.getMonth() - 1);
|
||||
const transactionsLastMonth = await getTransactionsBetweenDates(
|
||||
account,
|
||||
lastMonth,
|
||||
new Date()
|
||||
);
|
||||
console.log(`Found ${transactionsLastMonth.length} transactions in the last month`);
|
||||
}
|
||||
|
||||
// Run the demo
|
||||
demonstratePagination().catch(console.error);
|
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@apiclient.xyz/bunq",
|
||||
"version": "4.0.1",
|
||||
"version": "4.1.2",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@apiclient.xyz/bunq",
|
||||
"version": "4.0.1",
|
||||
"version": "4.1.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@bunq-community/bunq-js-client": "^1.1.2",
|
||||
|
21
package.json
21
package.json
@@ -1,39 +1,32 @@
|
||||
{
|
||||
"name": "@apiclient.xyz/bunq",
|
||||
"version": "4.0.1",
|
||||
"version": "4.4.0",
|
||||
"private": false,
|
||||
"description": "A full-featured TypeScript/JavaScript client for the bunq API",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./dist_ts/index.js"
|
||||
},
|
||||
"author": "Lossless GmbH",
|
||||
"author": "Task Venture Capital GmbH",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "(tstest test/ --verbose --logfile)",
|
||||
"test:basic": "(tstest test/test.ts --verbose)",
|
||||
"test:payments": "(tstest test/test.payments.simple.ts --verbose)",
|
||||
"test:webhooks": "(tstest test/test.webhooks.ts --verbose)",
|
||||
"test:session": "(tstest test/test.session.ts --verbose)",
|
||||
"test:errors": "(tstest test/test.errors.ts --verbose)",
|
||||
"test:advanced": "(tstest test/test.advanced.ts --verbose)",
|
||||
"test:oauth": "(tstest test/test.oauth.ts --verbose)",
|
||||
"test": "(tstest test/ --verbose --logfile --timeout 60)",
|
||||
"build": "(tsbuild --web)"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.6.4",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^2.3.1",
|
||||
"@git.zone/tstest": "^2.3.2",
|
||||
"@push.rocks/qenv": "^6.1.0",
|
||||
"@push.rocks/tapbundle": "^6.0.3",
|
||||
"@types/node": "^24.0.14"
|
||||
"@types/node": "^22"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartcrypto": "^2.0.4",
|
||||
"@push.rocks/smartfile": "^11.2.5",
|
||||
"@push.rocks/smartpath": "^5.0.18",
|
||||
"@push.rocks/smartpath": "^6.0.0",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smartrequest": "^2.0.21",
|
||||
"@push.rocks/smartrequest": "^4.2.1",
|
||||
"@push.rocks/smarttime": "^4.0.54"
|
||||
},
|
||||
"files": [
|
||||
|
814
pnpm-lock.yaml
generated
814
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
91
readme.md
91
readme.md
@@ -1,6 +1,34 @@
|
||||
# @apiclient.xyz/bunq
|
||||
|
||||
[](https://www.npmjs.com/package/@apiclient.xyz/bunq)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
A powerful, type-safe TypeScript/JavaScript client for the bunq API with full feature coverage
|
||||
|
||||
## Table of Contents
|
||||
- [Features](#features)
|
||||
- [Stateless Architecture](#stateless-architecture-v400)
|
||||
- [Installation](#installation)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Core Examples](#core-examples)
|
||||
- [Account Management](#account-management)
|
||||
- [Making Payments](#making-payments)
|
||||
- [Payment Requests](#payment-requests)
|
||||
- [Draft Payments](#draft-payments-requires-approval)
|
||||
- [Card Management](#card-management)
|
||||
- [Webhooks](#webhooks)
|
||||
- [File Attachments](#file-attachments)
|
||||
- [Export Statements](#export-statements)
|
||||
- [Session Management](#stateless-session-management)
|
||||
- [User Management](#user-management)
|
||||
- [Advanced Usage](#advanced-usage)
|
||||
- [Security Best Practices](#security-best-practices)
|
||||
- [Migration Guides](#migration-guide)
|
||||
- [Testing](#testing)
|
||||
- [Requirements](#requirements)
|
||||
- [License](#license-and-legal-information)
|
||||
|
||||
## Features
|
||||
|
||||
### Core Banking Operations
|
||||
@@ -26,6 +54,7 @@ A powerful, type-safe TypeScript/JavaScript client for the bunq API with full fe
|
||||
- ⚡ **Promise-based** - Modern async/await support throughout
|
||||
- 🛡️ **Type Safety** - Compile-time type checking for all operations
|
||||
- 📚 **Comprehensive Documentation** - Detailed examples for every feature
|
||||
- 🔄 **Robust HTTP Client** - Built-in retry logic and rate limit handling
|
||||
|
||||
## Stateless Architecture (v4.0.0+)
|
||||
|
||||
@@ -405,6 +434,44 @@ await new ExportBuilder(bunq, account)
|
||||
.lastDays(30)
|
||||
.includeAttachments(true)
|
||||
.downloadTo('/path/to/statement-with-attachments.pdf');
|
||||
|
||||
// Get statement as Buffer (no file saving)
|
||||
const buffer = await new ExportBuilder(bunq, account)
|
||||
.asPdf()
|
||||
.lastMonth()
|
||||
.download();
|
||||
// Use the buffer directly, e.g., send as email attachment
|
||||
await emailService.sendWithAttachment(buffer, 'statement.pdf');
|
||||
|
||||
// Get statement as ArrayBuffer for web APIs
|
||||
const arrayBuffer = await new ExportBuilder(bunq, account)
|
||||
.asCsv()
|
||||
.lastDays(30)
|
||||
.downloadAsArrayBuffer();
|
||||
// Use with web APIs like Blob
|
||||
const blob = new Blob([arrayBuffer], { type: 'text/csv' });
|
||||
|
||||
// Using account's getAccountStatement method for easy month selection
|
||||
const statement1 = account.getAccountStatement({
|
||||
monthlyIndexedFrom1: 1, // Last month (1 = last month, 2 = two months ago, etc.)
|
||||
includeTransactionAttachments: true
|
||||
});
|
||||
await statement1.asPdf().downloadTo('/path/to/last-month.pdf');
|
||||
|
||||
// Or using 0-based indexing
|
||||
const statement2 = account.getAccountStatement({
|
||||
monthlyIndexedFrom0: 0, // Current month (0 = current, 1 = last month, etc.)
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
await statement2.asCsv().downloadTo('/path/to/current-month.csv');
|
||||
|
||||
// Or specify exact date range
|
||||
const statement3 = account.getAccountStatement({
|
||||
from: new Date('2024-01-01'),
|
||||
to: new Date('2024-03-31'),
|
||||
includeTransactionAttachments: true
|
||||
});
|
||||
await statement3.asMt940().downloadTo('/path/to/q1-statement.sta');
|
||||
```
|
||||
|
||||
### Stateless Session Management
|
||||
@@ -552,10 +619,6 @@ try {
|
||||
error.errors.forEach(e => {
|
||||
console.error(`- ${e.error_description}`);
|
||||
});
|
||||
} else if (error.response?.status === 429) {
|
||||
// Handle rate limiting
|
||||
console.error('Rate limited. Please retry after a few seconds.');
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
} else if (error.response?.status === 401) {
|
||||
// Handle authentication errors
|
||||
console.error('Authentication failed:', error.message);
|
||||
@@ -567,6 +630,26 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
### Automatic Rate Limit Handling
|
||||
|
||||
The library automatically handles rate limiting (HTTP 429 responses) with intelligent exponential backoff:
|
||||
|
||||
```typescript
|
||||
// No special handling needed - rate limits are handled automatically
|
||||
const payments = await Promise.all([
|
||||
payment1.create(),
|
||||
payment2.create(),
|
||||
payment3.create(),
|
||||
// ... many more payments
|
||||
]);
|
||||
|
||||
// The HTTP client will automatically:
|
||||
// 1. Detect 429 responses
|
||||
// 2. Wait for the time specified in Retry-After header
|
||||
// 3. Use exponential backoff if no Retry-After is provided
|
||||
// 4. Retry the request automatically (up to 3 times)
|
||||
```
|
||||
|
||||
### Pagination
|
||||
|
||||
```typescript
|
||||
|
@@ -1,71 +1,48 @@
|
||||
# bunq API Client Implementation Plan
|
||||
# Migration Plan: @push.rocks/smartrequest
|
||||
|
||||
cat /home/philkunz/.claude/CLAUDE.md
|
||||
To re-read CLAUDE.md: `cat ~/.claude/CLAUDE.md`
|
||||
|
||||
## Phase 1: Remove External Dependencies & Setup Core Infrastructure
|
||||
## Objective
|
||||
Migrate the Bunq HTTP client from native `fetch` to `@push.rocks/smartrequest` to leverage built-in rate limiting, better error handling, and improved maintainability.
|
||||
|
||||
- [x] Remove @bunq-community/bunq-js-client dependency from package.json
|
||||
- [x] Remove JSONFileStore and bunqCommunityClient from bunq.plugins.ts
|
||||
- [x] Create bunq.classes.apicontext.ts for API context management
|
||||
- [x] Create bunq.classes.httpclient.ts for HTTP request handling
|
||||
- [x] Create bunq.classes.crypto.ts for cryptographic operations
|
||||
- [x] Create bunq.classes.session.ts for session management
|
||||
- [x] Create bunq.interfaces.ts for shared interfaces and types
|
||||
## Tasks
|
||||
|
||||
## Phase 2: Implement Core Authentication Flow
|
||||
### 1. Setup
|
||||
- [x] Install @push.rocks/smartrequest dependency using pnpm
|
||||
- [x] Update ts/bunq.plugins.ts to import smartrequest
|
||||
|
||||
- [x] Implement RSA key pair generation in crypto class
|
||||
- [x] Implement installation endpoint (`POST /v1/installation`)
|
||||
- [x] Implement device registration (`POST /v1/device-server`)
|
||||
- [x] Implement session creation (`POST /v1/session-server`)
|
||||
- [x] Implement request signing mechanism
|
||||
- [x] Implement response verification
|
||||
- [x] Add session token refresh logic
|
||||
### 2. Refactor BunqHttpClient
|
||||
- [x] Replace fetch-based makeRequest method with SmartRequest implementation
|
||||
- [x] Preserve all custom headers (X-Bunq-*)
|
||||
- [x] Maintain request signing functionality
|
||||
- [x] Keep response signature verification
|
||||
- [x] Map LIST method to GET (SmartRequest doesn't have LIST)
|
||||
- [x] Replace manual retry logic with built-in handle429Backoff()
|
||||
|
||||
## Phase 3: Update Existing Classes
|
||||
### 3. Error Handling
|
||||
- [x] Ensure BunqApiError is still thrown for API errors
|
||||
- [x] Map SmartRequest errors to appropriate error messages
|
||||
- [x] Preserve error message format for backward compatibility
|
||||
|
||||
- [x] Refactor BunqAccount class to use new HTTP client
|
||||
- [x] Update BunqMonetaryAccount to work with new infrastructure
|
||||
- [x] Update BunqTransaction to work with new infrastructure
|
||||
- [x] Add proper TypeScript interfaces for all API responses
|
||||
- [x] Implement error handling with bunq-specific error types
|
||||
### 4. Testing
|
||||
- [x] Run existing tests to ensure no regression (tests passing)
|
||||
- [x] Verify rate limiting behavior works correctly
|
||||
- [x] Test signature creation and verification
|
||||
- [x] Ensure all HTTP methods (GET, POST, PUT, DELETE, LIST) work
|
||||
|
||||
## Phase 4: Implement Additional API Resources
|
||||
### 5. Cleanup
|
||||
- [x] Remove unused code from the old implementation (manual retry logic removed)
|
||||
- [x] Update any relevant documentation or comments
|
||||
|
||||
- [x] Create bunq.classes.user.ts for user management
|
||||
- [x] Create bunq.classes.payment.ts for payment operations
|
||||
- [x] Create bunq.classes.card.ts for card management
|
||||
- [x] Create bunq.classes.request.ts for payment requests
|
||||
- [x] Create bunq.classes.schedule.ts for scheduled payments
|
||||
- [x] Create bunq.classes.draft.ts for draft payments
|
||||
- [x] Create bunq.classes.attachment.ts for file handling
|
||||
- [x] Create bunq.classes.export.ts for statement exports
|
||||
- [x] Create bunq.classes.notification.ts for notifications
|
||||
- [x] Create bunq.classes.webhook.ts for webhook management
|
||||
## Implementation Notes
|
||||
|
||||
## Phase 5: Enhanced Features
|
||||
### Key Changes
|
||||
1. Replace native fetch with SmartRequest fluent API
|
||||
2. Use built-in handle429Backoff() instead of manual retry logic
|
||||
3. Leverage SmartRequest's response methods (.json(), .text())
|
||||
4. Maintain all Bunq-specific behavior (signatures, custom headers)
|
||||
|
||||
- [x] Implement pagination support for all list endpoints
|
||||
- [x] Add rate limiting compliance
|
||||
- [x] Implement retry logic with exponential backoff
|
||||
- [x] Add request/response logging capabilities
|
||||
- [x] Implement webhook signature verification
|
||||
- [x] Add OAuth flow support for third-party apps
|
||||
|
||||
## Phase 6: Testing & Documentation
|
||||
|
||||
- [ ] Write unit tests for crypto operations
|
||||
- [ ] Write unit tests for HTTP client
|
||||
- [ ] Write unit tests for all API classes
|
||||
- [ ] Create integration tests using sandbox environment
|
||||
- [x] Update main README.md with usage examples
|
||||
- [x] Add JSDoc comments to all public methods
|
||||
- [x] Create example scripts for common use cases
|
||||
|
||||
## Phase 7: Cleanup & Optimization
|
||||
|
||||
- [x] Remove all references to old bunq-community client
|
||||
- [x] Optimize bundle size
|
||||
- [x] Ensure all TypeScript types are properly exported
|
||||
- [x] Run build and verify all tests pass
|
||||
- [x] Update package version
|
||||
### Risk Mitigation
|
||||
- All Bunq-specific logic remains unchanged
|
||||
- Public API of BunqHttpClient stays the same
|
||||
- Error handling maintains same format
|
@@ -25,7 +25,7 @@ tap.test('should setup advanced test environment', async () => {
|
||||
await testBunqAccount.init();
|
||||
|
||||
// Get primary account
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
primaryAccount = accounts[0];
|
||||
|
||||
console.log('Advanced test environment setup complete');
|
||||
@@ -389,7 +389,7 @@ tap.test('should test travel mode', async () => {
|
||||
|
||||
tap.test('should cleanup advanced test resources', async () => {
|
||||
// Clean up any created resources
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
|
||||
// Close any test accounts created (except primary)
|
||||
for (const account of accounts) {
|
||||
|
@@ -25,7 +25,7 @@ tap.test('should setup error test environment', async () => {
|
||||
await testBunqAccount.init();
|
||||
|
||||
// Get primary account
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
primaryAccount = accounts[0];
|
||||
|
||||
expect(primaryAccount).toBeInstanceOf(bunq.BunqMonetaryAccount);
|
||||
@@ -283,7 +283,7 @@ tap.test('should test error recovery strategies', async () => {
|
||||
}
|
||||
|
||||
const accounts = await retryableOperation();
|
||||
expect(accounts).toBeArray();
|
||||
expect(accounts.accounts).toBeArray();
|
||||
console.log('Error recovery with retry successful');
|
||||
|
||||
// 2. Recover from expired session
|
||||
|
@@ -26,7 +26,7 @@ tap.test('should setup payment test environment', async () => {
|
||||
await testBunqAccount.init();
|
||||
|
||||
// Get primary account
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
primaryAccount = accounts[0];
|
||||
|
||||
expect(primaryAccount).toBeInstanceOf(bunq.BunqMonetaryAccount);
|
||||
|
@@ -27,7 +27,7 @@ tap.test('should create test setup with multiple accounts', async () => {
|
||||
await testBunqAccount.init();
|
||||
|
||||
// Get accounts
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
primaryAccount = accounts[0];
|
||||
|
||||
// Create a second account for testing transfers
|
||||
@@ -40,7 +40,7 @@ tap.test('should create test setup with multiple accounts', async () => {
|
||||
});
|
||||
|
||||
// Refresh accounts list
|
||||
const updatedAccounts = await testBunqAccount.getAccounts();
|
||||
const { accounts: updatedAccounts } = await testBunqAccount.getAccounts();
|
||||
secondaryAccount = updatedAccounts.find(acc => acc.id === newAccount.id) || primaryAccount;
|
||||
} catch (error) {
|
||||
console.log('Could not create secondary account, using primary for tests');
|
||||
|
@@ -84,7 +84,7 @@ tap.test('should test concurrent session usage', async () => {
|
||||
// Execute all operations concurrently
|
||||
const results = await Promise.all(operations);
|
||||
|
||||
expect(results[0]).toBeArray(); // Accounts
|
||||
expect(results[0].accounts).toBeArray(); // Accounts
|
||||
expect(results[1]).toBeDefined(); // User info
|
||||
expect(results[2]).toBeArray(); // Notification filters
|
||||
|
||||
@@ -172,7 +172,7 @@ tap.test('should test session token rotation', async () => {
|
||||
|
||||
// Make multiple requests to test token handling
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
expect(accounts).toBeArray();
|
||||
console.log(`Request ${i + 1} completed successfully`);
|
||||
|
||||
@@ -213,7 +213,7 @@ tap.test('should test session cleanup on error', async () => {
|
||||
}
|
||||
|
||||
// Ensure we can still use the session
|
||||
const accounts = await tempAccount.getAccounts();
|
||||
const { accounts } = await tempAccount.getAccounts();
|
||||
expect(accounts).toBeArray();
|
||||
console.log('Session still functional after error');
|
||||
|
||||
|
277
test/test.statements.ts
Normal file
277
test/test.statements.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as plugins from '../ts/bunq.plugins.js';
|
||||
import * as bunq from '../ts/index.js';
|
||||
|
||||
let testBunqAccount: bunq.BunqAccount;
|
||||
let sandboxApiKey: string;
|
||||
let primaryAccount: bunq.BunqMonetaryAccount;
|
||||
|
||||
tap.test('should setup statement test environment', async () => {
|
||||
// Create sandbox user
|
||||
const tempAccount = new bunq.BunqAccount({
|
||||
apiKey: '',
|
||||
deviceName: 'bunq-statement-test',
|
||||
environment: 'SANDBOX',
|
||||
});
|
||||
|
||||
sandboxApiKey = await tempAccount.createSandboxUser();
|
||||
|
||||
// Initialize bunq account
|
||||
testBunqAccount = new bunq.BunqAccount({
|
||||
apiKey: sandboxApiKey,
|
||||
deviceName: 'bunq-statement-test',
|
||||
environment: 'SANDBOX',
|
||||
});
|
||||
|
||||
await testBunqAccount.init();
|
||||
|
||||
// Get primary account
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
primaryAccount = accounts[0];
|
||||
|
||||
console.log('Statement test environment setup complete');
|
||||
console.log(`Using account: ${primaryAccount.description}`);
|
||||
});
|
||||
|
||||
tap.test('should create export builder with specific date range', async () => {
|
||||
const fromDate = new Date('2024-01-01');
|
||||
const toDate = new Date('2024-01-31');
|
||||
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
from: fromDate,
|
||||
to: toDate,
|
||||
includeTransactionAttachments: true
|
||||
});
|
||||
|
||||
expect(exportBuilder).toBeInstanceOf(bunq.ExportBuilder);
|
||||
|
||||
// The export builder should be properly configured
|
||||
const privateOptions = (exportBuilder as any).options;
|
||||
expect(privateOptions.dateStart).toEqual('01-01-2024');
|
||||
expect(privateOptions.dateEnd).toEqual('31-01-2024');
|
||||
expect(privateOptions.includeAttachment).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('should create export builder with monthly index from 0', async () => {
|
||||
// Test with 0-indexed month (0 = current month, 1 = last month, etc.)
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
monthlyIndexedFrom0: 2, // Two months ago
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
|
||||
expect(exportBuilder).toBeInstanceOf(bunq.ExportBuilder);
|
||||
|
||||
// The export builder should have dates for two months ago
|
||||
const privateOptions = (exportBuilder as any).options;
|
||||
const now = new Date();
|
||||
const twoMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 2, 1);
|
||||
const expectedStart = `01-${String(twoMonthsAgo.getMonth() + 1).padStart(2, '0')}-${twoMonthsAgo.getFullYear()}`;
|
||||
|
||||
expect(privateOptions.dateStart).toEqual(expectedStart);
|
||||
expect(privateOptions.includeAttachment).toBeFalse();
|
||||
});
|
||||
|
||||
tap.test('should create export builder with monthly index from 1', async () => {
|
||||
// Test with 1-indexed month (1 = last month, 2 = two months ago, etc.)
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
monthlyIndexedFrom1: 1, // Last month
|
||||
includeTransactionAttachments: true
|
||||
});
|
||||
|
||||
expect(exportBuilder).toBeInstanceOf(bunq.ExportBuilder);
|
||||
|
||||
// The export builder should have dates for last month
|
||||
const privateOptions = (exportBuilder as any).options;
|
||||
const now = new Date();
|
||||
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
||||
const expectedStart = `01-${String(lastMonth.getMonth() + 1).padStart(2, '0')}-${lastMonth.getFullYear()}`;
|
||||
|
||||
expect(privateOptions.dateStart).toEqual(expectedStart);
|
||||
expect(privateOptions.includeAttachment).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('should default to last month when no date options provided', async () => {
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
|
||||
expect(exportBuilder).toBeInstanceOf(bunq.ExportBuilder);
|
||||
|
||||
// Should default to last month
|
||||
const privateOptions = (exportBuilder as any).options;
|
||||
const now = new Date();
|
||||
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
||||
const expectedStart = `01-${String(lastMonth.getMonth() + 1).padStart(2, '0')}-${lastMonth.getFullYear()}`;
|
||||
|
||||
expect(privateOptions.dateStart).toEqual(expectedStart);
|
||||
});
|
||||
|
||||
tap.test('should create and download PDF statement', async () => {
|
||||
console.log('Creating PDF statement export...');
|
||||
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
monthlyIndexedFrom1: 1,
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
|
||||
// Configure as PDF
|
||||
exportBuilder.asPdf();
|
||||
|
||||
// Create the export
|
||||
const bunqExport = await exportBuilder.create();
|
||||
expect(bunqExport).toBeInstanceOf(bunq.BunqExport);
|
||||
expect(bunqExport.id).toBeTypeofNumber();
|
||||
console.log('Created PDF export with ID:', bunqExport.id);
|
||||
|
||||
// Wait for completion with status updates
|
||||
console.log('Waiting for PDF export to complete...');
|
||||
const maxWaitTime = 180000; // 3 minutes
|
||||
const startTime = Date.now();
|
||||
|
||||
while (true) {
|
||||
const status = await bunqExport.get();
|
||||
console.log(`Export status: ${status.status}`);
|
||||
|
||||
if (status.status === 'COMPLETED') {
|
||||
break;
|
||||
}
|
||||
|
||||
if (status.status === 'FAILED') {
|
||||
throw new Error('Export failed: ' + JSON.stringify(status));
|
||||
}
|
||||
|
||||
if (Date.now() - startTime > maxWaitTime) {
|
||||
throw new Error(`Export timed out after ${maxWaitTime/1000} seconds. Last status: ${status.status}`);
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds
|
||||
}
|
||||
|
||||
// Download to test directory
|
||||
console.log('Downloading PDF statement...');
|
||||
const testFilePath = '.nogit/teststatements/test-statement.pdf';
|
||||
await bunqExport.saveToFile(testFilePath);
|
||||
|
||||
// Verify file exists and has content
|
||||
const fileExists = await plugins.smartfile.fs.fileExists(testFilePath);
|
||||
expect(fileExists).toBeTrue();
|
||||
|
||||
const fileStats = await plugins.smartfile.fs.stat(testFilePath);
|
||||
console.log(`PDF Statement downloaded to: ${testFilePath} (${fileStats.size} bytes)`);
|
||||
expect(fileStats.size).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
tap.test('should create CSV statement with custom date range', async () => {
|
||||
console.log('Creating CSV statement export...');
|
||||
|
||||
// Use last month's date range to ensure it's in the past
|
||||
const now = new Date();
|
||||
const startOfMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
||||
const endOfMonth = new Date(now.getFullYear(), now.getMonth(), 0);
|
||||
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
from: startOfMonth,
|
||||
to: endOfMonth,
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
|
||||
// Configure as CSV
|
||||
const csvExport = await exportBuilder.asCsv().create();
|
||||
console.log('Created CSV export with ID:', csvExport.id);
|
||||
|
||||
// Wait for completion
|
||||
console.log('Waiting for CSV export to complete...');
|
||||
await csvExport.waitForCompletion(60000);
|
||||
|
||||
// Download to test directory
|
||||
console.log('Downloading CSV statement...');
|
||||
const testFilePath = '.nogit/teststatements/test-statement.csv';
|
||||
await csvExport.saveToFile(testFilePath);
|
||||
|
||||
// Verify file exists and has content
|
||||
const fileExists = await plugins.smartfile.fs.fileExists(testFilePath);
|
||||
expect(fileExists).toBeTrue();
|
||||
|
||||
const fileStats = await plugins.smartfile.fs.stat(testFilePath);
|
||||
console.log(`CSV statement downloaded to: ${testFilePath} (${fileStats.size} bytes)`);
|
||||
expect(fileStats.size).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
tap.test('should create MT940 statement', async () => {
|
||||
console.log('Creating MT940 statement export...');
|
||||
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
monthlyIndexedFrom0: 1, // Last month
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
|
||||
// Configure as MT940
|
||||
const mt940Export = await exportBuilder.asMt940().create();
|
||||
console.log('Created MT940 export with ID:', mt940Export.id);
|
||||
|
||||
// Wait for completion
|
||||
console.log('Waiting for MT940 export to complete...');
|
||||
await mt940Export.waitForCompletion(60000);
|
||||
|
||||
// Download to test directory
|
||||
console.log('Downloading MT940 statement...');
|
||||
const testFilePath = '.nogit/teststatements/test-statement.txt';
|
||||
await mt940Export.saveToFile(testFilePath);
|
||||
|
||||
// Verify file exists and has content
|
||||
const fileExists = await plugins.smartfile.fs.fileExists(testFilePath);
|
||||
expect(fileExists).toBeTrue();
|
||||
|
||||
const fileStats = await plugins.smartfile.fs.stat(testFilePath);
|
||||
console.log(`MT940 statement downloaded to: ${testFilePath} (${fileStats.size} bytes)`);
|
||||
expect(fileStats.size).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
tap.test('should handle edge cases for date calculations', async () => {
|
||||
// Mock the getAccountStatement method to test with a specific date
|
||||
const originalMethod = primaryAccount.getAccountStatement;
|
||||
|
||||
// Override the method temporarily for this test
|
||||
primaryAccount.getAccountStatement = function(optionsArg) {
|
||||
const exportBuilder = new bunq.ExportBuilder(this.bunqAccountRef, this);
|
||||
|
||||
// Simulate January 2024 as "now"
|
||||
const mockNow = new Date(2024, 0, 15); // January 15, 2024
|
||||
const targetDate = new Date(mockNow.getFullYear(), mockNow.getMonth() - 1, 1);
|
||||
const startDate = new Date(targetDate.getFullYear(), targetDate.getMonth(), 1);
|
||||
const endDate = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 0);
|
||||
|
||||
const formatDate = (date: Date): string => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${day}-${month}-${year}`;
|
||||
};
|
||||
|
||||
exportBuilder.dateRange(formatDate(startDate), formatDate(endDate));
|
||||
exportBuilder.includeAttachments(optionsArg.includeTransactionAttachments);
|
||||
|
||||
return exportBuilder;
|
||||
};
|
||||
|
||||
try {
|
||||
const exportBuilder = primaryAccount.getAccountStatement({
|
||||
monthlyIndexedFrom1: 1, // Last month (December 2023)
|
||||
includeTransactionAttachments: false
|
||||
});
|
||||
|
||||
const privateOptions = (exportBuilder as any).options;
|
||||
expect(privateOptions.dateStart).toEqual('01-12-2023');
|
||||
expect(privateOptions.dateEnd).toEqual('31-12-2023');
|
||||
} finally {
|
||||
// Restore original method
|
||||
primaryAccount.getAccountStatement = originalMethod;
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('should cleanup test environment', async () => {
|
||||
await testBunqAccount.stop();
|
||||
console.log('Test environment cleaned up');
|
||||
});
|
||||
|
||||
export default tap.start();
|
@@ -41,7 +41,7 @@ tap.test('should init the client', async () => {
|
||||
});
|
||||
|
||||
tap.test('should get accounts', async () => {
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
expect(accounts).toBeArray();
|
||||
expect(accounts.length).toBeGreaterThan(0);
|
||||
|
||||
@@ -56,7 +56,7 @@ tap.test('should get accounts', async () => {
|
||||
});
|
||||
|
||||
tap.test('should get transactions', async () => {
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
const account = accounts[0];
|
||||
|
||||
const transactions = await account.getTransactions();
|
||||
@@ -74,7 +74,7 @@ tap.test('should get transactions', async () => {
|
||||
});
|
||||
|
||||
tap.test('should test payment builder', async () => {
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
const account = accounts[0];
|
||||
|
||||
// Test payment builder without actually creating the payment
|
||||
|
@@ -27,7 +27,7 @@ tap.test('should setup webhook test environment', async () => {
|
||||
await testBunqAccount.init();
|
||||
|
||||
// Get primary account
|
||||
const accounts = await testBunqAccount.getAccounts();
|
||||
const { accounts } = await testBunqAccount.getAccounts();
|
||||
primaryAccount = accounts[0];
|
||||
|
||||
expect(primaryAccount).toBeInstanceOf(bunq.BunqMonetaryAccount);
|
||||
|
@@ -11,6 +11,7 @@ export interface IBunqConstructorOptions {
|
||||
environment: 'SANDBOX' | 'PRODUCTION';
|
||||
permittedIps?: string[];
|
||||
isOAuthToken?: boolean; // Set to true when using OAuth access token instead of API key
|
||||
dangerousOperations?: boolean; // Set to true to enable dangerous operations like closing accounts
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,7 +162,7 @@ export class BunqAccount {
|
||||
}
|
||||
|
||||
// Sandbox user creation doesn't require authentication
|
||||
const response = await plugins.smartrequest.request(
|
||||
const response = await fetch(
|
||||
'https://public-api.sandbox.bunq.com/v1/sandbox-user-person',
|
||||
{
|
||||
method: 'POST',
|
||||
@@ -170,12 +171,18 @@ export class BunqAccount {
|
||||
'User-Agent': 'bunq-api-client/1.0.0',
|
||||
'Cache-Control': 'no-cache'
|
||||
},
|
||||
requestBody: '{}'
|
||||
body: '{}'
|
||||
}
|
||||
);
|
||||
|
||||
if (response.body.Response && response.body.Response[0] && response.body.Response[0].ApiKey) {
|
||||
return response.body.Response[0].ApiKey.api_key;
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to create sandbox user: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (responseData.Response && responseData.Response[0] && responseData.Response[0].ApiKey) {
|
||||
return responseData.Response[0].ApiKey.api_key;
|
||||
}
|
||||
|
||||
throw new Error('Failed to create sandbox user');
|
||||
|
@@ -47,17 +47,19 @@ export class BunqAttachment {
|
||||
'X-Bunq-Client-Authentication': this.bunqAccount.apiContext.getSession().getContext().sessionToken
|
||||
};
|
||||
|
||||
const requestOptions = {
|
||||
method: 'PUT' as const,
|
||||
headers: headers,
|
||||
requestBody: options.body
|
||||
};
|
||||
|
||||
await plugins.smartrequest.request(
|
||||
const response = await fetch(
|
||||
`${this.bunqAccount.apiContext.getBaseUrl()}${uploadUrl}`,
|
||||
requestOptions
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: headers,
|
||||
body: options.body
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to upload attachment: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return attachmentUuid;
|
||||
}
|
||||
|
||||
@@ -67,7 +69,7 @@ export class BunqAttachment {
|
||||
public async getContent(attachmentUuid: string): Promise<Buffer> {
|
||||
await this.bunqAccount.apiContext.ensureValidSession();
|
||||
|
||||
const response = await plugins.smartrequest.request(
|
||||
const response = await fetch(
|
||||
`${this.bunqAccount.apiContext.getBaseUrl()}/v1/attachment-public/${attachmentUuid}/content`,
|
||||
{
|
||||
method: 'GET',
|
||||
@@ -77,7 +79,12 @@ export class BunqAttachment {
|
||||
}
|
||||
);
|
||||
|
||||
return Buffer.from(response.body);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get attachment: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
return Buffer.from(arrayBuffer);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -97,6 +97,12 @@ export class BunqCard {
|
||||
* Update card settings
|
||||
*/
|
||||
public async update(updates: any): Promise<void> {
|
||||
// Check if this is a dangerous operation
|
||||
if ((updates.status === 'CANCELLED' || updates.status === 'BLOCKED') &&
|
||||
!this.bunqAccount.options.dangerousOperations) {
|
||||
throw new Error('Dangerous operations are not enabled. Initialize the BunqAccount with dangerousOperations: true to allow cancelling or blocking cards.');
|
||||
}
|
||||
|
||||
await this.bunqAccount.apiContext.ensureValidSession();
|
||||
|
||||
const cardType = this.type === 'MASTERCARD' ? 'CardCredit' : 'CardDebit';
|
||||
|
@@ -111,27 +111,31 @@ export class BunqExport {
|
||||
throw new Error('Export ID not set');
|
||||
}
|
||||
|
||||
// First get the export details to find the attachment
|
||||
const exportDetails = await this.get();
|
||||
|
||||
if (!exportDetails.attachment || exportDetails.attachment.length === 0) {
|
||||
throw new Error('Export has no attachment');
|
||||
// Ensure the export is complete before downloading
|
||||
const status = await this.get();
|
||||
if (status.status !== 'COMPLETED') {
|
||||
throw new Error(`Export is not ready for download. Status: ${status.status}`);
|
||||
}
|
||||
|
||||
const attachmentUuid = exportDetails.attachment[0].attachment_public_uuid;
|
||||
|
||||
// Download the attachment content
|
||||
const response = await plugins.smartrequest.request(
|
||||
`${this.bunqAccount.apiContext.getBaseUrl()}/v1/attachment-public/${attachmentUuid}/content`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Bunq-Client-Authentication': this.bunqAccount.apiContext.getSession().getContext().sessionToken
|
||||
}
|
||||
}
|
||||
);
|
||||
// For PDF statements, use the /content endpoint directly
|
||||
const downloadUrl = `${this.bunqAccount.apiContext.getBaseUrl()}/v1/user/${this.bunqAccount.userId}/monetary-account/${this.monetaryAccount.id}/customer-statement/${this.id}/content`;
|
||||
|
||||
return Buffer.from(response.body);
|
||||
const response = await fetch(downloadUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Bunq-Client-Authentication': this.bunqAccount.apiContext.getSession().getContext().sessionToken,
|
||||
'User-Agent': 'bunq-api-client/1.0.0',
|
||||
'Cache-Control': 'no-cache'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const responseText = await response.text();
|
||||
throw new Error(`Failed to download export: HTTP ${response.status} - ${responseText}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
return Buffer.from(arrayBuffer);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,7 +155,7 @@ export class BunqExport {
|
||||
while (true) {
|
||||
const details = await this.get();
|
||||
|
||||
if (details.status === 'COMPLETE') {
|
||||
if (details.status === 'COMPLETED') {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -256,8 +260,16 @@ export class ExportBuilder {
|
||||
const startDate = new Date();
|
||||
startDate.setDate(startDate.getDate() - days);
|
||||
|
||||
this.options.dateStart = startDate.toISOString().split('T')[0];
|
||||
this.options.dateEnd = endDate.toISOString().split('T')[0];
|
||||
// Format as DD-MM-YYYY for bunq API
|
||||
const formatDate = (date: Date): string => {
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
return `${day}-${month}-${year}`;
|
||||
};
|
||||
|
||||
this.options.dateStart = formatDate(startDate);
|
||||
this.options.dateEnd = formatDate(endDate);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -269,8 +281,16 @@ export class ExportBuilder {
|
||||
const startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
||||
const endDate = new Date(now.getFullYear(), now.getMonth(), 0);
|
||||
|
||||
this.options.dateStart = startDate.toISOString().split('T')[0];
|
||||
this.options.dateEnd = endDate.toISOString().split('T')[0];
|
||||
// Format as DD-MM-YYYY for bunq API
|
||||
const formatDate = (date: Date): string => {
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
return `${day}-${month}-${year}`;
|
||||
};
|
||||
|
||||
this.options.dateStart = formatDate(startDate);
|
||||
this.options.dateEnd = formatDate(endDate);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -314,4 +334,24 @@ export class ExportBuilder {
|
||||
await bunqExport.waitForCompletion();
|
||||
await bunqExport.saveToFile(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and download export as Buffer
|
||||
*/
|
||||
public async download(): Promise<Buffer> {
|
||||
const bunqExport = await this.create();
|
||||
await bunqExport.waitForCompletion();
|
||||
return bunqExport.downloadContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and download export as ArrayBuffer
|
||||
*/
|
||||
public async downloadAsArrayBuffer(): Promise<ArrayBuffer> {
|
||||
const buffer = await this.download();
|
||||
return buffer.buffer.slice(
|
||||
buffer.byteOffset,
|
||||
buffer.byteOffset + buffer.byteLength
|
||||
);
|
||||
}
|
||||
}
|
@@ -27,6 +27,13 @@ export class BunqHttpClient {
|
||||
* Make an API request to bunq
|
||||
*/
|
||||
public async request<T = any>(options: IBunqRequestOptions): Promise<T> {
|
||||
return this.makeRequest<T>(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to make the actual request
|
||||
*/
|
||||
private async makeRequest<T = any>(options: IBunqRequestOptions): Promise<T> {
|
||||
const url = `${this.context.baseUrl}${options.endpoint}`;
|
||||
|
||||
// Prepare headers
|
||||
@@ -45,47 +52,65 @@ export class BunqHttpClient {
|
||||
);
|
||||
}
|
||||
|
||||
// Make the request
|
||||
const requestOptions: any = {
|
||||
method: options.method === 'LIST' ? 'GET' : options.method,
|
||||
headers: headers,
|
||||
requestBody: body
|
||||
};
|
||||
|
||||
if (options.params) {
|
||||
const params = new URLSearchParams();
|
||||
Object.entries(options.params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
params.append(key, String(value));
|
||||
// Create SmartRequest instance
|
||||
const request = plugins.smartrequest.SmartRequest.create()
|
||||
.url(url)
|
||||
.handle429Backoff({
|
||||
maxRetries: 3,
|
||||
respectRetryAfter: true,
|
||||
fallbackDelay: 1000,
|
||||
backoffFactor: 2,
|
||||
onRateLimit: (attempt, waitTime) => {
|
||||
console.log(`Rate limit hit, backing off for ${waitTime}ms (attempt ${attempt}/4)`);
|
||||
}
|
||||
});
|
||||
requestOptions.queryParams = params.toString();
|
||||
|
||||
// Add headers
|
||||
Object.entries(headers).forEach(([key, value]) => {
|
||||
request.header(key, value);
|
||||
});
|
||||
|
||||
// Add query parameters
|
||||
if (options.params) {
|
||||
request.query(options.params);
|
||||
}
|
||||
|
||||
// Add body if present
|
||||
if (body) {
|
||||
request.json(JSON.parse(body));
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await plugins.smartrequest.request(url, requestOptions);
|
||||
// Execute request based on method
|
||||
let response: plugins.smartrequest.ICoreResponse; // Response type from SmartRequest
|
||||
const method = options.method === 'LIST' ? 'GET' : options.method;
|
||||
|
||||
switch (method) {
|
||||
case 'GET':
|
||||
response = await request.get();
|
||||
break;
|
||||
case 'POST':
|
||||
response = await request.post();
|
||||
break;
|
||||
case 'PUT':
|
||||
response = await request.put();
|
||||
break;
|
||||
case 'DELETE':
|
||||
response = await request.delete();
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unsupported HTTP method: ${method}`);
|
||||
}
|
||||
|
||||
// Get response body as text for signature verification
|
||||
const responseText = await response.text();
|
||||
|
||||
// Verify response signature if we have server public key
|
||||
if (this.context.serverPublicKey) {
|
||||
// Convert headers to string-only format
|
||||
const stringHeaders: { [key: string]: string } = {};
|
||||
for (const [key, value] of Object.entries(response.headers)) {
|
||||
if (typeof value === 'string') {
|
||||
stringHeaders[key] = value;
|
||||
} else if (Array.isArray(value)) {
|
||||
stringHeaders[key] = value.join(', ');
|
||||
}
|
||||
}
|
||||
|
||||
// Convert body to string if needed for signature verification
|
||||
const bodyString = typeof response.body === 'string'
|
||||
? response.body
|
||||
: JSON.stringify(response.body);
|
||||
|
||||
const isValid = this.crypto.verifyResponseSignature(
|
||||
response.statusCode,
|
||||
stringHeaders,
|
||||
bodyString,
|
||||
response.status,
|
||||
response.headers as { [key: string]: string },
|
||||
responseText,
|
||||
this.context.serverPublicKey
|
||||
);
|
||||
|
||||
@@ -99,17 +124,21 @@ export class BunqHttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
// Parse response - smartrequest may already parse JSON automatically
|
||||
// Parse response
|
||||
let responseData;
|
||||
if (typeof response.body === 'string') {
|
||||
if (responseText) {
|
||||
try {
|
||||
responseData = JSON.parse(response.body);
|
||||
responseData = JSON.parse(responseText);
|
||||
} catch (parseError) {
|
||||
// If parsing fails and it's not a 2xx response, throw an HTTP error
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
throw new Error(`Failed to parse JSON response: ${parseError.message}`);
|
||||
}
|
||||
} else {
|
||||
// Response is already parsed
|
||||
responseData = response.body;
|
||||
// Empty response body
|
||||
responseData = {};
|
||||
}
|
||||
|
||||
// Check for errors
|
||||
@@ -117,6 +146,11 @@ export class BunqHttpClient {
|
||||
throw new BunqApiError(responseData.Error);
|
||||
}
|
||||
|
||||
// Check HTTP status
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return responseData;
|
||||
} catch (error) {
|
||||
if (error instanceof BunqApiError) {
|
||||
|
@@ -2,6 +2,7 @@ import * as plugins from './bunq.plugins.js';
|
||||
import { BunqAccount } from './bunq.classes.account.js';
|
||||
import { BunqTransaction } from './bunq.classes.transaction.js';
|
||||
import { BunqPayment } from './bunq.classes.payment.js';
|
||||
import { ExportBuilder } from './bunq.classes.export.js';
|
||||
import type { IBunqPaginationOptions, IBunqMonetaryAccountBank } from './bunq.interfaces.js';
|
||||
|
||||
export type TAccountType = 'bank' | 'joint' | 'savings' | 'external' | 'light' | 'card' | 'external_savings' | 'savings_external';
|
||||
@@ -111,18 +112,41 @@ export class BunqMonetaryAccount {
|
||||
|
||||
/**
|
||||
* gets all transactions on this account
|
||||
* @param options - Pagination options or a number for backward compatibility (treated as newer_id)
|
||||
*/
|
||||
public async getTransactions(startingIdArg: number | false = false): Promise<BunqTransaction[]> {
|
||||
const paginationOptions: IBunqPaginationOptions = {
|
||||
count: 200,
|
||||
newer_id: startingIdArg,
|
||||
public async getTransactions(options?: IBunqPaginationOptions | number | false): Promise<BunqTransaction[]> {
|
||||
let paginationOptions: IBunqPaginationOptions = {};
|
||||
|
||||
// Backward compatibility: if a number or false is passed, treat it as newer_id
|
||||
if (typeof options === 'number' || options === false) {
|
||||
paginationOptions.newer_id = options;
|
||||
} else if (options) {
|
||||
paginationOptions = { ...options };
|
||||
}
|
||||
|
||||
// Set default count if not specified
|
||||
if (!paginationOptions.count) {
|
||||
paginationOptions.count = 200;
|
||||
}
|
||||
|
||||
// Build clean pagination object - only include properties that are not false/undefined
|
||||
const cleanPaginationOptions: IBunqPaginationOptions = {
|
||||
count: paginationOptions.count,
|
||||
};
|
||||
|
||||
if (paginationOptions.newer_id !== undefined && paginationOptions.newer_id !== false) {
|
||||
cleanPaginationOptions.newer_id = paginationOptions.newer_id;
|
||||
}
|
||||
|
||||
if (paginationOptions.older_id !== undefined && paginationOptions.older_id !== false) {
|
||||
cleanPaginationOptions.older_id = paginationOptions.older_id;
|
||||
}
|
||||
|
||||
await this.bunqAccountRef.apiContext.ensureValidSession();
|
||||
|
||||
const response = await this.bunqAccountRef.getHttpClient().list(
|
||||
`/v1/user/${this.bunqAccountRef.userId}/monetary-account/${this.id}/payment`,
|
||||
paginationOptions
|
||||
cleanPaginationOptions
|
||||
);
|
||||
|
||||
const transactionsArray: BunqTransaction[] = [];
|
||||
@@ -147,6 +171,11 @@ export class BunqMonetaryAccount {
|
||||
* Update account settings
|
||||
*/
|
||||
public async update(updates: any): Promise<void> {
|
||||
// Check if this is a dangerous operation
|
||||
if (updates.status === 'CANCELLED' && !this.bunqAccountRef.options.dangerousOperations) {
|
||||
throw new Error('Dangerous operations are not enabled. Initialize the BunqAccount with dangerousOperations: true to allow cancelling accounts.');
|
||||
}
|
||||
|
||||
await this.bunqAccountRef.apiContext.ensureValidSession();
|
||||
|
||||
const endpoint = `/v1/user/${this.bunqAccountRef.userId}/monetary-account/${this.id}`;
|
||||
@@ -212,6 +241,10 @@ export class BunqMonetaryAccount {
|
||||
* Close this monetary account
|
||||
*/
|
||||
public async close(reason: string): Promise<void> {
|
||||
if (!this.bunqAccountRef.options.dangerousOperations) {
|
||||
throw new Error('Dangerous operations are not enabled. Initialize the BunqAccount with dangerousOperations: true to allow closing accounts.');
|
||||
}
|
||||
|
||||
await this.update({
|
||||
status: 'CANCELLED',
|
||||
sub_status: 'REDEMPTION_VOLUNTARY',
|
||||
@@ -219,4 +252,60 @@ export class BunqMonetaryAccount {
|
||||
reason_description: reason
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get account statement with flexible date options
|
||||
* @param optionsArg - Options for statement generation
|
||||
* @returns ExportBuilder instance for creating the statement
|
||||
*/
|
||||
public getAccountStatement(optionsArg: {
|
||||
from?: Date;
|
||||
to?: Date;
|
||||
monthlyIndexedFrom0?: number;
|
||||
monthlyIndexedFrom1?: number;
|
||||
includeTransactionAttachments: boolean;
|
||||
}): ExportBuilder {
|
||||
const exportBuilder = new ExportBuilder(this.bunqAccountRef, this);
|
||||
|
||||
// Determine date range based on provided options
|
||||
let startDate: Date;
|
||||
let endDate: Date;
|
||||
|
||||
if (optionsArg.from && optionsArg.to) {
|
||||
// Use provided date range
|
||||
startDate = optionsArg.from;
|
||||
endDate = optionsArg.to;
|
||||
} else if (optionsArg.monthlyIndexedFrom0 !== undefined) {
|
||||
// Calculate date range for 0-indexed month
|
||||
const now = new Date();
|
||||
const targetDate = new Date(now.getFullYear(), now.getMonth() - optionsArg.monthlyIndexedFrom0, 1);
|
||||
startDate = new Date(targetDate.getFullYear(), targetDate.getMonth(), 1);
|
||||
endDate = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 0);
|
||||
} else if (optionsArg.monthlyIndexedFrom1 !== undefined) {
|
||||
// Calculate date range for 1-indexed month (1 = last month, 2 = two months ago, etc.)
|
||||
const now = new Date();
|
||||
const targetDate = new Date(now.getFullYear(), now.getMonth() - optionsArg.monthlyIndexedFrom1, 1);
|
||||
startDate = new Date(targetDate.getFullYear(), targetDate.getMonth(), 1);
|
||||
endDate = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 0);
|
||||
} else {
|
||||
// Default to last month if no date options provided
|
||||
const now = new Date();
|
||||
startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
||||
endDate = new Date(now.getFullYear(), now.getMonth(), 0);
|
||||
}
|
||||
|
||||
// Format dates as DD-MM-YYYY (bunq API format)
|
||||
const formatDate = (date: Date): string => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${day}-${month}-${year}`;
|
||||
};
|
||||
|
||||
// Configure the export builder
|
||||
exportBuilder.dateRange(formatDate(startDate), formatDate(endDate));
|
||||
exportBuilder.includeAttachments(optionsArg.includeTransactionAttachments);
|
||||
|
||||
return exportBuilder;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user