# API Reference (Full)

---
source: /docs/api.md

# API Reference

Technical reference documentation for all Bkper APIs and SDKs. Use the REST API directly or choose a client library for your platform.

  - [REST API](https://bkper.com/docs/api/rest.md): Full OpenAPI reference for the Bkper REST API — endpoints, parameters, and response schemas.
  - [bkper-js](https://bkper.com/docs/api/bkper-js.md): JavaScript/TypeScript client library for Bkper — classes, interfaces, and type definitions.
  - [bkper-gs](https://bkper.com/docs/api/bkper-gs.md): Google Apps Script library for Bkper — use Bkper directly in Google Sheets and Apps Script projects.
  - [bkper-web-auth](https://bkper.com/docs/api/bkper-web-auth.md): Web authentication SDK for Bkper — OAuth flows, token management, and session handling.
  - [bkper-api-types](https://bkper.com/docs/api/bkper-api-types.md): TypeScript type definitions for the Bkper API — shared interfaces and enumerations.
  - [Design Tokens](https://bkper.com/docs/api/bkper-web-design.md): CSS design tokens — typography, spacing, colors, and theming for Bkper web applications.

---
source: /docs/api/bkper-api-types.md

# bkper-api-types

This package contains Typescript definitions for the [Bkper REST API](https://bkper.com/docs/#rest-api).

The types are generated based on the Bkper [Open API spec](https://bkper.com/docs/api/rest/openapi.json) using the [dtsgenerator](https://github.com/horiuchi/dtsgenerator) tool.

More information at the [Bkper Developer Documentation](https://bkper.com/docs/#rest-api)

[![npm (scoped)](https://img.shields.io/npm/v/@bkper/bkper-api-types?color=%235889e4)](https://www.npmjs.com/package/@bkper/bkper-api-types) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--api--types-blue?logo=github)](https://github.com/bkper/bkper-api-types)

### 1) Add the package:

```bash
npm i -S @bkper/bkper-api-types
```
### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

---
source: /docs/api/bkper-gs.md

# bkper-gs

[![clasp](https://img.shields.io/badge/built%20with-clasp-4285f4.svg)](https://github.com/google/clasp) [![npm (scoped)](https://img.shields.io/npm/v/@bkper/bkper-gs-types?color=%235889e4&label=types)](https://www.npmjs.com/package/@bkper/bkper-gs-types) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--gs-blue?logo=github)](https://github.com/bkper/bkper-gs)

## bkper-gs

`bkper-gs` library provides a simple and secure way to access the [Bkper REST API](https://bkper.com/docs/#rest-api) through [Google Apps Script](https://developers.google.com/apps-script/reference/) infrastructure.

With `bkper-gs` you can build [Apps and Bots](https://bkper.com/docs/) to your Books to create bookkeeping and accounting solutions on Google Workspace, such as the Bkper [Add-on for Google Sheets](https://workspace.google.com/marketplace/app/bkper/360398463400), simple automations or advanced solutions, and you can manage your scripts in the [Dashboard](https://script.google.com/home).

It works the same way your favorite Google Apps Script library works, providing a **BkperApp** entry point, like [CalendarApp](https://developers.google.com/apps-script/reference/calendar/calendar-app), [DocumentApp](https://developers.google.com/apps-script/reference/document/document-app), [SpreadsheetApp](https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app) and the like.

### Setup

This library is already published as an [Apps Script](https://script.google.com/d/1hMJszJGSUVZDB3vmsWrUZfRhY1UWbhS0SQ6Lzl06gm1zhBF3ioTM7mpJ/edit?usp=sharing), making it easy to include in your project. To add it to your script, do the following in the Apps Script code editor:

1. Click on the menu item "Resources > Libraries..."
2. In the "Add a Library" text box, enter the Script ID "**1hMJszJGSUVZDB3vmsWrUZfRhY1UWbhS0SQ6Lzl06gm1zhBF3ioTM7mpJ**" and click the "Select" button.
3. Choose a version in the dropdown box (usually best to pick the latest version).
4. Click the "Save" button.

#### Typescript Definitions for autocomplete:

To use TypeScript in the development of an Apps Script project, see the [Develop Apps Script using TypeScript](https://developers.google.com/apps-script/guides/typescript) as reference.

##### 1) Add the package:

```bash
npm i -S @bkper/bkper-gs-types
```
##### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

### Get a Book

The get a [Book](https://bkper.com/docs/bkper-gs/#book), use the parameter found on the URL accessed on [bkper.com](https://bkper.com):

![bookId](https://bkper.com/docs/images/bookId.png)

To get the Book name:

```javascript
function getBookName() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');
    var bookName = book.getName();
}
```

### Record Transactions

To record a simple transaction:

```javascript
function recordATransaction() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');
    book.record('#gas 63.23');
}
```

You can also record transactions in batch by passing an Array of strings as the [record](https://bkper.com/docs/bkper-gs/#book_record) method parameter:

```javascript
function batchRecordTransactions() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');

    var transactions = new Array();

    transactions.push('#breakfast 15.40');
    transactions.push('#lunch 27.45');
    transactions.push('#dinner 35.86');

    book.record(transactions);
}
```

The above code will send all records in a bulk. Very useful for importing large amount of data without the risk of reaching script limits.

### List Transactions

Each book is a large database and every interaction is done in terms of queries. Everytime you "select" an [Account](https://bkper.com/docs/bkper-gs/#account) by clicking on left menu at [bkper.com](https://bkper.com), you are actually filtering transactions by that [Account](https://bkper.com/docs/bkper-gs/#account).

When you retrieve transactions, the [getTransactions](https://bkper.com/docs/bkper-gs/#book_gettransactions) method returns an [TransactionIterator](https://bkper.com/docs/bkper-gs/#transactioniterator) to let you handle potentially large datasets:

```javascript
function listTransactions() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgKCtg6MLDA');

    //GetTransactions returns an interator to deal with potencial large datasets
    var transactionIterator = book.getTransactions("account:'Bank' after:01/04/2014");

    while (transactionIterator.hasNext()) {
        var transaction = transactionIterator.next();
        Logger.log(transaction.getDescription());
    }
}
```

Run the **queryTransactions** function, exchanging your bookId, with the same query, check the log output and you will see the same descriptions:

![Search log](https://bkper.com/docs/images/logSearch.png)

### List Accounts

You can access all Account objects, in a way similar to the left sidebar:

```javascript
function listAccounts() {
    //Open the book
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');

    var accounts = book.getAccounts();
    for (var i = 0; i < accounts.length; i++) {
        var account = accounts[i];
        if (account.isPermanent() && account.isActive()) {
            Logger.log(account.getName() + ': ' + account.getBalance());
        }
    }
}
```

---
source: /docs/api/bkper-js.md

# bkper-js

bkper-js library is a simple and secure way to access the [Bkper REST API](https://bkper.com/docs/api/rest) on Node.js and modern browsers.

It provides a set of classes and functions to interact with the Bkper API, including authentication, authorization, and data manipulation.

[![npm](https://img.shields.io/npm/v/bkper-js?color=%235889e4)](https://www.npmjs.com/package/bkper-js) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--js-blue?logo=github)](https://github.com/bkper/bkper-js)

### Add the package:

```bash
npm i -S bkper-js
```

### CDN / Browser

The simplest way to use bkper-js in a browser — no build tools, no npm, just a `<script>` tag and a valid access token. Works on **any domain**.

```html
<script src="https://cdn.jsdelivr.net/npm/bkper-js@2/dist/bkper.min.js"></script>
<script>
    const { Bkper } = bkperjs;

    async function listBooks(token) {
        Bkper.setConfig({
            oauthTokenProvider: async () => token,
        });
        const bkper = new Bkper();
        return await bkper.getBooks();
    }

    // Example: prompt for a token and list books
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('go').addEventListener('click', async () => {
            const token = document.getElementById('token').value;
            const books = await listBooks(token);
            document.getElementById('output').textContent = books.map(b => b.getName()).join('\n');
        });
    });
</script>

<input id="token" placeholder="Paste your access token" />
<button id="go">List Books</button>
<pre id="output"></pre>
```

Get an access token with the [Bkper CLI](https://www.npmjs.com/package/bkper):

```bash
bkper auth login   # one-time setup
bkper auth token   # prints a token (valid for 1 hour)
```

Pin to a specific version by replacing `@2` with e.g. `@2.31.0`.

### Node.js / CLI Scripts

For local scripts and CLI tools, use the [bkper](https://www.npmjs.com/package/bkper) CLI package for authentication:

```typescript
import { Bkper } from 'bkper-js';
import { getOAuthToken } from 'bkper';

// Configure with CLI authentication
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
});

// Create Bkper instance
const bkper = new Bkper();

// Get a book and work with it
const book = await bkper.getBook('your-book-id');
console.log(`Book: ${book.getName()}`);

// List all books
const books = await bkper.getBooks();
console.log(`You have ${books.length} books`);
```

First, login via CLI: `bkper auth login`

### npm + Bundler

If you are using a bundler (Vite, webpack, esbuild, etc.), install from npm and provide an access token the same way as the CDN example:

```typescript
import { Bkper } from 'bkper-js';

Bkper.setConfig({
    oauthTokenProvider: async () => 'your-access-token',
});

const bkper = new Bkper();
const books = await bkper.getBooks();
```

### Web Applications on \*.bkper.app

> **Note:** `@bkper/web-auth` **only works on `*.bkper.app` subdomains**. Its session cookies are scoped to the `.bkper.app` domain and will not work on any other domain. For apps on other domains, use the [CDN / Browser](#cdn--browser) approach with an access token instead.

For apps hosted on `*.bkper.app` subdomains, use the [@bkper/web-auth](https://www.npmjs.com/package/@bkper/web-auth) SDK for built-in OAuth login flow:

```typescript
import { Bkper } from 'bkper-js';
import { BkperAuth } from '@bkper/web-auth';

// Initialize authentication
const auth = new BkperAuth({
    onLoginSuccess: () => initializeApp(),
    onLoginRequired: () => showLoginButton(),
});

// Restore session on app load
await auth.init();

// Configure Bkper with web auth
Bkper.setConfig({
    oauthTokenProvider: async () => auth.getAccessToken(),
});

// Create Bkper instance and use it
const bkper = new Bkper();
const books = await bkper.getBooks();
```

See the [@bkper/web-auth documentation](https://bkper.com/docs/auth-sdk) for more details.

### API Key (Optional)

API keys are optional and only needed for dedicated quota limits. If not provided, requests use a shared managed quota via the Bkper API proxy.

```typescript
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
    apiKeyProvider: async () => process.env.BKPER_API_KEY, // Optional - for dedicated quota
});
```

---
source: /docs/api/bkper-web-auth.md

# @bkper/web-auth

[![npm](https://img.shields.io/npm/v/@bkper/web-auth?color=%235889e4)](https://www.npmjs.com/package/@bkper/web-auth) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--web--sdks-blue?logo=github)](https://github.com/bkper/bkper-web-sdks)

# @bkper/web-auth

OAuth authentication SDK for apps on the [Bkper Platform](https://bkper.com/docs/build/apps/overview) (`*.bkper.app` subdomains).

## Installation

```bash
bun add @bkper/web-auth
```
## Quick Start

```typescript
import { BkperAuth } from '@bkper/web-auth';

// Initialize client with callbacks
const auth = new BkperAuth({
    onLoginSuccess: () => {
        console.log('User authenticated!');
        loadUserData();
    },
    onLoginRequired: () => {
        console.log('Please sign in');
        showLoginButton();
    },
});

// Initialize authentication flow on app load
await auth.init();

// Get access token for API calls
const token = auth.getAccessToken();
if (token) {
    fetch('/api/data', {
        headers: { Authorization: `Bearer ${token}` },
    });
}
```

## Handling Token Expiration

Access tokens expire and need to be refreshed. The recommended pattern is to handle authentication errors and retry:

```typescript
async function apiRequest(url: string, options: RequestInit = {}) {
    // Add auth header
    const token = auth.getAccessToken();
    options.headers = {
        ...options.headers,
        Authorization: `Bearer ${token}`,
    };

    const response = await fetch(url, options);

    // Handle expired token
    if (response.status === 403) {
        try {
            await auth.refresh();
            options.headers = {
                ...options.headers,
                Authorization: `Bearer ${auth.getAccessToken()}`,
            };
            return fetch(url, options); // Retry once
        } catch (error) {
            // Refresh failed - the onError callback will be triggered
            // Handle the error appropriately (e.g., redirect to login, show error message)
            throw error;
        }
    }

    return response;
}
```

## What's Included

-   OAuth authentication SDK for apps on `*.bkper.app` subdomains
-   Callback-based API for authentication events
-   OAuth flow with in-memory token management
-   Token refresh mechanism
-   TypeScript support with full type definitions

## How It Works

**Session Persistence:**

-   Access tokens are stored in-memory (cleared on page refresh)
-   Sessions persist via HTTP-only cookies scoped to the `.bkper.app` domain
-   Call `init()` on app load to restore the session from cookies

> **Note:** This SDK only works for apps hosted on `*.bkper.app` subdomains. For apps on other domains, use a valid access token directly with [bkper-js](https://github.com/bkper/bkper-js#cdn--browser).

**Security:**

-   HTTP-only cookies protect refresh tokens from XSS
-   In-memory access tokens minimize exposure

## TypeScript Support

This package is written in TypeScript and provides full type definitions out of the box. All public APIs are fully typed, including callbacks and configuration options.

```typescript
import { BkperAuth, BkperAuthConfig } from '@bkper/web-auth';

const config: BkperAuthConfig = {
    onLoginSuccess: () => console.log('Authenticated'),
    onError: error => console.error('Auth error:', error),
};

const auth = new BkperAuth(config);
```

## Browser Compatibility

This package requires a modern browser with support for:

-   [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#browser_compatibility) for HTTP requests
-   [Location API](https://developer.mozilla.org/en-US/docs/Web/API/Location) for login/logout redirects

The app must be deployed to a `*.bkper.app` subdomain for session cookies to work.

---
source: /docs/api/bkper-web-design.md

# Design Tokens

[![npm](https://img.shields.io/npm/v/@bkper/web-design?color=%235889e4)](https://www.npmjs.com/package/@bkper/web-design) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--web--sdks-blue?logo=github)](https://github.com/bkper/bkper-web-sdks)

# @bkper/web-design

Bkper's design system - CSS variables, tokens, and themes.

## Installation

```bash
npm install @bkper/web-design
```

## Usage

Import in your build system:

```css
@import '@bkper/web-design';
```

Or link directly in HTML:

```html
<link rel="stylesheet" href="node_modules/@bkper/web-design/src/bkper.css" />
```

Alternatively, skip installation and link directly to a hosted version (CDN):

```html
<link rel="stylesheet" href="https://bkper.app/design/v2/style.css" />
```

Note: The CDN serves the most recent npm release.

## Web Awesome Integration

This package works standalone with sensible default values. If [Web Awesome](https://www.webawesome.com/) is loaded, Bkper tokens will automatically inherit from Web Awesome's design system for seamless integration.

## Design Tokens

<!-- TOKENS:START -->

### Typography

| Token | Default | Web Awesome Fallback |
| :--- | :--- | :--- |
| `--bkper-font-family` | `ui-sans-serif, system-ui, sans-serif` | `--wa-font-family-body` |
| `--bkper-font-family-code` | `ui-monospace, monospace` | `--wa-font-family-code` |
| `--bkper-font-size-x-small` | `0.75rem` | `--wa-font-size-xs` |
| `--bkper-font-size-small` | `0.85rem` | — |
| `--bkper-font-size-medium` | `1rem` | `--wa-font-size-m` |
| `--bkper-font-size-large` | `1.25rem` | `--wa-font-size-l` |
| `--bkper-font-weight-bold` | `600` | `--wa-font-weight-bold` |
| `--bkper-line-height-normal` | `1.8` | — |

### Border

| Token | Default | Web Awesome Fallback |
| :--- | :--- | :--- |
| `--bkper-border` | `1px solid var(--bkper-color-border)` | — |
| `--bkper-border-radius` | `0.375rem` | `--wa-border-radius-m` |

### Spacing

| Token | Default | Web Awesome Fallback |
| :--- | :--- | :--- |
| `--bkper-spacing-3x-small` | `0.125rem` | `--wa-space-3xs` |
| `--bkper-spacing-2x-small` | `0.25rem` | `--wa-space-2xs` |
| `--bkper-spacing-x-small` | `0.5rem` | `--wa-space-xs` |
| `--bkper-spacing-small` | `0.75rem` | `--wa-space-s` |
| `--bkper-spacing-medium` | `1rem` | `--wa-space-m` |
| `--bkper-spacing-large` | `1.5rem` | `--wa-space-l` |
| `--bkper-spacing-x-large` | `2rem` | `--wa-space-xl` |
| `--bkper-spacing-2x-large` | `2.5rem` | `--wa-space-2xl` |
| `--bkper-spacing-3x-large` | `3rem` | `--wa-space-3xl` |
| `--bkper-spacing-4x-large` | `4rem` | `--wa-space-4xl` |

### Color

| Token | Default | Web Awesome Fallback |
| :--- | :--- | :--- |
| `--bkper-color-black` | `#1b1d26` | — |
| `--bkper-color-white` | `#f1f2f3` | — |
| `--bkper-color-primary` | `#0071ec` | `--wa-color-brand-50` |
| `--bkper-color-success` | `#00883c` | `--wa-color-success-50` |
| `--bkper-color-danger` | `#dc3146` | `--wa-color-danger-50` |
| `--bkper-color-warning` | `#b45f04` | `--wa-color-warning-50` |
| `--bkper-color-focus` | `#3e96ff` | `--wa-color-focus` |

### Contextual Colors

These tokens change between light and dark themes.

| Token | Light | Dark | Web Awesome Fallback |
| :--- | :--- | :--- | :--- |
| `--bkper-color-text` | `var(--bkper-color-black)` | `var(--bkper-color-white)` | `--wa-color-text-normal` |
| `--bkper-color-link` | `#0053c0` | `#6eb3ff` | `--wa-color-text-link` |
| `--bkper-color-background` | `white` | `#101219` | `--wa-color-surface-default` |
| `--bkper-color-border` | `#e4e5e9` | `#2f323f` | `--wa-color-surface-border` |
| `--bkper-color-neutral` | `#2f323f` | `#e4e5e9` | `--wa-color-neutral-20` |

#### Account Type Colors

Five color families map to Bkper account types, each at three intensity levels. Values change between themes for optimal contrast.

**Grey — Neutral**

| Level | Token | Light | Dark |
| :--- | :--- | :--- | :--- |
| low | `--bkper-color-grey-low` | `#f5f5f5` | `#3A3A3A` |
| medium | `--bkper-color-grey-medium` | `#ccc` | `#6d6d6d` |
| high | `--bkper-color-grey-high` | `#3A3A3A` | `#bfb8b8` |

**Blue — Assets**

| Level | Token | Light | Dark |
| :--- | :--- | :--- | :--- |
| low | `--bkper-color-blue-low` | `#dfedf6` | `#1d4268` |
| medium | `--bkper-color-blue-medium` | `#afd4e9` | `#3478bc` |
| high | `--bkper-color-blue-high` | `#3478bc` | `#50a4d9` |

**Yellow — Liabilities**

| Level | Token | Light | Dark |
| :--- | :--- | :--- | :--- |
| low | `--bkper-color-yellow-low` | `#fef3d8` | `#664900` |
| medium | `--bkper-color-yellow-medium` | `#fce39c` | `#cc9200` |
| high | `--bkper-color-yellow-high` | `#cc9200` | `#e3bb56` |

**Green — Incoming**

| Level | Token | Light | Dark |
| :--- | :--- | :--- | :--- |
| low | `--bkper-color-green-low` | `#e2f3e7` | `#0d3514` |
| medium | `--bkper-color-green-medium` | `#b8e0c3` | `#228c33` |
| high | `--bkper-color-green-high` | `#228c33` | `#36cf64` |

**Red — Outgoing**

| Level | Token | Light | Dark |
| :--- | :--- | :--- | :--- |
| low | `--bkper-color-red-low` | `#f6deda` | `#631b13` |
| medium | `--bkper-color-red-medium` | `#eebbb4` | `#bf4436` |
| high | `--bkper-color-red-high` | `#bf4436` | `#eb7763` |

### Deprecated Tokens

These aliases are kept for backward compatibility. Use the replacement token instead.

| Deprecated Token | Replacement |
| :--- | :--- |
| `--bkper-font-color-default` | `--bkper-color-text` |
| `--bkper-border-color` | `--bkper-color-border` |
| `--bkper-background-color` | `--bkper-color-background` |
| `--bkper-link-color` | `--bkper-color-link` |

<!-- TOKENS:END -->

---
source: /docs/api/bkper-api-types.md

# bkper-api-types

> TypeScript type definitions for the Bkper API — shared interfaces and enumerations.

This package contains Typescript definitions for the [Bkper REST API](https://bkper.com/docs/#rest-api).

The types are generated based on the Bkper [Open API spec](https://bkper.com/docs/api/rest/openapi.json) using the [dtsgenerator](https://github.com/horiuchi/dtsgenerator) tool.

More information at the [Bkper Developer Documentation](https://bkper.com/docs/#rest-api)

[![npm (scoped)](https://img.shields.io/npm/v/@bkper/bkper-api-types?color=%235889e4)](https://www.npmjs.com/package/@bkper/bkper-api-types) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--api--types-blue?logo=github)](https://github.com/bkper/bkper-api-types)

### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

## Interfaces

### Account

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `archived?`: `boolean` — Archived accounts are kept for history
- `balance?`: `string` — The running balance of the account at the transaction date.
- `balanceVerified?`: `boolean` — Whether the account balance has been verified/audited
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `credit?`: `boolean` — Credit nature or Debit otherwise
- `groups?`: `bkper.Group[]` — The groups of the account
- `hasTransactionPosted?`: `boolean` — Whether the account has any transactions posted
- `id?`: `string` — The unique id that identifies the Account in the Book
- `name?`: `string` — The name of the Account
- `normalizedName?`: `string` — The name of the Account, lowercase, without spaces or special characters
- `permanent?`: `boolean` — Permanent are such as bank accounts, customers or the like
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Account
- `type?`: `"ASSET" | "LIABILITY" | "INCOMING" | "OUTGOING"` — The type of the account
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### AccountBalances

**Properties:**

- `archived?`: `boolean`
- `balances?`: `bkper.Balance[]`
- `credit?`: `boolean`
- `cumulativeBalance?`: `string`
- `cumulativeCredit?`: `string`
- `cumulativeDebit?`: `string`
- `empty?`: `boolean`
- `name?`: `string`
- `normalizedName?`: `string`
- `periodBalance?`: `string`
- `periodCredit?`: `string`
- `periodDebit?`: `string`
- `permanent?`: `boolean`
- `properties?`: `{ [name: string]: string }`

### AccountList

**Properties:**

- `items?`: `bkper.Account[]` — List items

### Agent

**Properties:**

- `id?`: `string` — The agent id
- `logo?`: `string` — The agent logo. Public url or Base64 encoded
- `logoDark?`: `string` — The agent logo on dark mode. Public url or Base64 encoded
- `name?`: `string` — The agent name

### App

**Properties:**

- `apiVersion?`: `"v0" | "v1" | "v2" | "v3" | "v4" | "v5"` — The API version of the event payload
- `clientId?`: `string` — The Google OAuth Client ID
- `clientSecret?`: `string` — The Google OAuth Client Secret
- `connectable?`: `boolean` — Whether this app is connectable by a user
- `deprecated?`: `boolean` — Whether the app is deprecated
- `description?`: `string` — The App description
- `developers?`: `string` — The developers (usernames and domain patterns), comma or space separated
- `events?`: `("FILE_CREATED" | "FILE_UPDATED" | "TRANSACTION_CREATED" | "TRANSACTION_UPDATED" | "TRANSACTION_DELETED" | "TRANSACTION_POSTED" | "TRANSACTION_CHECKED" | "TRANSACTION_UNCHECKED" | "TRANSACTION_RESTORED" | "ACCOUNT_CREATED" | "ACCOUNT_UPDATED" | "ACCOUNT_DELETED" | "QUERY_CREATED" | "QUERY_UPDATED" | "QUERY_DELETED" | "GROUP_CREATED" | "GROUP_UPDATED" | "GROUP_DELETED" | "COMMENT_CREATED" | "COMMENT_DELETED" | "COLLABORATOR_ADDED" | "COLLABORATOR_UPDATED" | "COLLABORATOR_REMOVED" | "INTEGRATION_CREATED" | "INTEGRATION_UPDATED" | "INTEGRATION_DELETED" | "BOOK_CREATED" | "BOOK_AUDITED" | "BOOK_UPDATED" | "BOOK_DELETED")[]` — Event types the App listen to
- `filePatterns?`: `string[]` — File patterns the App handles - wildcard accepted. E.g. *.pdf, *-bank.csv
- `id?`: `string` — The unique agent id of the App - this can't be changed after created
- `installable?`: `boolean` — Whether this app is installable in a book
- `logoUrl?`: `string` — The App logo url
- `logoUrlDark?`: `string` — The App logo url in dark mode
- `menuPopupHeight?`: `string` — The menu popup window height
- `menuPopupWidth?`: `string` — The menu popup window width
- `menuText?`: `string` — The contex menu text - default to the App name
- `menuUrl?`: `string` — The context menu url
- `menuUrlDev?`: `string` — The context menu url in dev mode
- `name?`: `string` — The App name
- `ownerEmail?`: `string` — The owner user email
- `ownerId?`: `string` — The owner user id
- `ownerLogoUrl?`: `string` — The owner company logo url
- `ownerName?`: `string` — The owner company name
- `ownerWebsite?`: `string` — The owner company website url
- `propertiesSchema?`: `bkper.AppPropertiesSchema`
- `published?`: `boolean` — Whether this app is already published
- `readme?`: `string` — The readme.md file as string
- `readmeMd?`: `string` — The readme.md file as raw markdown string
- `repoPrivate?`: `boolean` — Whether the code repository is private
- `repoUrl?`: `string` — The code repository url
- `scopes?`: `string[]` — The Google OAuth Scopes used by the app
- `users?`: `string` — The users (usernames and domain patterns) to enable the App while not yet published
- `webhookUrl?`: `string` — The Webhook endpoint URL to listen for book events
- `webhookUrlDev?`: `string` — The Webhook endpoint URL to listen for book events in dev mode
- `website?`: `string` — The App website url

### AppList

**Properties:**

- `items?`: `bkper.App[]`

### AppPropertiesSchema

**Properties:**

- `account?`: `bkper.AppPropertySchema`
- `book?`: `bkper.AppPropertySchema`
- `group?`: `bkper.AppPropertySchema`
- `transaction?`: `bkper.AppPropertySchema`

### AppPropertySchema

**Properties:**

- `keys?`: `string[]` — The property keys schema
- `values?`: `string[]` — The property values schema

### Backlog

**Properties:**

- `count?`: `number`

### Balance

**Properties:**

- `cumulativeBalance?`: `string`
- `cumulativeCredit?`: `string`
- `cumulativeDebit?`: `string`
- `day?`: `number`
- `fuzzyDate?`: `number`
- `month?`: `number`
- `periodBalance?`: `string`
- `periodCredit?`: `string`
- `periodDebit?`: `string`
- `year?`: `number`

### Balances

**Properties:**

- `accountBalances?`: `bkper.AccountBalances[]`
- `balancesUrl?`: `string`
- `groupBalances?`: `bkper.GroupBalances[]`
- `nextRange?`: `string`
- `periodicity?`: `"DAILY" | "MONTHLY" | "YEARLY"`
- `previousRange?`: `string`
- `range?`: `string`
- `rangeBeginLabel?`: `string`
- `rangeEndLabel?`: `string`

### Billing

**Properties:**

- `adminEmail?`: `string` — The billing admin email for the user's billing account
- `daysLeftInTrial?`: `number` — How many days the user has left in the trial period
- `email?`: `string` — The user's email address
- `enabled?`: `boolean` — True if billing is enabled for the user
- `hostedDomain?`: `string` — The user hosted domain
- `plan?`: `string` — The user's current plan
- `planOverdue?`: `boolean` — True if subscription payment is overdue
- `startedTrial?`: `boolean` — True if the user has started the trial period
- `totalTransactionsThisMonth?`: `number` — User-level total transactions this month
- `totalTransactionsThisYear?`: `number` — User-level total transactions this year

### Book

**Properties:**

- `accounts?`: `bkper.Account[]` — The book Accounts
- `agentId?`: `string` — The id of agent that created the resource
- `autoPost?`: `boolean` — Tells if the Book has auto post enabled
- `closingDate?`: `string` — The book closing date, in ISO format yyyy-MM-dd. Transactions on or before this date are closed for the period
- `collection?`: `bkper.Collection`
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `datePattern?`: `string` — The date pattern of the Book. Example: dd/MM/yyyy
- `decimalSeparator?`: `"DOT" | "COMMA"` — The decimal separator of the Book
- `fractionDigits?`: `number` — The number of fraction digits (decimal places) of the Book. E.g. 2 for ####.##, 4 for ####.####
- `groups?`: `bkper.Group[]` — The book account Groups
- `id?`: `string` — The unique id that identifies the Book in the system. Found at bookId url param
- `lastUpdateMs?`: `string` — The last update date of the Book, in milliseconds
- `lockDate?`: `string` — The book lock date, in ISO format yyyy-MM-dd. Transactions on or before this date are locked
- `logoUrl?`: `string` — The logo URL of the book owner's custom domain
- `name?`: `string` — The name of the Book
- `ownerName?`: `string` — The Book owner username
- `pageSize?`: `number` — The transactions pagination page size
- `period?`: `"MONTH" | "QUARTER" | "YEAR"` — The period slice for balances visualization
- `periodStartMonth?`: `"JANUARY" | "FEBRUARY" | "MARCH" | "APRIL" | "MAY" | "JUNE" | "JULY" | "AUGUST" | "SEPTEMBER" | "OCTOBER" | "NOVEMBER" | "DECEMBER"` — The start month when YEAR period set
- `permission?`: `"OWNER" | "EDITOR" | "POSTER" | "RECORDER" | "VIEWER" | "NONE"` — The Permission the current user has in the Book
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Book
- `timeZone?`: `string` — The time zone of the Book, in IANA format. E.g. America/New_York, Europe/London
- `timeZoneOffset?`: `number` — The time zone offset of the Book, in minutes
- `totalTransactions?`: `number` — The total transactions posted
- `totalTransactionsCurrentMonth?`: `number` — The total transactions posted on current month
- `totalTransactionsCurrentYear?`: `number` — The total transactions posted on current year
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `visibility?`: `"PUBLIC" | "PRIVATE"` — The Visibility of the Book

### BookList

**Properties:**

- `items?`: `bkper.Book[]` — List items

### BotResponse

**Properties:**

- `agentId?`: `string`
- `createdAt?`: `string`
- `message?`: `string`
- `type?`: `"INFO" | "WARNING" | "ERROR"`

### Collaborator

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `email?`: `string` — The email of the Collaborator
- `id?`: `string` — The unique id that identifies the Collaborator in the Book
- `permission?`: `"OWNER" | "EDITOR" | "POSTER" | "RECORDER" | "VIEWER" | "NONE"` — The permission the Collaborator has in the Book
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### CollaboratorPayloadCollection

**Properties:**

- `items?`: `bkper.Collaborator[]`

### Collection

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `books?`: `bkper.Book[]` — The Books contained in the Collection
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `id?`: `string` — The unique id of the Collection
- `name?`: `string` — The name of the Collection
- `ownerUsername?`: `string` — The username of the Collection owner
- `permission?`: `"OWNER" | "EDITOR" | "POSTER" | "RECORDER" | "VIEWER" | "NONE"` — The permission the current user has in the Collection. E.g. OWNER, EDITOR, NONE
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### CollectionList

**Properties:**

- `items?`: `bkper.Collection[]` — List items

### Connection

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `dateAddedMs?`: `string`
- `email?`: `string`
- `id?`: `string`
- `logo?`: `string`
- `name?`: `string`
- `properties?`: `{ [name: string]: string }`
- `type?`: `"APP" | "BANK"`
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `userId?`: `string`
- `uuid?`: `string`

### ConnectionList

**Properties:**

- `items?`: `bkper.Connection[]` — List items

### Count

**Properties:**

- `day?`: `number`
- `fuzzyDate?`: `number`
- `month?`: `number`
- `total?`: `number`
- `year?`: `number`

### Counts

**Properties:**

- `posted?`: `bkper.Count[]`
- `trashed?`: `bkper.Count[]`

### Event

**Properties:**

- `agent?`: `bkper.Agent`
- `book?`: `bkper.Book`
- `bookId?`: `string` — The id of the Book associated to the Event
- `botResponses?`: `bkper.BotResponse[]` — The list of bot responses associated to the Event
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `createdOn?`: `string` — The creation date time on RFC3339 format
- `data?`: `bkper.EventData`
- `id?`: `string` — The unique id that identifies the Event
- `resource?`: `string` — The resource associated to the Event
- `type?`: `"FILE_CREATED" | "FILE_UPDATED" | "TRANSACTION_CREATED" | "TRANSACTION_UPDATED" | "TRANSACTION_DELETED" | "TRANSACTION_POSTED" | "TRANSACTION_CHECKED" | "TRANSACTION_UNCHECKED" | "TRANSACTION_RESTORED" | "ACCOUNT_CREATED" | "ACCOUNT_UPDATED" | "ACCOUNT_DELETED" | "QUERY_CREATED" | "QUERY_UPDATED" | "QUERY_DELETED" | "GROUP_CREATED" | "GROUP_UPDATED" | "GROUP_DELETED" | "COMMENT_CREATED" | "COMMENT_DELETED" | "COLLABORATOR_ADDED" | "COLLABORATOR_UPDATED" | "COLLABORATOR_REMOVED" | "INTEGRATION_CREATED" | "INTEGRATION_UPDATED" | "INTEGRATION_DELETED" | "BOOK_CREATED" | "BOOK_AUDITED" | "BOOK_UPDATED" | "BOOK_DELETED"` — The type of the Event
- `user?`: `bkper.User`

### EventData

**Properties:**

- `object?`: `unknown`
- `previousAttributes?`: `{ [name: string]: string }` — The object previous attributes when updated

### EventList

**Properties:**

- `cursor?`: `string` — The cursor, for pagination
- `items?`: `bkper.Event[]` — List items

### File

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `content?`: `string` — The file content Base64 encoded
- `contentType?`: `string` — The file content type
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `id?`: `string` — The unique id that identifies the file in the book
- `name?`: `string` — The file name
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the File
- `size?`: `number` — The file size in bytes
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `url?`: `string` — The file serving url

### Group

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `credit?`: `boolean` — Whether the group has credit nature
- `hasAccounts?`: `boolean` — Whether the group has any accounts
- `hasGroups?`: `boolean` — Whether the group has any children groups
- `hidden?`: `boolean` — Whether the group is hidden on the transactions main menu
- `id?`: `string` — The unique id that identifies the Group in the Book
- `locked?`: `boolean` — Whether the group is locked by the Book owner
- `mixed?`: `boolean` — Whether the group has mixed types of accounts
- `name?`: `string` — The name of the Group
- `normalizedName?`: `string` — The name of the Group, lowercase, without spaces or special characters
- `parent?`: `bkper.Group`
- `permanent?`: `boolean` — Whether the group is permanent
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Group
- `type?`: `"ASSET" | "LIABILITY" | "INCOMING" | "OUTGOING"` — The type of the accounts in the group. E.g. ASSET, LIABILITY, INCOMING, OUTGOING
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### GroupBalances

**Properties:**

- `accountBalances?`: `bkper.AccountBalances[]`
- `balances?`: `bkper.Balance[]`
- `credit?`: `boolean`
- `cumulativeBalance?`: `string`
- `cumulativeCredit?`: `string`
- `cumulativeDebit?`: `string`
- `groupBalances?`: `bkper.GroupBalances[]`
- `name?`: `string`
- `normalizedName?`: `string`
- `periodBalance?`: `string`
- `periodCredit?`: `string`
- `periodDebit?`: `string`
- `permanent?`: `boolean`
- `properties?`: `{ [name: string]: string }`

### GroupList

**Properties:**

- `items?`: `bkper.Group[]` — List items

### Integration

**Properties:**

- `addedBy?`: `string`
- `agentId?`: `string` — The id of agent that created the resource
- `bookId?`: `string`
- `connectionId?`: `string`
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `dateAddedMs?`: `string`
- `id?`: `string`
- `lastUpdateMs?`: `string`
- `logo?`: `string`
- `logoDark?`: `string`
- `name?`: `string`
- `normalizedName?`: `string`
- `properties?`: `{ [name: string]: string }`
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `userId?`: `string`

### IntegrationList

**Properties:**

- `items?`: `bkper.Integration[]` — List items

### Query

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `id?`: `string` — The unique id that identifies the saved Query in the Book
- `query?`: `string` — The Query string to be executed
- `title?`: `string` — The title of the saved Query
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### QueryList

**Properties:**

- `items?`: `bkper.Query[]` — List items

### Template

**Properties:**

- `bookId?`: `string`
- `bookLink?`: `string`
- `category?`: `string`
- `description?`: `string`
- `imageUrl?`: `string`
- `name?`: `string`
- `sheetsLink?`: `string`
- `timesUsed?`: `number`

### TemplateList

**Properties:**

- `items?`: `bkper.Template[]` — List items

### Transaction

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `agentLogo?`: `string` — The logo of the agent that created the transaction
- `agentLogoDark?`: `string` — The logo in dark mode, of the agent that created the transaction
- `agentName?`: `string` — The name of the agent that created the transaction
- `amount?`: `string` — The amount on format ####.##
- `checked?`: `boolean` — Whether the transaction is checked
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `createdBy?`: `string` — The actor username that created the transaction
- `creditAccount?`: `bkper.Account`
- `date?`: `string` — The date on ISO format yyyy-MM-dd
- `dateFormatted?`: `string` — The date on format of the Book
- `dateValue?`: `number` — The date number representation on format YYYYMMDD
- `debitAccount?`: `bkper.Account`
- `description?`: `string` — The transaction description
- `draft?`: `boolean` — Whether the transaction is a draft
- `files?`: `bkper.File[]` — The files attached to the transaction
- `id?`: `string` — The unique id that identifies the transaction in the book
- `posted?`: `boolean` — Whether the transaction is already posted on accounts, otherwise is a draft
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Transaction
- `remoteIds?`: `string[]` — The transaction remote ids, to avoid duplication
- `tags?`: `string[]` — The transaction #hashtags
- `trashed?`: `boolean` — Whether the transaction is trashed
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `urls?`: `string[]` — The transaction urls

### TransactionList

**Properties:**

- `account?`: `string` — The account id when filtering by a single account. E.g. account='Bank'
- `cursor?`: `string` — The cursor, for pagination
- `items?`: `bkper.Transaction[]` — List items

### TransactionOperation

**Properties:**

- `accounts?`: `bkper.Account[]` — The affected accounts
- `transaction?`: `bkper.Transaction`

### Url

**Properties:**

- `url?`: `string`

### User

**Properties:**

- `avatarUrl?`: `string` — The user public avatar url
- `bankConnections?`: `boolean` — True if user already had any bank connection
- `billingAdminEmail?`: `string` — The billing admin email for this user's billing account
- `billingEnabled?`: `boolean` — True if billing is enabled for the user
- `daysLeftInTrial?`: `number` — How many days left in trial
- `email?`: `string` — The user email
- `free?`: `boolean` — True if user is in the free plan
- `fullName?`: `string` — The user full name
- `givenName?`: `string` — The user given name
- `hash?`: `string` — The user hash
- `hostedDomain?`: `string` — The user hosted domain
- `id?`: `string` — The user unique id
- `name?`: `string` — The user display name
- `plan?`: `string` — The user plan
- `planOverdue?`: `boolean` — True if subscription payment is overdue
- `startedTrial?`: `boolean` — True if user started trial
- `totalTransactionsThisMonth?`: `number` — User-level total transactions this month
- `totalTransactionsThisYear?`: `number` — User-level total transactions this year
- `username?`: `string` — The Bkper username of the user

---
source: /docs/api/bkper-gs.md

# bkper-gs

> Google Apps Script library for Bkper — use Bkper directly in Google Sheets and Apps Script projects.

[![clasp](https://img.shields.io/badge/built%20with-clasp-4285f4.svg)](https://github.com/google/clasp) [![npm (scoped)](https://img.shields.io/npm/v/@bkper/bkper-gs-types?color=%235889e4&label=types)](https://www.npmjs.com/package/@bkper/bkper-gs-types) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--gs-blue?logo=github)](https://github.com/bkper/bkper-gs)

## bkper-gs

`bkper-gs` library provides a simple and secure way to access the [Bkper REST API](https://bkper.com/docs/#rest-api) through [Google Apps Script](https://developers.google.com/apps-script/reference/) infrastructure.

With `bkper-gs` you can build [Apps and Bots](https://bkper.com/docs/) to your Books to create bookkeeping and accounting solutions on Google Workspace, such as the Bkper [Add-on for Google Sheets](https://workspace.google.com/marketplace/app/bkper/360398463400), simple automations or advanced solutions, and you can manage your scripts in the [Dashboard](https://script.google.com/home).

It works the same way your favorite Google Apps Script library works, providing a **BkperApp** entry point, like [CalendarApp](https://developers.google.com/apps-script/reference/calendar/calendar-app), [DocumentApp](https://developers.google.com/apps-script/reference/document/document-app), [SpreadsheetApp](https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app) and the like.

### Setup

This library is already published as an [Apps Script](https://script.google.com/d/1hMJszJGSUVZDB3vmsWrUZfRhY1UWbhS0SQ6Lzl06gm1zhBF3ioTM7mpJ/edit?usp=sharing), making it easy to include in your project. To add it to your script, do the following in the Apps Script code editor:

1. Click on the menu item "Resources > Libraries..."
2. In the "Add a Library" text box, enter the Script ID "**1hMJszJGSUVZDB3vmsWrUZfRhY1UWbhS0SQ6Lzl06gm1zhBF3ioTM7mpJ**" and click the "Select" button.
3. Choose a version in the dropdown box (usually best to pick the latest version).
4. Click the "Save" button.

#### Typescript Definitions for autocomplete:

To use TypeScript in the development of an Apps Script project, see the [Develop Apps Script using TypeScript](https://developers.google.com/apps-script/guides/typescript) as reference.

##### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

### Get a Book

The get a [Book](https://bkper.com/docs/bkper-gs/#book), use the parameter found on the URL accessed on [bkper.com](https://bkper.com):

![bookId](https://bkper.com/docs/images/bookId.png)

To get the Book name:

```javascript
function getBookName() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');
    var bookName = book.getName();
}
```

### Record Transactions

To record a simple transaction:

```javascript
function recordATransaction() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');
    book.record('#gas 63.23');
}
```

You can also record transactions in batch by passing an Array of strings as the [record](https://bkper.com/docs/bkper-gs/#book_record) method parameter:

```javascript
function batchRecordTransactions() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');

    var transactions = new Array();

    transactions.push('#breakfast 15.40');
    transactions.push('#lunch 27.45');
    transactions.push('#dinner 35.86');

    book.record(transactions);
}
```

The above code will send all records in a bulk. Very useful for importing large amount of data without the risk of reaching script limits.

### List Transactions

Each book is a large database and every interaction is done in terms of queries. Everytime you "select" an [Account](https://bkper.com/docs/bkper-gs/#account) by clicking on left menu at [bkper.com](https://bkper.com), you are actually filtering transactions by that [Account](https://bkper.com/docs/bkper-gs/#account).

When you retrieve transactions, the [getTransactions](https://bkper.com/docs/bkper-gs/#book_gettransactions) method returns an [TransactionIterator](https://bkper.com/docs/bkper-gs/#transactioniterator) to let you handle potentially large datasets:

```javascript
function listTransactions() {
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgKCtg6MLDA');

    //GetTransactions returns an interator to deal with potencial large datasets
    var transactionIterator = book.getTransactions("account:'Bank' after:01/04/2014");

    while (transactionIterator.hasNext()) {
        var transaction = transactionIterator.next();
        Logger.log(transaction.getDescription());
    }
}
```

Run the **queryTransactions** function, exchanging your bookId, with the same query, check the log output and you will see the same descriptions:

![Search log](https://bkper.com/docs/images/logSearch.png)

### List Accounts

You can access all Account objects, in a way similar to the left sidebar:

```javascript
function listAccounts() {
    //Open the book
    var book = BkperApp.getBook('agtzfmJrcGVyLWhyZHIOCxIGTGVkZ2VyGNKJAgw');

    var accounts = book.getAccounts();
    for (var i = 0; i < accounts.length; i++) {
        var account = accounts[i];
        if (account.isPermanent() && account.isActive()) {
            Logger.log(account.getName() + ': ' + account.getBalance());
        }
    }
}
```

## Interfaces

### Account

**Properties:**

- `payload`: `bkper.Account` — The underlying payload data for this resource

**Methods:**

- `addGroup(group: string | Bkper.Group)` → `Bkper.Account` — Add a group to the Account.
- `create()` → `Bkper.Account` — Perform create new account.
- `deleteProperty(key: string)` → `this` — Deletes a custom property.
- `getBalance()` → `Bkper.Amount` — Gets the balance on the current month, based on the credit nature of this Account.
- `getBalanceRaw()` → `Bkper.Amount` — Gets the raw balance on the current month, no matter the credit nature of this Account.
- `getDescription()` → `string` — ~~Deprecated: Use properties instead~~ Gets the account description
- `getGroups()` / `setGroups(groups: Bkper.Group[] | string[])` → `Bkper.Group[] (set: Bkper.Group[] | string[])` — Get the `Groups` of this account.
- `getId()` → `string` — Gets the account internal id.
- `getName()` / `setName(name: string)` → `string` — Gets the account name.
- `getNormalizedName()` → `string`
- `getProperties()` / `setProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the custom properties stored in this resource.
- `getProperty(keys: string[])` / `setProperty(key: string, value: string)` → `string` — Gets the property value for given keys. First property found will be retrieved.
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in this resource.
- `getType()` / `setType(type: Bkper.AccountType)` → `Bkper.AccountType`
- `getVisibleProperties()` / `setVisibleProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the visible custom properties stored in this resource.
Hidden properties (those ending with "_") are excluded from the result.
- `hasTransactionPosted()` → `boolean` — Tell if the Account has any transaction already posted.
- `isActive()` → `boolean` — ~~Deprecated: Use isArchived instead~~ Tell if this account is Active or otherwise Archived.
- `isArchived()` → `boolean` — Tell if this account is archived.
- `isCredit()` → `boolean` — Tell if the account has a Credit nature or Debit otherwise
- `isInGroup(group: string | Bkper.Group)` → `boolean` — Tell if this account is in the `Group`
- `isPermanent()` → `boolean` — Tell if the account is permanent.
- `json()` → `bkper.Account` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Bkper.Account` — Perform delete account.
- `removeGroup(group: string | Bkper.Group)` → `Bkper.Account` — Remove a group from the Account.
- `setArchived(archived: boolean)` → `Bkper.Account` — Set account archived/unarchived.
- `setVisibleProperty(key: string, value: string | null)` → `this` — Sets a custom property in this resource, filtering out hidden properties.
Hidden properties are those whose keys end with an underscore "_".
- `update()` → `Bkper.Account` — Perform update account, applying pending changes.

**hasTransactionPosted**

Accounts with transaction posted, even with zero balance, can only be archived.

**isCredit**

Credit accounts are just for representation purposes. It increase or decrease the absolute balance. It doesn't affect the overall balance or the behavior of the system.

The absolute balance of credit accounts increase when it participate as a credit/origin in a transaction. Its usually for Accounts that increase the balance of the assets, like revenue accounts.

```
        Crediting a credit
  Thus ---------------------> account increases its absolute balance
        Debiting a debit


        Debiting a credit
  Thus ---------------------> account decreases its absolute balance
        Crediting a debit
```

As a rule of thumb, and for simple understanding, almost all accounts are Debit nature (NOT credit), except the ones that "offers" amount for the books, like revenue accounts.

**isPermanent**

Permanent Accounts are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(accountancy)#Based_on_periodicity_of_flow)

Usually represents assets or tangibles, capable of being perceived by the senses or the mind, like bank accounts, money, debts and so on.

### AccountsDataTableBuilder

**Methods:**

- `archived(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether the archived accounts should included.
- `build()` → `any[][]`
- `groups(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether include account groups.
- `ids(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether include account ids.
- `properties(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether include custom account properties.

### Amount

**Methods:**

- `abs()` → `Bkper.Amount` — Returns an absolute Amount.
- `cmp(n: string | number | Bkper.Amount)` → `-1 | 0 | 1` — Compare
- `div(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Divide by
- `eq(n: string | number | Bkper.Amount)` → `boolean` — Equals to
- `gt(n: string | number | Bkper.Amount)` → `boolean` — Greater than
- `gte(n: string | number | Bkper.Amount)` → `boolean` — Greater than or equal
- `lt(n: string | number | Bkper.Amount)` → `boolean` — Less than
- `lte(n: string | number | Bkper.Amount)` → `boolean` — Less than or equal to
- `minus(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Minus
- `mod(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Modulo - the integer remainder of dividing this Amount by n.
- `plus(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Sum
- `round(dp?: number)` → `Bkper.Amount` — Round to a maximum of dp decimal places.
- `times(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Multiply
- `toFixed(dp?: number)` → `string` — Returns a string representing the value of this Amount in normal notation to a fixed number of decimal places dp.
- `toNumber()` → `number` — Returns a primitive number representing the value of this Amount.
- `toString()` → `string` — Returns a string representing the value of this Amount.

**mod**

Similar to % operator

### App

**Properties:**

- `payload`: `bkper.App` — The underlying payload data for this resource

**Methods:**

- `getDescription()` → `string`
- `getId()` → `string`
- `getName()` → `string`
- `json()` → `bkper.App` — Gets an immutable copy of the JSON payload for this resource.

### Backlog

**Properties:**

- `payload`: `bkper.Backlog` — The underlying payload data for this resource

**Methods:**

- `getCount()` → `number`
- `json()` → `bkper.Backlog` — Gets an immutable copy of the JSON payload for this resource.

### Balance

**Properties:**

- `payload`: `bkper.Balance` — The underlying payload data for this resource

**Methods:**

- `getCumulativeBalance()` → `Bkper.Amount` — The cumulative balance to the date, based on the credit nature of the container
- `getCumulativeBalanceRaw()` → `Bkper.Amount` — The raw cumulative balance to the date.
- `getCumulativeCredit()` → `Bkper.Amount` — The cumulative credit to the date.
- `getCumulativeDebit()` → `Bkper.Amount` — The cumulative debit to the date.
- `getDate()` → `Date` — Date object constructed based on `Book` time zone offset. Usefull for
- `getDay()` → `number` — The day of the balance. Days starts on 1 to 31.
- `getFuzzyDate()` → `number` — The Fuzzy Date of the balance, based on `Periodicity` of the `BalancesReport` query, composed by Year, Month and Day.
- `getMonth()` → `number` — The month of the balance. Months starts on 1 (January) to 12 (December)
- `getPeriodBalance()` → `Bkper.Amount` — The balance on the date period, based on credit nature of the container.
- `getPeriodBalanceRaw()` → `Bkper.Amount` — The raw balance on the date period.
- `getPeriodCredit()` → `Bkper.Amount` — The credit on the date period.
- `getPeriodDebit()` → `Bkper.Amount` — The debit on the date period.
- `getYear()` → `number` — The year of the balance
- `json()` → `bkper.Balance` — Gets an immutable copy of the JSON payload for this resource.

**getDate**

If Month or Day is zero, the date will be constructed with first Month (January) or Day (1).

**getDay**

Day can be 0 (zero) in case of Monthly or Early `Periodicity` of the `BalancesReport`

**getFuzzyDate**

The format is **YYYYMMDD**. Very usefull for ordering and indexing

Month and Day can be 0 (zero), depending on the granularity of the `Periodicity`.

*Example:*

**20180125** - 25, January, 2018 - DAILY Periodicity

**20180100** - January, 2018 - MONTHLY Periodicity

**20180000** - 2018 - YEARLY Periodicity

**getMonth**

Month can be 0 (zero) in case of Early `Periodicity` of the `BalancesReport`

### BalancesContainer

**Methods:**

- `addBalancesContainer(container: Bkper.BalancesContainer)` → `Bkper.BalancesContainer` — Adds an `Account` container to a `Group` container.
- `createDataTable()` → `Bkper.BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`
- `getAccount()` → `Bkper.Account` — The `Account` associated with this container
- `getAccountBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all `Account` `BalancesContainers`.
- `getBalances()` → `Bkper.Balance[]` — All `Balances` of the container
- `getBalancesContainer(name: string)` → `Bkper.BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all child `BalancesContainers`.
- `getBalancesReport()` → `Bkper.BalancesReport` — The parent BalancesReport of the container
- `getCumulativeBalance()` → `Bkper.Amount` — The cumulative balance to the date.
- `getCumulativeBalanceRaw()` → `Bkper.Amount` — The cumulative raw balance to the date.
- `getCumulativeBalanceRawText()` → `string` — The cumulative raw balance formatted according to `Book` decimal format and fraction digits.
- `getCumulativeBalanceText()` → `string` — The cumulative balance formatted according to `Book` decimal format and fraction digits.
- `getCumulativeCredit()` → `Bkper.Amount` — The cumulative credit to the date.
- `getCumulativeCreditText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getCumulativeDebit()` → `Bkper.Amount` — The cumulative debit to the date.
- `getCumulativeDebitText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getDepth()` → `number` — The depth in the parent chain up to the root.
- `getGroup()` → `Bkper.Group` — The `Group` associated with this container
- `getName()` → `string` — The `Account` or `Group` name
- `getNormalizedName()` → `string` — The `Account` or `Group` name without spaces or special characters.
- `getParent()` → `Bkper.BalancesContainer` — The parent BalanceContainer
- `getPeriodBalance()` → `Bkper.Amount` — The balance on the date period.
- `getPeriodBalanceRaw()` → `Bkper.Amount` — The raw balance on the date period.
- `getPeriodBalanceRawText()` → `string` — The raw balance on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodBalanceText()` → `string` — The balance on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodCredit()` → `Bkper.Amount` — The credit on the date period.
- `getPeriodCreditText()` → `string` — The credit on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodDebit()` → `Bkper.Amount` — The debit on the date period.
- `getPeriodDebitText()` → `string` — The debit on the date period formatted according to `Book` decimal format and fraction digits
- `getProperties()` → `{ [key: string]: string }` — Gets the custom properties stored in this Account or Group.
- `getProperty(keys: string[])` → `string` — Gets the property value for given keys. First property found will be retrieved
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in the associated `Account` or `Group`.
- `hasGroupBalances()` → `boolean` — Tell if the balance container is from a parent group
- `isCredit()` → `boolean` — Gets the credit nature of the BalancesContainer, based on `Account` or `Group`.
- `isFromAccount()` → `boolean` — Tell if this balance container if from an `Account`
- `isFromGroup()` → `boolean` — Tell if this balance container if from a `Group`
- `isPermanent()` → `boolean` — Tell if this balance container is permament, based on the `Account` or `Group`.
- `removeBalancesContainer(container: Bkper.BalancesContainer)` → `Bkper.BalancesContainer` — Removes an `Account` container from a `Group` container.

**addBalancesContainer**

**NOTE**: Only for Group balance containers.

**getBalancesContainers**

**NOTE**: Only for Group balance containers. Accounts returns null.

**isCredit**

For `Account`, the credit nature will be the same as the one from the Account

For `Group`, the credit nature will be the same, if all accounts containing on it has the same credit nature. False if mixed.

**isPermanent**

Permanent are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(accountancy)#Based_on_periodicity_of_flow)

Usually represents assets or liabilities, capable of being perceived by the senses or the mind, like bank accounts, money, debts and so on.

**removeBalancesContainer**

**NOTE**: Only for Group balance containers.

### BalancesDataTableBuilder

**Methods:**

- `build()` → `any[][]` — Builds an two-dimensional array with the balances.
- `expanded(expanded: number | boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether Groups should expand its child accounts.
- `formatDates(format: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the dates should be ISO YYYY-MM-DD formatted.
- `formatValues(format: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the value should be formatted based on decimal separator of the `Book`.
- `hideDates(hide: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the dates should be hidden for **PERIOD** or **CUMULATIVE** `BalanceType`.
- `hideNames(hide: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the `Accounts` and `Groups` names should be hidden.
- `period(period: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should force use of period balances for **TOTAL** `BalanceType`.
- `properties(include: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether include custom `Accounts` and `Groups` properties.
- `raw(raw: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should show raw balances, no matter the credit nature of the Account or Group.
- `transposed(transposed: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should rows and columns should be transposed.
- `trial(trial: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should split **TOTAL** `BalanceType` into debit and credit.
- `type(type: Bkper.BalanceType)` → `Bkper.BalancesDataTableBuilder` — Fluent method to set the `BalanceType` for the builder.

**expanded**

true to expand itself
-1 to expand all subgroups
-2 to expand all accounts
0 to expand nothing
1 to expand itself and its first level of children
2 to expand itself and its first two levels of children
etc.

**transposed**

For **TOTAL** `BalanceType`, the **transposed** table looks like:

```
  _____________________________
 |  Expenses | Income  |  ...  |
 | -4568.23  | 5678.93 |  ...  |
 |___________|_________|_______|

```
Two rows, and each `Account` or `Group` per column.


For **PERIOD** or **CUMULATIVE** `BalanceType`, the **transposed** table will be a time table, and the format looks like:

```
  _______________________________________________________________
 |            | Expenses   | Income     |     ...    |    ...    |
 | 15/01/2014 | -2345.23   |  3452.93   |     ...    |    ...    |
 | 15/02/2014 | -2345.93   |  3456.46   |     ...    |    ...    |
 | 15/03/2014 | -2456.45   |  3567.87   |     ...    |    ...    |
 |     ...    |     ...    |     ...    |     ...    |    ...    |
 |____________|____________|____________|____________|___________|

```

First column will be each `Account` or `Group`, and one column for each Date.

### BalancesReport

**Properties:**

- `payload`: `bkper.Balances` — The underlying payload data for this resource

**Methods:**

- `createDataTable()` → `Bkper.BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`.
- `getAccountBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all `Account` `BalancesContainers`.
- `getBalancesContainer(name: string)` → `Bkper.BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all `BalancesContainers` of the report.
- `getBook()` → `Bkper.Book` — The `Book` that generated the report.
- `getPeriodicity()` → `Bkper.Periodicity` — The `Periodicity` of the query used to generate the report.
- `hasOnlyOneGroup()` → `boolean` — Check if the report has only one Group specified on query.
- `json()` → `bkper.Balances` — Gets an immutable copy of the JSON payload for this resource.

### BkperApp

**Properties:**

- `AccountType`: `Bkper.AccountType`
- `BalanceType`: `Bkper.BalanceType`
- `BotResponseType`: `Bkper.BotResponseType`
- `DecimalSeparator`: `Bkper.DecimalSeparator`
- `Month`: `Bkper.Month`
- `Periodicity`: `Bkper.Periodicity`
- `Permission`: `Bkper.Permission`
- `TransactionStatus`: `Bkper.TransactionStatus`

**Methods:**

- `getBook(id: string)` → `Bkper.Book` — Gets the `Book` with the specified bookId from url param.
- `getBooks()` → `Bkper.Book[]` — Gets all `Books` the user has access.
- `newAmount(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Create a new `Amount` wrapping a given number, or arbitrary-precision math calculations.
- `normalizeName(name: string)` → `string` — Normalize a name
- `setAgentId(agentId: string | null)` → `void` — Sets the agent ID to identify the calling agent for attribution purposes.
- `setApiKey(key: string | null)` → `void` — Sets the API key for dedicated quota limits.
- `setOAuthTokenProvider(tokenProvider: Bkper.OAuthTokenProvider)` → `void` — Sets the `OAuthTokenProvider`.

**getBook**

This is the main Entry Point to start interacting with the [bkper-gs](https://github.com/bkper/bkper-gs) library.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");
book.record("#fuel for my Land Rover 126.50 28/01/2013");
```

**setAgentId**

This ID is sent via the `bkper-agent-id` header with each API request,
allowing the server to attribute actions to the correct agent.

**setApiKey**

API keys are optional - if not set, the Bkper API proxy provides a managed key with shared quota.
Use your own API key for dedicated quota limits and project-level usage tracking.

API keys are for project identification only, not for authentication or agent attribution.
Agent attribution is handled separately via `setAgentId()`.

**setOAuthTokenProvider**

If none set, the default built-in [ScriptApp](https://developers.google.com/apps-script/reference/script/script-app#getoauthtoken) will be used.

### Book

**Properties:**

- `payload`: `bkper.Book` — The underlying payload data for this resource

**Methods:**

- `addCollaborator(email: string, permission: Bkper.Permission)` → `void` — Adds a collaborator to the Book.
- `audit()` → `void` — Trigger Balances Audit async process.
- `batchCheckTransactions(transactions: Bkper.Transaction[])` → `void` — Batch check `Transactions` on the Book.
- `batchCreateAccounts(accounts: Bkper.Account[])` → `Bkper.Account[]` — Create `Accounts` on the Book, in batch.
- `batchCreateGroups(groups: Bkper.Group[])` → `Bkper.Group[]` — Create `Groups` on the Book, in batch.
- `batchCreateTransactions(transactions: Bkper.Transaction[])` → `Bkper.Transaction[]` — Batch create `Transactions` on the Book.
- `batchTrashTransactions(transactions: Bkper.Transaction[], trashChecked?: boolean)` → `void` — Batch trash `Transactions` on the Book.
- `batchUncheckTransactions(transactions: Bkper.Transaction[])` → `void` — Batch uncheck `Transactions` on the Book.
- `batchUpdateTransactions(transactions: Bkper.Transaction[], updateChecked?: boolean)` → `void` — Batch update `Transactions` on the Book.
- `continueTransactionIterator(query: string, continuationToken: string)` → `Bkper.TransactionIterator` — Resumes a transaction iteration using a continuation token from a previous iterator.
- `countTransactions(query?: string)` → `number` — Retrieve the number of transactions based on a query.
- `createAccount(name: string, group?: string, description?: string)` → `Bkper.Account` — ~~Deprecated~~ Create an `Account` in this book.
- `createAccounts(accounts: string[][])` → `Bkper.Account[]` — ~~Deprecated~~ Create `Accounts` on the Book, in batch.
- `createAccountsDataTable(group?: string)` → `Bkper.AccountsDataTableBuilder` — Create a `AccountsDataTableBuilder`, to build two dimensional Array representations of `Accounts` dataset.
- `createBalancesDataTable(query: string)` → `Bkper.BalancesDataTableBuilder` — Create a `BalancesDataTableBuilder` based on a query, to create two dimensional Array representation of balances of `Account` or `Group`
- `createGroups(groups: string[])` → `Bkper.Group[]` — ~~Deprecated~~ Create `Groups` on the Book, in batch.
- `createGroupsDataTable()` → `Bkper.GroupsDataTableBuilder` — Create a `GroupsDataTableBuilder`, to build two dimensional Array representations of `Groups` dataset.
- `createTransactionsDataTable(query?: string)` → `Bkper.TransactionsDataTableBuilder` — Create a `TransactionsDataTableBuilder` based on a query, to build two dimensional Array representations of `Transactions` dataset.
- `formatAmount(amount: Bkper.Amount)` → `string` — Formats an amount according to `DecimalSeparator` and fraction digits of the Book.
- `formatDate(date: Date, timeZone?: string)` → `string` — Formats a date according to date pattern of the Book.
- `formatValue(value: Bkper.Amount)` → `string` — ~~Deprecated~~ Formats a value according to `DecimalSeparator` and fraction digits of the Book.
- `getAccount(idOrName: string)` → `Bkper.Account` — Gets an `Account` object
- `getAccounts(group?: string)` → `Bkper.Account[]`
- `getApps()` → `Bkper.App[]` — Retrieve installed `Apps` for this Book
- `getBacklog()` → `Bkper.Backlog` — Retrieve the pending events `Backlog` for this Book
- `getBalancesReport(query: string)` → `Bkper.BalancesReport` — Create a `BalancesReport` based on query
- `getClosingDate()` / `setClosingDate(closingDate: string | null)` → `string (set: string | null)`
- `getCollection()` → `Bkper.Collection`
- `getDatePattern()` / `setDatePattern(datePattern: string)` → `string`
- `getDecimalSeparator()` / `setDecimalSeparator(decimalSeparator: Bkper.DecimalSeparator)` → `Bkper.DecimalSeparator`
- `getEvents(afterDate?: string, beforeDate?: string, onError?: boolean, resource?: Bkper.Account | Bkper.Group | Bkper.Transaction)` → `Bkper.EventIterator` — Get Book events based on search parameters.
- `getFile(id: string)` → `Bkper.File` — Retrieve a `File` by id
- `getFractionDigits()` / `setFractionDigits(fractionDigits: number)` → `number`
- `getGroup(idOrName: string)` → `Bkper.Group` — Gets a `Group` object
- `getGroups()` → `Bkper.Group[]`
- `getId()` → `string` — Same as bookId param
- `getLastUpdateMs()` → `number`
- `getLockDate()` / `setLockDate(lockDate: string | null)` → `string (set: string | null)`
- `getName()` / `setName(name: string)` → `string`
- `getOwnerName()` → `string`
- `getPeriodStartMonth()` / `setPeriodStartMonth(month: Bkper.Month)` → `Bkper.Month`
- `getPermission()` → `Bkper.Permission`
- `getSavedQueries()` → `{ id?: string; query?: string; title?: string }[]`
- `getTimeZone()` / `setTimeZone(timeZone: string)` → `string`
- `getTimeZoneOffset()` → `number`
- `getTotalTransactions()` → `number`
- `getTotalTransactionsCurrentMonth()` → `number`
- `getTotalTransactionsCurrentYear()` → `number`
- `getTransaction(id: string)` → `Bkper.Transaction` — Retrieve a `Transaction` by id
- `getTransactions(query?: string)` → `Bkper.TransactionIterator` — Get Book transactions based on a query.
- `json()` → `bkper.Book` — Gets an immutable copy of the JSON payload for this resource.
- `mergeTransactions(transaction1: Bkper.Transaction, transaction2: Bkper.Transaction)` → `Bkper.Transaction` — Merge two `Transactions` into one.
- `newAccount()` → `Bkper.Account` — Instantiate a new `Account`
- `newFile()` → `Bkper.File` — Instantiate a new `File`
- `newGroup()` → `Bkper.Group` — Instantiate a new `Group`
- `newTransaction()` → `Bkper.Transaction` — Instantiate a new `Transaction`
- `parseAmount(value: string)` → `Bkper.Amount` — Parse an amount string according to `DecimalSeparator` and fraction digits of the Book.
- `parseDate(date: string)` → `Date` — Parse a date string according to date pattern and timezone of the Book.
- `parseValue(value: string)` → `Bkper.Amount` — ~~Deprecated~~ Parse a value string according to `DecimalSeparator` and fraction digits of the Book.
- `record(transactions: string | any[] | any[][], timeZone?: string)` → `void` — ~~Deprecated~~ Record `Transactions` on the Book.
- `removeCollaborator(email: string)` → `void` — Removes a collaborator from the Book.
- `round(amount: Bkper.Amount)` → `Bkper.Amount` — Rounds an amount according to the number of fraction digits of the Book
- `update()` → `Bkper.Book` — Perform update Book, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**createAccount**

The type of account will be determined by the type of others Accounts in same group.

If not specified, the type ASSET (permanent=true/credit=false) will be set.

If all other accounts in same group is in another group, the account will also be added to the other group.

**Deprecated**

**createAccounts**

The first column of the matrix will be used as the `Account` name.

The other columns will be used to find a matching `AccountType`.

Names matching existent accounts will be skipped.

**Deprecated**

**createAccountsDataTable**

Accounts data table builder.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var accountsDataTable = book.createAccountsDataTable().build();

// Or filter by group
var filteredDataTable = book.createAccountsDataTable("Revenue").build();
```

**createBalancesDataTable**

The balances data table builder

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var balancesDataTable = book.createBalancesDataTable("account:'Credit card' after:7/2018 before:8/2018").build();
```

**createGroupsDataTable**

Groups data table builder.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var groupsDataTable = book.createGroupsDataTable().build();
```

**createTransactionsDataTable**

Transactions data table builder.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var transactionsDataTable = book.createTransactionsDataTable("account:'Bank Account' before:1/2019").build();
```

**getBalancesReport**

The balances report

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var balancesReport = book.getBalancesReport("group:'Equity' after:7/2018 before:8/2018");

var accountBalance = balancesReport.getBalancesContainer("Bank Account").getCumulativeBalance();
```

**getTransactions**

The Transactions result as an iterator.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

var transactions = book.getTransactions("account:CreditCard after:28/01/2013 before:29/01/2013");

while (transactions.hasNext()) {
 var transaction = transactions.next();
 Logger.log(transaction.getDescription());
}
```

**mergeTransactions**

The merged transaction is created synchronously. Cleanup of the two
originals is scheduled asynchronously by the backend.

**newAccount**

The new Account, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newAccount()
 .setName('Some New Account')
 .setType('INCOMING')
 .addGroup('Revenue').addGroup('Salary')
 .setProperties({prop_a: 'A', prop_b: 'B'})
 .create();
```

**newFile**

The new File, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newFile()
 .setBlob(UrlFetchApp.fetch('https://bkper.com/images/index/integrations4.png').getBlob())
 .create();
```

**newGroup**

The new Group, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newGroup()
 .setName('Some New Group')
 .setProperty('key', 'value')
 .create();
```

**newTransaction**

The new Transaction, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newTransaction()
 .setDate('2013-01-25')
 .setDescription("Filling tank of my truck")
 .from('Credit Card')
 .to('Gas')
 .setAmount(126.50)
 .create();

```

**parseDate**

Also parse ISO yyyy-mm-dd format.

**record**

The text is usually amount and description, but it can also can contain an informed Date in full format (dd/mm/yyyy - mm/dd/yyyy).

Example:

```js
book.record("#gas 63.23");
```

**Deprecated**

### BotResponse

**Properties:**

- `payload`: `bkper.BotResponse` — The underlying payload data for this resource

**Methods:**

- `getAgentId()` → `string`
- `getMessage()` → `string`
- `getType()` → `Bkper.BotResponseType`
- `json()` → `bkper.BotResponse` — Gets an immutable copy of the JSON payload for this resource.

### Collection

**Properties:**

- `payload`: `bkper.Collection` — The underlying payload data for this resource

**Methods:**

- `getBooks()` → `Bkper.Book[]`
- `getId()` → `string`
- `getName()` / `setName(name: string)` → `string`
- `json()` → `bkper.Collection` — Gets an immutable copy of the JSON payload for this resource.
- `update()` → `Bkper.Collection` — Performs update Collection, applying pending changes.

### Event

**Properties:**

- `payload`: `bkper.Event` — The underlying payload data for this resource

**Methods:**

- `getBotResponses()` → `Bkper.BotResponse[]`
- `getId()` → `string`
- `json()` → `bkper.Event` — Gets an immutable copy of the JSON payload for this resource.

### EventIterator

**Methods:**

- `getBook()` → `Bkper.Book` — Gets the Book that originated the iterator
- `getContinuationToken()` / `setContinuationToken(continuationToken: string)` → `string` — Gets a token that can be used to resume this iteration at a later time.
- `hasNext()` → `boolean` — Determines whether calling next() will return a transaction.
- `next()` → `Bkper.Event` — Gets the next event in the collection of events.

**continuationToken**

This method is useful if processing an iterator in one execution would exceed the maximum execution time.

Continuation tokens are generally valid short period of time.

### File

**Properties:**

- `payload`: `bkper.File` — The underlying payload data for this resource

**Methods:**

- `create()` → `Bkper.File` — Perform create new File.
- `getBlob()` / `setBlob(blob: GoogleAppsScript.Base.Blob)` → `GoogleAppsScript.Base.Blob` — Gets the Blob from this file
- `getContent()` / `setContent(content: string)` → `string` — Gets the file content Base64 encoded
- `getContentType()` / `setContentType(contentType: string)` → `string` — Gets the File content type
- `getId()` → `string` — Gets the File id
- `getName()` / `setName(name: string)` → `string` — Gets the File name
- `getSize()` → `number` — Gets the file size in bytes
- `getUrl()` → `string` — Gets the file serving url for accessing via browser
- `json()` → `bkper.File` — Gets an immutable copy of the JSON payload for this resource.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### Group

**Properties:**

- `payload`: `bkper.Group` — The underlying payload data for this resource

**Methods:**

- `create()` → `Bkper.Group` — Perform create new group.
- `getAccounts()` → `Bkper.Account[]`
- `getChildren()` → `Bkper.Group[]`
- `getDepth()` → `number`
- `getId()` → `string`
- `getName()` / `setName(name: string)` → `string`
- `getNormalizedName()` → `string`
- `getParent()` / `setParent(group: Bkper.Group | null)` → `Bkper.Group (set: Bkper.Group | null)`
- `getParentGroupsChain()` → `Bkper.Group[]`
- `getRoot()` → `Bkper.Group`
- `getType()` → `Bkper.AccountType`
- `hasAccounts()` → `boolean`
- `hasChildren()` → `boolean` — Tell if this group has any children
- `isCredit()` → `boolean` — Tell if this is a credit (Incoming and Liabities) group
- `isHidden()` → `boolean` — Tell if the Group is hidden on main transactions menu
- `isLocked()` → `boolean`
- `isMixed()` → `boolean` — Tell if this is a mixed (Assets/Liabilities or Incoming/Outgoing) group
- `isPermanent()` → `boolean` — Tell if this is a permanent (Assets and Liabilities) group
- `json()` → `bkper.Group` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Bkper.Group` — Perform delete group.
- `setHidden(hidden: boolean)` → `Bkper.Group` — Hide/Show group on main menu.
- `setLocked(locked: boolean)` → `Bkper.Group` — Sets the locked state of the Group.
- `update()` → `Bkper.Group` — Perform update group, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### GroupsDataTableBuilder

**Methods:**

- `build()` → `any[][]`
- `ids(include: boolean)` → `Bkper.GroupsDataTableBuilder` — Defines whether include group ids.
- `properties(include: boolean)` → `Bkper.GroupsDataTableBuilder` — Defines whether include custom group properties.

### OAuthTokenProvider

**Methods:**

- `getOAuthToken()` → `string` — A valid OAuth2 access token with **email** scope authorized.

### Transaction

**Properties:**

- `payload`: `bkper.Transaction` — The underlying payload data for this resource

**Methods:**

- `addFile(file: any)` → `Bkper.Transaction` — Add a File attachment to the Transaction.
- `addRemoteId(remoteId: string)` → `Bkper.Transaction` — Add a remote id to the Transaction.
- `addUrl(url: string)` → `Bkper.Transaction` — Add a url to the Transaction. Url starts with https://
- `check()` → `Bkper.Transaction` — Perform check transaction.
- `create()` → `Bkper.Transaction` — Perform create new draft transaction.
- `from(account: string | Bkper.Account)` → `Bkper.Transaction` — Set the credit/origin Account of the Transaction. Same as setCreditAccount().
- `getAccountBalance(raw?: boolean)` → `Bkper.Amount` — Gets the balance that the `Account` has at that day, when listing transactions of that Account.
- `getAgentId()` → `string`
- `getAmount()` / `setAmount(amount: string | number | Bkper.Amount)` → `Bkper.Amount (set: string | number | Bkper.Amount)`
- `getCreatedAt()` → `Date`
- `getCreatedAtFormatted()` → `string`
- `getCreditAccount()` / `setCreditAccount(account: string | Bkper.Account)` → `Bkper.Account (set: string | Bkper.Account)`
- `getCreditAccountName()` → `string`
- `getCreditAmount(account: string | Bkper.Account)` → `Bkper.Amount` — Get the absolute amount of this transaction if the given account is at the credit side, else null.
- `getDate()` / `setDate(date: string | Date)` → `string (set: string | Date)`
- `getDateFormatted()` → `string`
- `getDateObject()` → `Date`
- `getDateValue()` → `number`
- `getDebitAccount()` / `setDebitAccount(account: string | Bkper.Account)` → `Bkper.Account (set: string | Bkper.Account)`
- `getDebitAccountName()` → `string`
- `getDebitAmount(account: string | Bkper.Account)` → `Bkper.Amount` — Gets the absolute amount of this transaction if the given account is at the debit side, else null.
- `getDescription()` / `setDescription(description: string)` → `string`
- `getFiles()` → `Bkper.File[]`
- `getId()` → `string`
- `getInformedDate()` → `Date` — ~~Deprecated: Use getDateObject instead.~~
- `getInformedDateText()` → `string` — ~~Deprecated: use getDateFormatted instead~~
- `getInformedDateValue()` → `number` — ~~Deprecated: use getDateValue instead.~~
- `getOtherAccount(account: string | Bkper.Account)` → `Bkper.Account` — Gets the `Account` at the other side of the transaction given the one in one side.
- `getOtherAccountName(account: string | Bkper.Account)` → `string` — The account name at the other side of the transaction given the one in one side.
- `getPostDate()` → `Date` — ~~Deprecated: use getCreatedAt instead.~~
- `getPostDateText()` → `string` — ~~Deprecated: use getCreatedAtFormatted instead.~~
- `getRemoteIds()` → `string[]` — Remote ids are used to avoid duplication.
- `getStatus()` → `Bkper.TransactionStatus` — Gets the status of the transaction.
- `getTags()` → `string[]`
- `getUrls()` / `setUrls(urls: string[])` → `string[]`
- `hasTag(tag: string)` → `boolean` — Check if the transaction has the specified tag.
- `isChecked()` → `boolean`
- `isCredit(account: Bkper.Account)` → `boolean` — Tell if the given account is credit on the transaction
- `isDebit(account: Bkper.Account)` → `boolean` — Tell if the given account is debit on the transaction
- `isLocked()` → `boolean`
- `isPosted()` → `boolean`
- `isTrashed()` → `boolean`
- `json()` → `bkper.Transaction` — Gets an immutable copy of the JSON payload for this resource.
- `post()` → `Bkper.Transaction` — Perform post transaction, changing credit and debit `Account` balances.
- `remove()` → `Bkper.Transaction` — ~~Deprecated~~ Remove the transaction, sending to trash.
- `restore()` → `Bkper.Transaction` — ~~Deprecated~~ Restore the transaction from trash.
- `setChecked(checked: boolean)` → `Bkper.Transaction` — Set the check state of the Transaction.
- `to(account: string | Bkper.Account)` → `Bkper.Transaction` — Set the debit/destination Account of the Transaction. Same as setDebitAccount().
- `trash()` → `Bkper.Transaction` — Perform trash transaction.
- `uncheck()` → `Bkper.Transaction` — Perform uncheck transaction.
- `untrash()` → `Bkper.Transaction` — Perform untrash transaction.
- `update()` → `Bkper.Transaction` — Upddate transaction, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**addFile**

Files not previously created in the Book will be automatically created when the Transaction is persisted.

**getAccountBalance**

Evolved balances is returned when searching for transactions of a permanent `Account`.

Only comes with the last posted transaction of the day.

**getStatus**

The status is determined by precedence: TRASHED > DRAFT > CHECKED/UNCHECKED

### TransactionIterator

**Methods:**

- `getAccount()` → `Bkper.Account`
- `getBook()` → `Bkper.Book` — Gets the Book that originate the iterator
- `getContinuationToken()` / `setContinuationToken(continuationToken: string)` → `string` — Gets a token that can be used to resume this iteration at a later time.
- `hasNext()` → `boolean` — Determines whether calling next() will return a transaction.
- `next()` → `Bkper.Transaction` — Gets the next transaction in the collection of transactions.

**continuationToken**

This method is useful if processing an iterator in one execution would exceed the maximum execution time.

Continuation tokens are generally valid short period of time.

### TransactionsDataTableBuilder

**Methods:**

- `build()` → `any[][]`
- `formatDates(format: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether the dates should be formatted, based on date patter of the `Book`
- `formatValues(format: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether amounts should be formatted based on `DecimalSeparator` of the `Book`
- `getAccount()` → `Bkper.Account`
- `includeIds(include: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether include transaction ids.
- `includeProperties(include: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether include custom transaction properties.
- `includeUrls(include: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether include attachments and url links.

## Enums

### AccountType

Enum that represents account types.

- `ASSET` — Asset account type
- `INCOMING` — Incoming account type
- `LIABILITY` — Liability account type
- `OUTGOING` — Outgoing account type

### BalanceType

Enum that represents balance types.

- `CUMULATIVE` — Cumulative balance
- `PERIOD` — Period balance
- `TOTAL` — Total balance

### BotResponseType

Enum that represents a Bot Response type

- `ERROR` — Error bot response
- `INFO` — Info bot response
- `WARNING` — Warning bot response

### DecimalSeparator

Decimal separator of numbers on book

- `COMMA` — ,
- `DOT` — .

### Month

Enum that represents a Month.

- `APRIL`
- `AUGUST`
- `DECEMBER`
- `FEBRUARY`
- `JANUARY`
- `JULY`
- `JUNE`
- `MARCH`
- `MAY`
- `NOVEMBER`
- `OCTOBER`
- `SEPTEMBER`

### Periodicity

The Periodicity of the query. It may depend on the level of granularity you write the range params.

- `DAILY` — Example: after:25/01/1983, before:04/03/2013, after:$d-30, before:$d, after:$d-15/$m
- `MONTHLY` — Example: after:jan/2013, before:mar/2013, after:$m-1, before:$m
- `YEARLY` — Example: on:2013, after:2013, $y

### Permission

Enum representing permissions of user in the Book

- `EDITOR` — Manage accounts, transactions, book configuration and sharing
- `NONE` — No permission
- `OWNER` — Manage everything, including book visibility and deletion. Only one owner per book.
- `POSTER` — View transactions, accounts, record and delete drafts
- `RECORDER` — Record and delete drafts only. Useful to collect data only
- `VIEWER` — View transactions, accounts and balances.

### TransactionStatus

Enum that represents a Transaction status.

- `CHECKED` — Transaction is posted and checked
- `DRAFT` — Transaction is not yet posted (draft)
- `TRASHED` — Transaction is in trash
- `UNCHECKED` — Transaction is posted but not checked

---
source: /docs/api/bkper-js.md

# bkper-js

> JavaScript/TypeScript client library for Bkper — classes, interfaces, and type definitions.

bkper-js library is a simple and secure way to access the [Bkper REST API](https://bkper.com/docs/api/rest) on Node.js and modern browsers.

It provides a set of classes and functions to interact with the Bkper API, including authentication, authorization, and data manipulation.

[![npm](https://img.shields.io/npm/v/bkper-js?color=%235889e4)](https://www.npmjs.com/package/bkper-js) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--js-blue?logo=github)](https://github.com/bkper/bkper-js)

### CDN / Browser

The simplest way to use bkper-js in a browser — no build tools, no npm, just a `<script>` tag and a valid access token. Works on **any domain**.

```html
<script src="https://cdn.jsdelivr.net/npm/bkper-js@2/dist/bkper.min.js"></script>
<script>
    const { Bkper } = bkperjs;

    async function listBooks(token) {
        Bkper.setConfig({
            oauthTokenProvider: async () => token,
        });
        const bkper = new Bkper();
        return await bkper.getBooks();
    }

    // Example: prompt for a token and list books
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('go').addEventListener('click', async () => {
            const token = document.getElementById('token').value;
            const books = await listBooks(token);
            document.getElementById('output').textContent = books.map(b => b.getName()).join('\n');
        });
    });
</script>

<input id="token" placeholder="Paste your access token" />
<button id="go">List Books</button>
<pre id="output"></pre>
```

Get an access token with the [Bkper CLI](https://www.npmjs.com/package/bkper):

```bash
bkper auth login   # one-time setup
bkper auth token   # prints a token (valid for 1 hour)
```

Pin to a specific version by replacing `@2` with e.g. `@2.31.0`.

### Node.js / CLI Scripts

For local scripts and CLI tools, use the [bkper](https://www.npmjs.com/package/bkper) CLI package for authentication:

```typescript
import { Bkper } from 'bkper-js';
import { getOAuthToken } from 'bkper';

// Configure with CLI authentication
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
});

// Create Bkper instance
const bkper = new Bkper();

// Get a book and work with it
const book = await bkper.getBook('your-book-id');
console.log(`Book: ${book.getName()}`);

// List all books
const books = await bkper.getBooks();
console.log(`You have ${books.length} books`);
```

First, login via CLI: `bkper auth login`

### npm + Bundler

If you are using a bundler (Vite, webpack, esbuild, etc.), install from npm and provide an access token the same way as the CDN example:

```typescript
import { Bkper } from 'bkper-js';

Bkper.setConfig({
    oauthTokenProvider: async () => 'your-access-token',
});

const bkper = new Bkper();
const books = await bkper.getBooks();
```

### Web Applications on \*.bkper.app

> **Note:** `@bkper/web-auth` **only works on `*.bkper.app` subdomains**. Its session cookies are scoped to the `.bkper.app` domain and will not work on any other domain. For apps on other domains, use the [CDN / Browser](#cdn--browser) approach with an access token instead.

For apps hosted on `*.bkper.app` subdomains, use the [@bkper/web-auth](https://www.npmjs.com/package/@bkper/web-auth) SDK for built-in OAuth login flow:

```typescript
import { Bkper } from 'bkper-js';
import { BkperAuth } from '@bkper/web-auth';

// Initialize authentication
const auth = new BkperAuth({
    onLoginSuccess: () => initializeApp(),
    onLoginRequired: () => showLoginButton(),
});

// Restore session on app load
await auth.init();

// Configure Bkper with web auth
Bkper.setConfig({
    oauthTokenProvider: async () => auth.getAccessToken(),
});

// Create Bkper instance and use it
const bkper = new Bkper();
const books = await bkper.getBooks();
```

See the [@bkper/web-auth documentation](https://bkper.com/docs/auth-sdk) for more details.

### API Key (Optional)

API keys are optional and only needed for dedicated quota limits. If not provided, requests use a shared managed quota via the Bkper API proxy.

```typescript
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
    apiKeyProvider: async () => process.env.BKPER_API_KEY, // Optional - for dedicated quota
});
```

## Classes

### Account *(extends ResourceProperty<bkper.Account>)*

This class defines an [Account](https://en.wikipedia.org/wiki/Account_(bookkeeping)) of a `Book`.

It maintains a balance of all amount [credited and debited](http://en.wikipedia.org/wiki/Debits_and_credits) in it by `Transactions`.

An Account can be grouped by `Groups`.

`Account` has no `getBalance()` method. To retrieve account balances, use
`Book.getBalancesReport` and read the resulting `BalancesContainer`.

**Constructor:** `new Account(book: Book, payload?: bkper.Account)`

**Properties:**

- `payload`: `bkper.Account` — The underlying payload data for this resource

**Methods:**

- `addGroup(group: bkper.Group | Group)` → `Account` — Adds a group to the Account.
- `create()` → `Promise<Account>` — Performs create new Account.
- `deleteProperty(key: string)` → `this` — Deletes a custom property.
- `getGroups()` / `setGroups(groups: Group[] | bkper.Group[])` → `Promise<Group[]> (set: Group[] | bkper.Group[])` — Gets the `Groups` of this Account.
- `getId()` → `string | undefined` — Gets the Account internal id.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the Account name.
- `getNormalizedName()` → `string` — Gets the normalized name of this Account without spaces or special characters.
- `getProperties()` / `setProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the custom properties stored in this resource.
- `getProperty(keys: string[])` / `setProperty(key: string, value: string | null | undefined)` → `string | undefined (set: string)` — Gets the property value for given keys. First property found will be retrieved.
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in this resource.
- `getType()` / `setType(type: AccountType)` → `AccountType` — Gets the type of this Account.
- `getVisibleProperties()` / `setVisibleProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the visible custom properties stored in this resource.
Hidden properties (those ending with "_") are excluded from the result.
- `hasTransactionPosted()` → `boolean | undefined` — Tells if the Account has any transaction already posted.
- `isArchived()` → `boolean | undefined` — Tells if this Account is archived.
- `isBalanceVerified()` → `boolean | undefined` — Tells if the balance of this Account has been verified/audited.
- `isCredit()` → `boolean | undefined` — Tells if the Account has a Credit nature or Debit otherwise.
- `isInGroup(group: string | Group)` → `Promise<boolean>` — Tells if this Account is in the `Group`.
- `isPermanent()` → `boolean | undefined` — Tells if the Account is permanent.
- `json()` → `bkper.Account` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Account>` — Performs delete Account.
- `removeGroup(group: string | Group)` → `Promise<Account>` — Removes a group from the Account.
- `setArchived(archived: boolean)` → `Account` — Sets Account archived/unarchived.
- `setVisibleProperty(key: string, value: string | null | undefined)` → `this` — Sets a custom property in this resource, filtering out hidden properties.
Hidden properties are those whose keys end with an underscore "_".
- `update()` → `Promise<Account>` — Performs update Account, applying pending changes.

**groups**

When groups are already embedded in the account payload (e.g. from
`Bkper.getBook` with includeGroups), resolves them from the
book's cache instead of making API calls.

**hasTransactionPosted**

Accounts with transaction posted, even with zero balance, can only be archived.

**isCredit**

Credit Accounts are just for representation purposes. It increase or decrease the absolute balance. It doesn't affect the overall balance or the behavior of the system.

The absolute balance of credit Accounts increase when it participate as a credit/origin in a transaction. Its usually for Accounts that increase the balance of the assets, like revenue Accounts.

```
        Crediting a credit
  Thus ---------------------> Account increases its absolute balance
        Debiting a debit


        Debiting a credit
  Thus ---------------------> Account decreases its absolute balance
        Crediting a debit
```

As a rule of thumb, and for simple understanding, almost all Accounts are Debit nature (NOT credit), except the ones that "offers" amount for the books, like revenue Accounts.

**isPermanent**

Permanent Accounts are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(Accountancy)#Based_on_periodicity_of_flow)

Usually represents assets or tangibles, capable of being perceived by the senses or the mind, like bank Accounts, money, debts and so on.

### AccountsDataTableBuilder

A AccountsDataTableBuilder is used to setup and build two-dimensional arrays containing accounts.

**Constructor:** `new AccountsDataTableBuilder(accounts: Account[])`

**Methods:**

- `archived(include: boolean)` → `AccountsDataTableBuilder` — Defines whether the archived accounts should be included.
- `build()` → `Promise<any[][]>` — Builds a two-dimensional array containing all accounts.
- `groups(include: boolean)` → `AccountsDataTableBuilder` — Defines whether include account groups.
- `hiddenProperties(include: boolean)` → `AccountsDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `AccountsDataTableBuilder` — Defines whether include account ids.
- `properties(include: boolean)` → `AccountsDataTableBuilder` — Defines whether include custom account properties.

### Agent

Defines an Agent on Bkper.

An Agent represents an entity (such as an App or Bot) that interacts with Bkper, executing actions on behalf of users.

**Constructor:** `new Agent(payload?: bkper.Agent)`

**Properties:**

- `payload`: `bkper.Agent`

**Methods:**

- `getId()` → `string | undefined` — Gets the Agent universal identifier.
- `getLogoUrl()` → `string | undefined` — Gets the Agent logo URL.
- `getLogoUrlDark()` → `string | undefined` — Gets the Agent logo URL in dark mode.
- `getName()` → `string | undefined` — Gets the Agent name.
- `json()` → `bkper.Agent` — Gets the wrapped plain JSON object.

### Amount

This class defines an Amount for arbitrary-precision decimal arithmetic.

It inherits methods from [big.js](http://mikemcl.github.io/big.js/) library

**Constructor:** `new Amount(n: string | number | Amount)`

The Amount constructor.

**Methods:**

- `abs()` → `Amount` — Returns an absolute Amount.
- `cmp(n: string | number | Amount)` → `-1 | 0 | 1` — Compares this Amount with another value.
- `div(n: string | number | Amount)` → `Amount` — Divides this Amount by another value.
- `eq(n: string | number | Amount)` → `boolean` — Checks if this Amount equals another value.
- `gt(n: string | number | Amount)` → `boolean` — Checks if this Amount is greater than another value.
- `gte(n: string | number | Amount)` → `boolean` — Checks if this Amount is greater than or equal to another value.
- `lt(n: string | number | Amount)` → `boolean` — Checks if this Amount is less than another value.
- `lte(n: string | number | Amount)` → `boolean` — Checks if this Amount is less than or equal to another value.
- `minus(n: string | number | Amount)` → `Amount` — Subtracts another value from this Amount.
- `mod(n: string | number | Amount)` → `Amount` — Calculates the modulo (remainder) of dividing this Amount by another value.
- `plus(n: string | number | Amount)` → `Amount` — Adds another value to this Amount.
- `round(dp?: number)` → `Amount` — Rounds this Amount to a maximum of dp decimal places.
- `times(n: string | number | Amount)` → `Amount` — Multiplies this Amount by another value.
- `toFixed(dp?: number)` → `string` — Returns a string representing the value of this Amount in normal notation to a fixed number of decimal places.
- `toNumber()` → `number` — Returns a primitive number representing the value of this Amount.
- `toString()` → `string` — Returns a string representing the value of this Amount.

**mod**

Similar to % operator

### App *(extends Resource<bkper.App>)*

Defines an App on Bkper.

Apps can be installed on Books by users.

**Constructor:** `new App(payload?: bkper.App, config?: Config)`

**Properties:**

- `payload`: `bkper.App` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<App>` — Performs the app creation, applying pending changes.
- `getDescription()` → `string | undefined` — Gets the description of this App.
- `getDevelopers()` / `setDevelopers(developers?: string)` → `string | undefined (set: string)` — Gets the developers (usernames and domain patterns).
- `getEvents()` → `EventType[] | undefined` — Gets the events bound to this App.
- `getFilePatterns()` → `string[] | undefined` — Gets the file patterns the App handles.
- `getId()` → `string | undefined` — Gets the App universal identifier.
- `getLogoUrl()` → `string | undefined` — Gets the logo url of this App.
- `getLogoUrlDark()` → `string | undefined` — Gets the logo url of this App in dark mode.
- `getMenuPopupHeight()` → `string | undefined` — Gets the menu popup height of this App.
- `getMenuPopupWidth()` → `string | undefined` — Gets the menu popup width of this App.
- `getMenuText()` → `string | undefined` — Gets the menu text of this App.
- `getMenuUrl()` → `string | undefined` — Gets the menu url of this App.
- `getMenuUrlDev()` → `string | undefined` — Gets the menu development url of this App.
- `getName()` → `string | undefined` — Gets the name of this App.
- `getOwnerLogoUrl()` → `string | undefined` — Gets the logo url of the owner of this App.
- `getOwnerName()` → `string | undefined` — Gets the name of the owner of this App.
- `getOwnerWebsiteUrl()` → `string | undefined` — Gets the website url of the owner of this App.
- `getReadme()` / `setReadme(readme?: string)` → `string | undefined (set: string)` — Gets the readme.md file as text.
- `getRepositoryUrl()` → `string | undefined` — Gets the repository url of this App.
- `getUsers()` / `setUsers(users?: string)` → `string | undefined (set: string)` — Gets the whitelisted users (usernames and domain patterns).
- `getWebsiteUrl()` → `string | undefined` — Gets the website url of this App.
- `hasEvents()` → `boolean` — Checks if this App has events bound to it.
- `isInstallable()` → `boolean` — Tells if this App is installable.
- `isPublished()` → `boolean` — Checks if this App is published.
- `isRepositoryPrivate()` → `boolean | undefined` — Tells if the repository is private.
- `json()` → `bkper.App` — Gets an immutable copy of the JSON payload for this resource.
- `setClientSecret(clientSecret?: string)` → `App` — Sets the client secret.
- `setWebhookUrlDev(webhookUrlDev: string)` → `App` — Sets the webhook url for development.
- `update()` → `Promise<App>` — Performs a full update of the App, applying pending changes.

**create**

The App id MUST be unique. If another app is already existing, an error will be thrown.

### Backlog *(extends Resource<bkper.Backlog>)*

This class defines the Backlog of a `Book`.

A Backlog is a list of pending tasks in a Book

**Constructor:** `new Backlog(payload?: bkper.Backlog, config?: Config)`

**Properties:**

- `payload`: `bkper.Backlog` — The underlying payload data for this resource

**Methods:**

- `getCount()` → `number | undefined` — Returns the number of pending tasks in this Backlog.
- `json()` → `bkper.Backlog` — Gets an immutable copy of the JSON payload for this resource.

### Balance

Class that represents an `Account` or `Group` balance on a window of time (Day / Month / Year).

**Constructor:** `new Balance(container: BalancesContainer, balancePlain: bkper.Balance)`

**Properties:**

- `payload`: `bkper.Balance`

**Methods:**

- `getCumulativeBalance()` → `Amount` — The cumulative balance to the date, based on the credit nature of the container
- `getCumulativeBalanceRaw()` → `Amount` — The raw cumulative balance to the date.
- `getCumulativeCredit()` → `Amount` — The cumulative credit to the date.
- `getCumulativeDebit()` → `Amount` — The cumulative debit to the date.
- `getDate()` → `Date` — Date object constructed based on `Book` time zone offset. Usefull for
- `getDay()` → `number` — The day of the balance. Days starts on 1 to 31.
- `getFuzzyDate()` → `number` — The Fuzzy Date of the balance, based on `Periodicity` of the `BalancesReport` query, composed by Year, Month and Day.
- `getMonth()` → `number` — The month of the balance. Months starts on 1 (January) to 12 (December)
- `getPeriodBalance()` → `Amount` — The balance on the date period, based on credit nature of the container.
- `getPeriodBalanceRaw()` → `Amount` — The raw balance on the date period.
- `getPeriodCredit()` → `Amount` — The credit on the date period.
- `getPeriodDebit()` → `Amount` — The debit on the date period.
- `getYear()` → `number` — The year of the balance

**getDate**

If Month or Day is zero, the date will be constructed with first Month (January) or Day (1) of the next period.

**getDay**

Day can be 0 (zero) in case of Monthly or Early `Periodicity` of the `BalancesReport`

**getFuzzyDate**

The format is **YYYYMMDD**. Very usefull for ordering and indexing

Month and Day can be 0 (zero), depending on the granularity of the `Periodicity`.

*Example:*

**20180125** - 25, January, 2018 - DAILY Periodicity

**20180100** - January, 2018 - MONTHLY Periodicity

**20180000** - 2018 - YEARLY Periodicity

**getMonth**

Month can be 0 (zero) in case of Early `Periodicity` of the `BalancesReport`

### BalancesDataTableBuilder *(implements BalancesDataTableBuilder)*

A BalancesDataTableBuilder is used to setup and build two-dimensional arrays containing balance information.

**Constructor:** `new BalancesDataTableBuilder(book: Book, balancesContainers: BalancesContainer[], periodicity: Periodicity)`

**Methods:**

- `build()` → `any[][]` — Builds an two-dimensional array with the balances.
- `expanded(expanded: number | boolean)` → `BalancesDataTableBuilder` — Defines whether Groups should expand its child accounts.
- `formatDates(format: boolean)` → `BalancesDataTableBuilder` — Defines whether the dates should be ISO formatted YYYY-MM-DD. E.g. 2025-01-01
- `formatValues(format: boolean)` → `BalancesDataTableBuilder` — Defines whether the value should be formatted based on decimal separator of the `Book`.
- `hiddenProperties(include: boolean)` → `BalancesDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `hideDates(hide: boolean)` → `BalancesDataTableBuilder` — Defines whether the dates should be hidden for **PERIOD** or **CUMULATIVE** `BalanceType`.
- `hideNames(hide: boolean)` → `BalancesDataTableBuilder` — Defines whether the `Accounts` and `Groups` names should be hidden.
- `period(period: boolean)` → `BalancesDataTableBuilder` — Defines whether should force use of period balances for **TOTAL** `BalanceType`.
- `properties(include: boolean)` → `BalancesDataTableBuilder` — Defines whether include custom `Accounts` and `Groups` properties.
- `raw(raw: boolean)` → `BalancesDataTableBuilder` — Defines whether should show raw balances, no matter the credit nature of the Account or Group.
- `transposed(transposed: boolean)` → `BalancesDataTableBuilder` — Defines whether should rows and columns should be transposed.
- `trial(trial: boolean)` → `BalancesDataTableBuilder` — Defines whether should split **TOTAL** `BalanceType` into debit and credit.
- `type(type: BalanceType)` → `BalancesDataTableBuilder` — Fluent method to set the `BalanceType` for the builder.

**expanded**

true to expand itself
-1 to expand all subgroups
-2 to expand all accounts
0 to expand nothing
1 to expand itself and its first level of children
2 to expand itself and its first two levels of children
etc.

**transposed**

For **TOTAL** `BalanceType`, the **transposed** table looks like:

```
  _____________________________
 |  Expenses | Income  |  ...  |
 | -4568.23  | 5678.93 |  ...  |
 |___________|_________|_______|

```
Two rows, and each `Account` or `Group` per column.


For **PERIOD** or **CUMULATIVE** `BalanceType`, the **transposed** table will be a time table, and the format looks like:

```
  _______________________________________________________________
 |            | Expenses   | Income     |     ...    |    ...    |
 | 15/01/2014 | -2345.23   |  3452.93   |     ...    |    ...    |
 | 15/02/2014 | -2345.93   |  3456.46   |     ...    |    ...    |
 | 15/03/2014 | -2456.45   |  3567.87   |     ...    |    ...    |
 |     ...    |     ...    |     ...    |     ...    |    ...    |
 |____________|____________|____________|____________|___________|

```

First column will be each Date, and one column for each `Account` or `Group`.

### BalancesReport

Class representing a Balance Report, generated when calling [Book.getBalanceReport](#book_getbalancesreport)

**Constructor:** `new BalancesReport(book: Book, payload: bkper.Balances)`

**Properties:**

- `payload`: `bkper.Balances`

**Methods:**

- `createDataTable()` → `BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`.
- `getBalancesContainer(name: string)` → `BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers()` → `BalancesContainer[]` — Gets all `BalancesContainers` of the report.
- `getBook()` → `Book` — Gets the `Book` that generated the report.
- `getPeriodicity()` → `Periodicity` — Gets the `Periodicity` of the query used to generate the report.

### Billing *(extends Resource<bkper.Billing>)*

This class defines the Billing information for a `User`.

The Billing information includes the plan, the admin email, and the billing portal URL.

**Constructor:** `new Billing(json?: bkper.Billing, config?: Config)`

**Properties:**

- `payload`: `bkper.Billing` — The underlying payload data for this resource

**Methods:**

- `getAdminEmail()` → `string | undefined` — Gets the admin email for this User's billing account.
- `getCheckoutUrl(plan: string, successUrl?: string, cancelUrl?: string, cycle?: string)` → `Promise<string | undefined>` — Gets the URL to redirect the User to the billing checkout.
- `getCounts()` → `Promise<bkper.Counts>` — Gets the transaction counts associated to the User's billing account.
- `getDaysLeftInTrial()` → `number | undefined` — Gets the number of days left in User's trial period.
- `getEmail()` → `string | undefined` — Gets the email for the User.
- `getHostedDomain()` → `string | undefined` — Gets the hosted domain for the User.
- `getPlan()` → `string | undefined` — Gets the current plan of the User.
- `getPortalUrl(returnUrl: string)` → `Promise<string | undefined>` — Gets the URL to redirect the User to the billing portal.
- `getTotalTransactionsThisMonth()` → `number | undefined` — Gets the number of total transactions this month for the User's billing account.
- `getTotalTransactionsThisYear()` → `number | undefined` — Gets the number of total transactions this year for the User's billing account.
- `hasStartedTrial()` → `boolean | undefined` — Tells if the User has started the trial period.
- `isEnabled()` → `boolean | undefined` — Tells if billing is enabled for the User.
- `isPlanOverdue()` → `boolean | undefined` — Tells if the User's current plan payment is overdue.
- `json()` → `bkper.Billing` — Gets an immutable copy of the JSON payload for this resource.

### Bkper

This is the main entry point of the [bkper-js](https://www.npmjs.com/package/bkper-js) library.

You can configure the library in two ways:

1. Using static configuration (traditional approach):

```typescript
Bkper.setConfig({
  apiKeyProvider: () => process.env.BKPER_API_KEY,
  oauthTokenProvider: () => process.env.BKPER_OAUTH_TOKEN
});

const bkper = new Bkper();
const book = await bkper.getBook('bookId');
```

2. Using per-instance configuration (recommended for Cloudflare Workers):

```typescript
const bkper = new Bkper({
  apiKeyProvider: () => process.env.BKPER_API_KEY,
  oauthTokenProvider: () => process.env.BKPER_OAUTH_TOKEN
});

const book = await bkper.getBook('bookId');
```

**Constructor:** `new Bkper(config?: Config)`

Creates a new Bkper instance with the provided configuration.

**Methods:**

- `getApp(id: string)` → `Promise<App>` — Gets the `App` with the specified id.
- `getApps()` → `Promise<App[]>` — Gets all `Apps` available for the user.
- `getBook(id: string, includeAccounts?: boolean, includeGroups?: boolean)` → `Promise<Book>` — Gets the `Book` with the specified bookId from url param.
- `getBooks(query?: string)` → `Promise<Book[]>` — Gets all `Books` the user has access to.
- `getCollections()` → `Promise<Collection[]>` — Gets all `Collections` the user has access to.
- `getConfig()` → `Config` — Gets the current instance configuration.
- `getTemplates()` → `Promise<Template[]>` — Gets all `Templates` available for the user.
- `getUser()` → `Promise<User>` — Gets the current logged `User`.
- `static setConfig(config: Config)` → `void` — Sets the global API configuration for all Bkper operations.

**setConfig**

WARNING: This configuration will be shared and should NOT be used on shared environments.

### BkperError *(extends Error)*

Standard error class for Bkper API errors.
Extends Error to enable instanceof checks and standard error handling.

**Constructor:** `new BkperError(code: number, message: string, reason?: string)`

**Properties:**

- `readonly code`: `number` — HTTP status code (e.g., 404, 400, 500)
- `message`: `string`
- `name`: `string`
- `readonly reason?`: `string` — Machine-readable reason (e.g., "notFound", "badRequest")
- `stack?`: `string`
- `static prepareStackTrace?`: `(err: Error, stackTraces: __global.NodeJS.CallSite[]) => any` — Optional override for formatting stack traces
- `static stackTraceLimit`: `number`

**Methods:**

- `static captureStackTrace(targetObject: object, constructorOpt?: Function)` → `void` — Create .stack property on a target object

### Book *(extends ResourceProperty<bkper.Book>)*

A Book represents a [General Ledger](https://en.wikipedia.org/wiki/General_ledger) for a company or business, but can also represent a [Ledger](https://en.wikipedia.org/wiki/Ledger) for a project or department

It contains all `Accounts` where `Transactions` are recorded/posted;

**Constructor:** `new Book(payload?: bkper.Book, config?: Config)`

**Properties:**

- `payload`: `bkper.Book` — The underlying payload data for this resource

**Methods:**

- `audit()` → `void` — Trigger Balances Audit async process.
- `batchCheckTransactions(transactions: Transaction[])` → `Promise<void>` — Batch check `Transactions` on the Book.
- `batchCreateAccounts(accounts: Account[])` → `Promise<Account[]>` — Create `Accounts` on the Book, in batch.
- `batchCreateGroups(groups: Group[])` → `Promise<Group[]>` — Create `Groups` on the Book, in batch.
- `batchCreateTransactions(transactions: Transaction[])` → `Promise<Transaction[]>` — Batch create `Transactions` on the Book.
- `batchDeleteAccounts(accounts: Account[])` → `Promise<Account[]>` — Delete `Accounts` on the Book, in batch.
- `batchPostTransactions(transactions: Transaction[])` → `Promise<void>` — Batch post `Transactions` on the Book.
- `batchReplayEvents(events: Event[], errorOnly?: boolean)` → `Promise<void>` — Replay `Events` on the Book, in batch.
- `batchTrashTransactions(transactions: Transaction[], trashChecked?: boolean)` → `Promise<void>` — Batch trash `Transactions` on the Book.
- `batchUncheckTransactions(transactions: Transaction[])` → `Promise<void>` — Batch uncheck `Transactions` on the Book.
- `batchUntrashTransactions(transactions: Transaction[])` → `Promise<void>` — Batch untrash `Transactions` on the Book.
- `batchUpdateAccounts(accounts: Account[])` → `Promise<Account[]>` — Update `Accounts` on the Book, in batch.
- `batchUpdateTransactions(transactions: Transaction[], updateChecked?: boolean)` → `Promise<Transaction[]>` — Batch update `Transactions` on the Book.
- `copy(name: string, copyTransactions?: boolean, fromDate?: number)` → `Promise<Book>` — Creates a copy of this Book
- `countTransactions(query?: string)` → `Promise<number | undefined>` — Retrieve the number of transactions based on a query.
- `create()` → `Promise<Book>` — Performs create new Book.
- `createAccountsDataTable(accounts?: Account[])` → `Promise<AccountsDataTableBuilder>` — Create a `AccountsDataTableBuilder`, to build two dimensional Array representations of `Account` dataset.
- `createGroupsDataTable(groups?: Group[])` → `Promise<GroupsDataTableBuilder>` — Create a `GroupsDataTableBuilder`, to build two dimensional Array representations of `Group` dataset.
- `createIntegration(integration: bkper.Integration | Integration)` → `Promise<Integration>` — Creates a new `Integration` in the Book.
- `createTransactionsDataTable(transactions: Transaction[], account?: Account)` → `TransactionsDataTableBuilder` — Create a `TransactionsDataTableBuilder`, to build two dimensional Array representations of `Transaction` dataset.
- `formatDate(date: Date, timeZone?: string)` → `string` — Formats a date according to date pattern of the Book.
- `formatValue(value: number | Amount | null | undefined)` → `string` — Formats a value according to `DecimalSeparator` and fraction digits of the Book.
- `getAccount(idOrName?: string)` → `Promise<Account | undefined>` — Gets an `Account` object by id or name.
- `getAccounts()` → `Promise<Account[]>` — Gets all `Accounts` of this Book with full account-group relationships.
- `getApps()` → `Promise<App[]>` — Retrieve installed `Apps` for this Book.
- `getAutoPost()` / `setAutoPost(autoPost: boolean)` → `boolean | undefined (set: boolean)` — Gets the auto post status of the Book.
- `getBacklog()` → `Promise<Backlog>` — Gets the Backlog of this Book.
- `getBalancesReport(query: string)` → `Promise<BalancesReport>` — Create a `BalancesReport` based on query.
- `getClosingDate()` / `setClosingDate(closingDate: string | null)` → `string | undefined (set: string | null)` — Gets the closing date of the Book in ISO format yyyy-MM-dd.
- `getCollaborators()` → `Promise<Collaborator[]>` — Gets all collaborators of this Book.
- `getCollection()` → `Collection | undefined` — Gets the collection of this Book, if any.
- `getDatePattern()` / `setDatePattern(datePattern: string)` → `string` — Gets the date pattern of the Book.
- `getDecimalPlaces()` → `number | undefined` — Gets the number of decimal places supported by this Book.
- `getDecimalSeparator()` / `setDecimalSeparator(decimalSeparator: DecimalSeparator)` → `DecimalSeparator` — Gets the decimal separator of the Book.
- `getFile(id: string)` → `Promise<File | undefined>` — Retrieve a file by id.
- `getFractionDigits()` / `setFractionDigits(fractionDigits: number)` → `number | undefined (set: number)` — Gets the number of fraction digits supported by this Book.
- `getGroup(idOrName?: string)` → `Promise<Group | undefined>` — Gets a `Group` object by id or name.
- `getGroups()` → `Promise<Group[]>` — Gets all `Groups` of this Book with complete parent/child hierarchy.
- `getId()` → `string` — Gets the unique identifier of this Book.
- `getIntegrations()` → `Promise<Integration[]>` — Gets the existing `Integrations` in the Book.
- `getLastUpdateMs()` → `number | undefined` — Gets the last update date of the book, in milliseconds.
- `getLockDate()` / `setLockDate(lockDate: string | null)` → `string | undefined (set: string | null)` — Gets the lock date of the Book in ISO format yyyy-MM-dd.
- `getLogoUrl()` → `string | undefined` — Gets the logo URL of the Book owner's custom domain, if any.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of this Book.
- `getOwnerName()` → `string | undefined` — Gets the name of the owner of the Book.
- `getPageSize()` / `setPageSize(pageSize: number)` → `number | undefined (set: number)` — Gets the transactions pagination page size.
- `getPeriod()` / `setPeriod(period: Period)` → `Period` — Gets the period slice for balances visualization.
- `getPeriodStartMonth()` / `setPeriodStartMonth(month: Month)` → `Month` — Gets the start month when YEAR period is set.
- `getPermission()` → `Permission` — Gets the permission for the current user in this Book.
- `getSavedQueries()` → `Promise<Query[]>` — Gets the saved queries from this book.
- `getTimeZone()` / `setTimeZone(timeZone: string)` → `string | undefined (set: string)` — Gets the time zone of the Book.
- `getTimeZoneOffset()` → `number | undefined` — Gets the time zone offset of the book, in minutes.
- `getTotalTransactions()` → `number` — Gets the total number of posted transactions.
- `getTotalTransactionsCurrentMonth()` → `number` — Gets the total number of posted transactions on current month.
- `getTotalTransactionsCurrentYear()` → `number` — Gets the total number of posted transactions on current year.
- `getTransaction(id: string)` → `Promise<Transaction | undefined>` — Retrieve a transaction by id.
- `getVisibility()` / `setVisibility(visibility: Visibility)` → `Visibility` — Gets the visibility of the book.
- `json()` → `bkper.Book` — Gets an immutable copy of the JSON payload for this resource.
- `listEvents(afterDate: string | null, beforeDate: string | null, onError: boolean, resourceId: string | null, limit: number, cursor?: string)` → `Promise<EventList>` — Lists events in the Book based on the provided parameters.
- `listTransactions(query?: string, limit?: number, cursor?: string)` → `Promise<TransactionList>` — Lists transactions in the Book based on the provided query, limit, and cursor, for pagination.
- `mergeTransactions(transaction1: Transaction, transaction2: Transaction)` → `Promise<Transaction>` — Merge two `Transactions` into a single new canonical transaction.
- `parseDate(date: string)` → `Date` — Parse a date string according to date pattern and timezone of the Book. Also parse ISO yyyy-mm-dd format.
- `parseValue(value: string)` → `Amount | undefined` — Parse a value string according to `DecimalSeparator` and fraction digits of the Book.
- `remove()` → `Promise<Book>` — Warning!
- `round(value: number | Amount)` → `Amount` — Rounds a value according to the number of fraction digits of the Book.
- `update()` → `Promise<Book>` — Perform update Book, applying pending changes.
- `updateIntegration(integration: bkper.Integration)` → `Promise<Integration>` — Updates an existing `Integration` in the Book.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**getAccount**

Results are cached to avoid repeated server calls. Account-group relationships
are included if the full chart was loaded via getAccounts() or when the Book
was loaded with includeAccounts=true.

```typescript
// Get individual account (basic data, cached)
const account = await book.getAccount('Bank Account');

// For account-group relationships, use one of these approaches:
// Option 1: Load book with full data upfront
const bookWithAccounts = await Bkper.getBook(bookId, true);
const accountWithGroups = await bookWithAccounts.getAccount('Bank Account');

// Option 2: Load full chart when needed
await book.getAccounts();
const accountWithGroups2 = await book.getAccount('Bank Account');
```

**getAccounts**

Results are cached for performance. Groups are automatically loaded first
to ensure proper linking. Consider using Bkper.getBook(id, true) for
upfront loading when you know you'll need all accounts.

```typescript
// Load all accounts with complete relationships
const accounts = await book.getAccounts();

// Alternative: Load book with accounts upfront (more efficient)
const bookWithAccounts = await Bkper.getBook(bookId, true);
const accounts2 = await bookWithAccounts.getAccounts(); // Already cached
```

**getBalancesReport**

The balances report

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var balancesReport = book.getBalancesReport("group:'Equity' after:7/2018 before:8/2018");

var accountBalance = balancesReport.getBalancesContainer("Bank Account").getCumulativeBalance();
```

**getGroup**

Results are cached to avoid repeated server calls. Parent/child relationships
are included if all groups were loaded via getGroups() or when the Book was
loaded with includeGroups=true.

```typescript
// Get individual group (basic data, cached)
const group = await book.getGroup('Assets');

// For parent/child relationships, use one of these approaches:
// Option 1: Load book with full hierarchy upfront
const bookWithGroups = await Bkper.getBook(bookId, false, true);
const groupWithTree = await bookWithGroups.getGroup('Assets');

// Option 2: Load full hierarchy when needed
await book.getGroups();
const groupWithTree2 = await book.getGroup('Assets');
console.log(groupWithTree2.getParent(), groupWithTree2.getChildren());
```

**getGroups**

Results are cached for performance. Group tree relationships are built
during loading. Consider using Bkper.getBook(id, false, true) for
upfront loading when you know you'll need all groups.

```typescript
// Load all groups with complete hierarchy
const groups = await book.getGroups();

// Alternative: Load book with groups upfront (more efficient)
const bookWithGroups = await Bkper.getBook(bookId, false, true);
const groups2 = await bookWithGroups.getGroups(); // Already cached
```

**mergeTransactions**

The merged transaction is created synchronously. Cleanup of the two
originals is scheduled asynchronously by the backend.

**remove**

Deletes this Book and all its data (transactions, accounts, groups). Book owner only.

### BooksDataTableBuilder

A BooksDataTableBuilder is used to setup and build two-dimensional arrays containing books.

**Constructor:** `new BooksDataTableBuilder(books: Book[])`

**Methods:**

- `build()` → `any[][]` — Builds a two-dimensional array containing all Books.
- `hiddenProperties(include: boolean)` → `BooksDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `BooksDataTableBuilder` — Defines whether to include book ids.
- `properties(include: boolean)` → `BooksDataTableBuilder` — Defines whether to include custom book properties.

### BotResponse

This class defines a Bot Response associated to an `Event`.

**Constructor:** `new BotResponse(event: Event, payload?: bkper.BotResponse)`

**Properties:**

- `payload`: `bkper.BotResponse`

**Methods:**

- `getAgentId()` → `string | undefined` — Gets the agent id of this Bot Response.
- `getCreatedAt()` → `Date | undefined` — Gets the date this Bot Response was created.
- `getEvent()` → `Event` — Gets the Event this Bot Response is associated to.
- `getMessage()` → `string | undefined` — Gets the message of this Bot Response.
- `getType()` → `BotResponseType | undefined` — Gets the type of this Bot Response.
- `remove()` → `Promise<BotResponse>` — Delete this Bot Response.
- `replay()` → `Promise<BotResponse>` — Replay this Bot Response.

### Collaborator *(extends Resource<bkper.Collaborator>)*

This class defines a Collaborator of a `Book`.

A Collaborator represents a user that has been granted access to a Book with specific permissions.

**Constructor:** `new Collaborator(book: Book, payload?: bkper.Collaborator)`

**Properties:**

- `payload`: `bkper.Collaborator` — The underlying payload data for this resource

**Methods:**

- `create(message?: string)` → `Promise<Collaborator>` — Performs create new Collaborator.
- `getEmail()` / `setEmail(email: string)` → `string | undefined (set: string)` — Gets the Collaborator email address.
- `getId()` → `string | undefined` — Gets the Collaborator internal id.
- `getPermission()` / `setPermission(permission: Permission)` → `Permission | undefined (set: Permission)` — Gets the permission level of the Collaborator.
- `json()` → `bkper.Collaborator` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Collaborator>` — Performs remove Collaborator.
- `update()` → `Promise<Collaborator>` — Performs update Collaborator.

### Collection *(extends Resource<bkper.Collection>)*

This class defines a Collection of `Books`.

**Constructor:** `new Collection(payload?: bkper.Collection, config?: Config)`

**Properties:**

- `payload`: `bkper.Collection` — The underlying payload data for this resource

**Methods:**

- `addBooks(books: Book[])` → `Promise<Book[]>` — Adds Books to this Collection.
- `create()` → `Promise<Collection>` — Performs create new Collection.
- `getBooks()` → `Book[]` — Gets all Books of this collection.
- `getId()` → `string | undefined` — Gets the unique identifier of this Collection.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of this Collection.
- `getOwnerUsername()` → `string | undefined` — Gets the username of the owner of this Collection
- `getPermission()` → `Permission | undefined` — Gets the user permission for this Collection
- `getUpdatedAt()` → `string | undefined` — Gets the last update date of this Collection
- `json()` → `bkper.Collection` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Book[]>` — Performs delete Collection.
- `removeBooks(books: Book[])` → `Promise<Book[]>` — Removes Books from this Collection.
- `update()` → `Promise<Collection>` — Performs update Collection, applying pending changes.

### Connection *(extends ResourceProperty<bkper.Connection>)*

This class defines a Connection from an `User` to an external service.

**Constructor:** `new Connection(payload?: bkper.Connection, config?: Config)`

**Properties:**

- `payload`: `bkper.Connection` — The underlying payload data for this resource

**Methods:**

- `clearTokenProperties()` → `void` — Cleans any token property stored in the Connection.
- `create()` → `Promise<Connection>` — Performs create new Connection.
- `getAgentId()` / `setAgentId(agentId: string)` → `string | undefined (set: string)` — Gets the agentId of the Connection.
- `getDateAddedMs()` → `string | undefined` — Gets the date when the Connection was added.
- `getEmail()` → `string | undefined` — Gets the email of the owner of the Connection.
- `getId()` → `string | undefined` — Gets the id of the Connection.
- `getIntegrations()` → `Promise<Integration[]>` — Gets the existing `Integrations` on the Connection.
- `getLogo()` → `string | undefined` — Gets the logo of the Connection.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of the Connection.
- `getType()` / `setType(type: "APP" | "BANK")` → `"APP" | "BANK" | undefined (set: "APP" | "BANK")` — Gets the type of the Connection.
- `getUUID()` / `setUUID(uuid: string)` → `string | undefined (set: string)` — Gets the universal unique identifier of this Connection.
- `json()` → `bkper.Connection` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Connection>` — Performs remove Connection.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### Event

This class defines an Event from a `Book`.

An event is an object that represents an action (such as posting or deleting a `Transaction`) made by an actor (such as a user or a [Bot](https://bkper.com/apps) acting on behalf of a user).

**Constructor:** `new Event(book: Book, payload?: bkper.Event)`

**Properties:**

- `payload`: `bkper.Event`

**Methods:**

- `getAgent()` → `Agent | undefined` — Gets the Agent who performed the Event.
- `getBook()` → `Book` — Gets the book in which the Event was created.
- `getBotResponses()` → `BotResponse[]` — Gets the Bot Responses associated to this Event.
- `getCreatedAt()` → `Date | undefined` — Gets the date the Event was created.
- `getId()` → `string | undefined` — Gets the id of the Event.
- `getType()` → `EventType | undefined` — Gets the type of the Event.
- `getUser()` → `User | undefined` — Gets the user who performed the Event.
- `hasErrorResponse()` → `boolean` — Checks if this Event has at least one Bot Response of type ERROR.
- `json()` → `bkper.Event` — Gets an immutable copy of the JSON payload for this Event.

### EventList

A list associated with an event query.

**Constructor:** `new EventList(book: Book, payload: bkper.EventList)`

**Methods:**

- `getCursor()` → `string | undefined` — Gets the cursor associated with the query for pagination.
- `getFirst()` → `Event | undefined` — Gets the first Event in the list.
- `getItems()` → `Event[]` — Get the events in the list.
- `size()` → `number` — Get the total number of events in the list.

### File *(extends ResourceProperty<bkper.File>)*

This class defines a File uploaded to a `Book`.

A File can be attached to a `Transaction` or used to import data.

**Constructor:** `new File(book: Book, payload?: bkper.File)`

**Properties:**

- `payload`: `bkper.File` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<File>` — Perform create new File.
- `getBook()` → `Book` — Gets the Book this File belongs to.
- `getContent()` / `setContent(content: string)` → `Promise<string | undefined> (set: string)` — Gets the file content Base64 encoded.
- `getContentType()` / `setContentType(contentType: string)` → `string | undefined (set: string)` — Gets the File content type.
- `getId()` → `string | undefined` — Gets the File id.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the File name.
- `getSize()` → `number | undefined` — Gets the file size in bytes.
- `getUrl()` → `string | undefined` — Gets the file serving url for accessing via browser.
- `json()` → `bkper.File` — Gets an immutable copy of the JSON payload for this resource.
- `update()` → `Promise<File>` — Perform update File, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### Group *(extends ResourceProperty<bkper.Group>)*

This class defines a Group of `Accounts`.

Accounts can be grouped by different meaning, like Expenses, Revenue, Assets, Liabilities and so on

Its useful to keep organized and for high level analysis.

**Constructor:** `new Group(book: Book, payload?: bkper.Group)`

**Properties:**

- `payload`: `bkper.Group` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<Group>` — Performs create new group.
- `getAccounts()` → `Promise<Account[]>` — Gets all Accounts of this group.
- `getChildren()` → `Group[]` — Gets the children of the Group.
- `getDepth()` → `number` — Gets the depth of the Group in the hierarchy.
- `getDescendants()` → `Set<Group>` — Gets all descendant Groups of the current Group.
- `getDescendantTreeIds()` → `Set<string>` — Gets the IDs of all descendant Groups in a tree structure.
- `getId()` → `string | undefined` — Gets the id of this Group.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of this Group.
- `getNormalizedName()` → `string` — Gets the normalized name of this group without spaces and special characters.
- `getParent()` / `setParent(group: Group | null | undefined)` → `Group | undefined (set: Group | null | undefined)` — Gets the parent Group.
- `getRoot()` → `Group` — Gets the root Group of the current Group.
- `getRootName()` → `string` — Gets the name of the root Group.
- `getType()` → `AccountType` — Gets the type of the accounts of this group.
- `hasAccounts()` → `boolean | undefined` — Tells if this group has any account in it.
- `hasChildren()` → `boolean` — Checks if the Group has any children.
- `hasParent()` → `boolean` — Checks if the Group has a parent.
- `isBalanceVerified()` → `Promise<boolean | undefined>` — Tells if the balance of this Group has been verified/audited.
- `isCredit()` → `boolean | undefined` — Tells if this is a credit (Incoming and Liabilities) group.
- `isHidden()` → `boolean | undefined` — Tells if the Group is hidden on main transactions menu.
- `isLeaf()` → `boolean` — Checks if the Group is a leaf node (i.e., has no children).
- `isLocked()` → `boolean` — Tells if the Group is locked by the Book owner.
- `isMixed()` → `boolean | undefined` — Tells if this is a mixed (Assets/Liabilities or Incoming/Outgoing) group.
- `isPermanent()` → `boolean | undefined` — Tells if the Group is permanent.
- `isRoot()` → `boolean` — Checks if the Group is a root node (i.e., has no parent).
- `json()` → `bkper.Group` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Group>` — Performs delete group.
- `setHidden(hidden: boolean)` → `Group` — Hide/Show group on main menu.
- `setLocked(locked: boolean)` → `Group` — Sets the locked state of the Group.
- `update()` → `Promise<Group>` — Performs update group, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### GroupsDataTableBuilder

A GroupsDataTableBuilder is used to setup and build two-dimensional arrays containing groups.

**Constructor:** `new GroupsDataTableBuilder(groups: Group[])`

**Methods:**

- `build()` → `any[][]` — Builds a two-dimensional array containing all Groups.
- `hiddenProperties(include: boolean)` → `GroupsDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `GroupsDataTableBuilder` — Defines whether include group ids.
- `properties(include: boolean)` → `GroupsDataTableBuilder` — Defines whether include custom group properties.
- `tree(enable: boolean)` → `GroupsDataTableBuilder` — Defines whether to render groups as an indented tree instead of flat rows with a Parent column.

### Integration *(extends ResourceProperty<bkper.Integration>)*

This class defines a Integration from an `User` to an external service.

**Constructor:** `new Integration(payload?: bkper.Integration, config?: Config)`

**Properties:**

- `payload`: `bkper.Integration` — The underlying payload data for this resource

**Methods:**

- `getAddedBy()` → `string | undefined` — Gets the name of the user who added the Integration.
- `getAgentId()` → `string | undefined` — Gets the agent id of the Integration.
- `getBookId()` → `string | undefined` — Gets the `Book` id of the Integration.
- `getDateAddedMs()` → `string | undefined` — Gets the date when the Integration was added.
- `getId()` → `string | undefined` — Gets the id of the Integration.
- `getLastUpdateMs()` → `string | undefined` — Gets the date when the Integration was last updated.
- `getLogo()` → `string | undefined` — ~~Deprecated: Use getLogoUrl instead.~~ Gets the logo of the Integration.
- `getLogoUrl()` → `string | undefined` — Gets the logo url of this Integration.
- `getLogoUrlDark()` → `string | undefined` — Gets the logo url of this Integration in dark mode.
- `getName()` → `string | undefined` — Gets the name of the Integration.
- `json()` → `bkper.Integration` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Integration>` — Performs remove Integration.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### Query *(extends Resource<bkper.Query>)*

Defines a saved Query in a `Book`.

Queries can be saved on Books by users.

**Constructor:** `new Query(book: Book, payload?: bkper.Query)`

**Properties:**

- `payload`: `bkper.Query` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<Query>` — Perform create new Query.
- `getId()` → `string | undefined` — Gets the Query universal identifier.
- `getQuery()` / `setQuery(query: string)` → `string | undefined (set: string)` — Gets the query string to be executed.
- `getTitle()` / `setTitle(title: string)` → `string | undefined (set: string)` — Gets the title of this saved Query.
- `json()` → `bkper.Query` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Query>` — Perform delete Query.
- `update()` → `Promise<Query>` — Perform update Query, applying pending changes.

### Template *(extends Resource<bkper.Template>)*

This class defines a Template.

A Template is a pre-configured setup for `Books` and associated Google Sheets that provides users with a starting point for specific accounting or financial management needs.

**Constructor:** `new Template(json?: bkper.Template, config?: Config)`

**Properties:**

- `payload`: `bkper.Template` — The underlying payload data for this resource

**Methods:**

- `getBookId()` → `string | undefined` — Gets the bookId of the `Book` associated with the Template.
- `getBookLink()` → `string | undefined` — Gets the link of the `Book` associated with the Template.
- `getCategory()` → `string | undefined` — Gets the category of the Template.
- `getDescription()` → `string | undefined` — Gets the description of the Template.
- `getImageUrl()` → `string | undefined` — Gets the url of the image of the Template.
- `getName()` → `string | undefined` — Gets the name of the Template.
- `getSheetsLink()` → `string | undefined` — Gets the link of the Google Sheets spreadsheet associated with the Template.
- `getTimesUsed()` → `number` — Gets the times the Template has been used.
- `json()` → `bkper.Template` — Gets an immutable copy of the JSON payload for this resource.

### Transaction *(extends ResourceProperty<bkper.Transaction>)*

This class defines a Transaction between [credit and debit](http://en.wikipedia.org/wiki/Debits_and_credits) `Accounts`.

A Transaction is the main entity on the [Double Entry](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system) [Bookkeeping](http://en.wikipedia.org/wiki/Bookkeeping) system.

**Constructor:** `new Transaction(book: Book, payload?: bkper.Transaction)`

**Properties:**

- `payload`: `bkper.Transaction` — The underlying payload data for this resource

**Methods:**

- `addFile(file: File)` → `Transaction` — Adds a file attachment to the Transaction.
- `addRemoteId(remoteId: string)` → `Transaction` — Add a remote id to the Transaction.
- `addUrl(url: string)` → `Transaction` — Add a url to the Transaction. Url starts with https://
- `check()` → `Promise<Transaction>` — Perform check transaction.
- `create()` → `Promise<Transaction>` — Perform create new draft transaction.
- `from(account: bkper.Account | Account | null | undefined)` → `Transaction` — Sets the credit/origin `Account` of this Transaction. Same as setCreditAccount()
- `getAccountBalance(raw?: boolean)` → `Promise<Amount | undefined>` — Gets the balance that the `Account` has at that day, when listing transactions of that Account.
- `getAgentId()` → `string | undefined` — Gets the unique identifier of the agent that created this transaction.
- `getAgentLogoUrl()` → `string | undefined` — Gets the logo URL of the agent that created this transaction.
- `getAgentLogoUrlDark()` → `string | undefined` — Gets the dark mode logo URL of the agent that created this transaction.
- `getAgentName()` → `string | undefined` — Gets the name of the agent that created this transaction.
- `getAmount()` / `setAmount(amount: string | number | Amount)` → `Amount | undefined (set: string | number | Amount)` — Gets the amount of this Transaction.
- `getAmountFormatted()` → `string | undefined` — Gets the formatted amount of this Transaction according to the Book format.
- `getBook()` → `Book` — Gets the book associated with this transaction.
- `getCreatedAt()` → `Date` — Gets the date when the transaction was created.
- `getCreatedAtFormatted()` → `string` — Gets the formatted creation date of the transaction.
- `getCreatedBy()` → `string | undefined` — Gets the username of the user who created the transaction.
- `getCreditAccount()` / `setCreditAccount(account: bkper.Account | Account | null | undefined)` → `Promise<Account | undefined> (set: bkper.Account | Account | null | undefined)` — Gets the credit account associated with this Transaction. Same as origin account
- `getCreditAccountName()` → `Promise<string | undefined>` — Gets the name of this Transaction's credit account.
- `getCreditAmount(account: string | Account)` → `Promise<Amount | undefined>` — Get the absolute amount of this Transaction if the given account is at the credit side.
- `getDate()` / `setDate(date: string | Date)` → `string | undefined (set: string | Date)` — Gets the transaction date in ISO format.
- `getDateFormatted()` → `string | undefined` — Gets the transaction date formatted according to the book's date pattern.
- `getDateObject()` → `Date` — Gets the transaction date as a Date object in the book's timezone.
- `getDateValue()` → `number | undefined` — Gets the transaction date as a numeric value.
- `getDebitAccount()` / `setDebitAccount(account: bkper.Account | Account | null | undefined)` → `Promise<Account | undefined> (set: bkper.Account | Account | null | undefined)` — Gets the debit account associated with this Transaction. Same as destination account
- `getDebitAccountName()` → `Promise<string | undefined>` — Gets the name of this Transaction's debit account.
- `getDebitAmount(account: string | Account)` → `Promise<Amount | undefined>` — Gets the absolute amount of this Transaction if the given account is at the debit side.
- `getDescription()` / `setDescription(description: string)` → `string` — Gets the description of this Transaction.
- `getFiles()` → `File[]` — Gets all files attached to the transaction.
- `getId()` → `string | undefined` — Gets the unique identifier of the transaction.
- `getOtherAccount(account: string | Account)` → `Promise<Account | undefined>` — Gets the `Account` at the other side of the transaction given the one in one side.
- `getOtherAccountName(account: string | Account)` → `Promise<string | undefined>` — The Account name at the other side of this Transaction given the one in one side.
- `getRemoteIds()` → `string[]` — Gets the remote IDs associated with this transaction. Remote ids are used to avoid duplication.
- `getStatus()` → `TransactionStatus` — Gets the status of the transaction.
- `getTags()` → `string[]` — Gets all hashtags used in the transaction.
- `getUpdatedAt()` → `Date` — Gets the date when the transaction was last updated.
- `getUpdatedAtFormatted()` → `string` — Gets the formatted last update date of the transaction.
- `getUrls()` / `setUrls(urls: string[])` → `string[]` — Gets all URLs associated with the transaction.
- `hasTag(tag: string)` → `boolean` — Check if the transaction has the specified tag.
- `isChecked()` → `boolean | undefined` — Checks if the transaction is marked as checked.
- `isCredit(account?: Account)` → `Promise<boolean>` — Tell if the given account is credit on this Transaction
- `isDebit(account?: Account)` → `Promise<boolean>` — Tell if the given account is debit on the Transaction
- `isLocked()` → `boolean` — Checks if the transaction is locked by the book's lock or closing date.
- `isPosted()` → `boolean | undefined` — Checks if the transaction has been posted to the accounts.
- `isTrashed()` → `boolean | undefined` — Checks if the transaction is in the trash.
- `json()` → `bkper.Transaction` — Gets an immutable copy of the JSON payload for this resource.
- `post()` → `Promise<Transaction>` — Perform post transaction, changing credit and debit `Account` balances.
- `removeFile(file: File)` → `Transaction` — Removes a file attachment from the Transaction.
- `setChecked(checked: boolean)` → `Transaction` — Set the check state of the Transaction.
- `to(account: bkper.Account | Account | null | undefined)` → `Transaction` — Sets the debit/destination `Account` of this Transaction. Same as setDebitAccount()
- `trash()` → `Promise<Transaction>` — Trash the transaction.
- `uncheck()` → `Promise<Transaction>` — Perform uncheck transaction.
- `untrash()` → `Promise<Transaction>` — Untrash the transaction.
- `update()` → `Promise<Transaction>` — Update transaction, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**addFile**

Files not previously created in the Book will be automatically created when the transaction is persisted.

**getAccountBalance**

Evolved balances is returned when searching for transactions of a permanent `Account`.

Only comes with the last posted transaction of the day.

### TransactionList

A list associated with a transaction query.

**Constructor:** `new TransactionList(book: Book, payload: bkper.TransactionList)`

**Methods:**

- `getAccount()` → `Promise<Account | undefined>` — Retrieves the account associated with the query, when filtering by account.
- `getCursor()` → `string | undefined` — Gets the cursor associated with the query for pagination.
- `getFirst()` → `Transaction | undefined` — Gets the first Transaction in the list.
- `getItems()` → `Transaction[]` — Gets the transactions in the list.
- `size()` → `number` — Gets the total number of transactions in the list.

### TransactionsDataTableBuilder

A TransactionsDataTableBuilder is used to setup and build two-dimensional arrays containing transactions.

**Constructor:** `new TransactionsDataTableBuilder(book: Book, transactions: Transaction[], account?: Account)`

**Methods:**

- `build()` → `Promise<any[][]>` — Builds a two-dimensional array containing all transactions.
- `formatDates(format: boolean)` → `TransactionsDataTableBuilder` — Defines whether the dates should be formatted, based on date pattern of the `Book`.
- `formatValues(format: boolean)` → `TransactionsDataTableBuilder` — Defines whether amounts should be formatted based on `DecimalSeparator` of the `Book`.
- `getAccount()` → `Account | undefined` — Gets the account used to filter transactions, when applicable.
- `hiddenProperties(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include transaction ids and remote ids.
- `includeIds(include: boolean)` → `TransactionsDataTableBuilder` — ~~Deprecated: Use `ids` instead.~~
- `includeProperties(include: boolean)` → `TransactionsDataTableBuilder` — ~~Deprecated: Use `properties` instead.~~
- `includeUrls(include: boolean)` → `TransactionsDataTableBuilder` — ~~Deprecated: Use `urls` instead.~~
- `properties(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include custom transaction properties.
- `recordedAt(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include the "Recorded at" column.
- `urls(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include attachments and url links.

### User *(extends Resource<bkper.User>)*

This class defines a User on the Bkper platform.

Users can own and collaborate on `Books`, manage `Collections`, and connect to external services through `Connections`.

Each User has a unique identity, subscription plan details, and access permissions across the platform.

**Constructor:** `new User(payload?: bkper.User, config?: Config)`

**Properties:**

- `payload`: `bkper.User` — The underlying payload data for this resource

**Methods:**

- `getAvatarUrl()` → `string | undefined` — Gets the avatar url of the User.
- `getBilling()` → `Promise<Billing>` — Gets the billing information for this User.
- `getConnection(id: string)` → `Promise<Connection>` — Gets a `Connection` of the User.
- `getConnections()` → `Promise<Connection[]>` — Gets the `Connections` of the User.
- `getEmail()` → `string | undefined` — Gets the email of the User.
- `getFullName()` → `string | undefined` — Gets the full name of the User.
- `getGivenName()` → `string | undefined` — Gets the given name of the User.
- `getHostedDomain()` → `string | undefined` — Gets the hosted domain of the User.
- `getId()` → `string | undefined` — Gets the id of the User.
- `getName()` → `string | undefined` — Gets the name of the User.
- `getUsername()` → `string | undefined` — Gets the username of the User.
- `hasUsedConnections()` → `boolean | undefined` — Tells if the User has already used `Connections`.
- `json()` → `bkper.User` — Gets an immutable copy of the JSON payload for this resource.

## Interfaces

### BalancesContainer

The container of balances of an `Account` or `Group`

The container is composed of a list of `Balances` for a window of time, as well as its period and cumulative totals.

**Properties:**

- `getAccount`: `() => Promise<Account | null>` — Gets the `Account` associated with this container.
- `getBalances`: `() => Balance[]` — Gets all `Balances` of the container
- `getBalancesContainer`: `(name: string) => BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers`: `() => BalancesContainer[]` — Gets all child `BalancesContainers`.
- `getBalancesReport`: `() => BalancesReport` — Gets the parent `BalancesReport` of the container.
- `getCumulativeBalance`: `() => Amount` — Gets the cumulative balance to the date.
- `getCumulativeBalanceRaw`: `() => Amount` — Gets the cumulative raw balance to the date.
- `getCumulativeBalanceRawText`: `() => string` — Gets the cumulative raw balance formatted according to `Book` decimal format and fraction digits.
- `getCumulativeBalanceText`: `() => string` — Gets the cumulative balance formatted according to `Book` decimal format and fraction digits.
- `getDepth`: `() => number` — Gets the depth in the parent chain up to the root.
- `getGroup`: `() => Promise<Group | null>` — Gets the `Group` associated with this container.
- `getName`: `() => string` — Gets the `Account` or `Group` name.
- `getNormalizedName`: `() => string` — Gets the `Account` or `Group` name without spaces or special characters.
- `getParent`: `() => BalancesContainer | null` — Gets the parent BalanceContainer.
- `getPeriodBalance`: `() => Amount` — Gets the balance on the date period.
- `getPeriodBalanceRaw`: `() => Amount` — Gets the raw balance on the date period.
- `getPeriodBalanceRawText`: `() => string` — Gets the raw balance on the date period formatted according to `Book` decimal format and fraction digits.
- `getPeriodBalanceText`: `() => string` — Gets the balance on the date period formatted according to `Book` decimal format and fraction digits.
- `hasGroupBalances`: `() => boolean` — Gets whether the balance container is from a parent group.
- `isCredit`: `() => boolean | undefined` — Gets the credit nature of the BalancesContainer, based on `Account` or `Group`.
- `isFromAccount`: `() => boolean` — Gets whether this balance container is from an `Account`.
- `isFromGroup`: `() => boolean` — Gets whether this balance container is from a `Group`.
- `isPermanent`: `() => boolean` — Tell if this balance container is permanent, based on the `Account` or `Group`.
- `payload`: `bkper.AccountBalances | bkper.GroupBalances`

**Methods:**

- `createDataTable()` → `BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`
- `getCumulativeCredit()` → `Amount` — The cumulative credit to the date.
- `getCumulativeCreditText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getCumulativeDebit()` → `Amount` — The cumulative debit to the date.
- `getCumulativeDebitText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getPeriodCredit()` → `Amount` — The credit on the date period.
- `getPeriodCreditText()` → `string` — The credit on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodDebit()` → `Amount` — The debit on the date period.
- `getPeriodDebitText()` → `string` — The debit on the date period formatted according to `Book` decimal format and fraction digits
- `getProperties()` → `{ [key: string]: string }` — Gets the custom properties stored in this Account or Group.
- `getProperty(keys: string[])` → `string | undefined` — Gets the property value for given keys. First property found will be retrieved
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in the associated `Account` or `Group`.

**getBalancesContainers**

**NOTE**: Only for Group balance containers. Accounts returns null.

**isCredit**

For `Account`, the credit nature will be the same as the one from the Account.

For `Group`, the credit nature will be the same, if all accounts containing on it has the same credit nature. False if mixed.

**isPermanent**

Permanent are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(accountancy)#Based_on_periodicity_of_flow).

Usually represents assets or liabilities, capable of being perceived by the senses or the mind, like bank accounts, money, debts and so on.

### Config

This class defines the `Bkper` API Config.

**Properties:**

- `agentIdProvider?`: `() => Promise<string | undefined>` — Provides the agent ID to identify the calling agent for attribution purposes.
- `apiKeyProvider?`: `() => Promise<string>` — Optional API key for dedicated quota limits.
- `oauthTokenProvider?`: `() => Promise<string | undefined>` — Issue a valid OAuth2 access token with **https://www.googleapis.com/auth/userinfo.email** scope authorized.
- `requestErrorHandler?`: `(error: any) => any` — Custom request error handler
- `requestHeadersProvider?`: `() => Promise<{ [key: string]: string }>` — Provides additional headers to append to the API request
- `requestRetryHandler?`: `(status?: number, error?: any, attempt?: number) => Promise<void>` — Custom request retry handler.

**agentIdProvider**

This ID is sent via the `bkper-agent-id` header with each API request,
allowing the server to attribute actions to the correct agent.

**apiKeyProvider**

If not provided, requests use a shared managed quota via the Bkper API proxy.
Use your own API key for dedicated quota limits and project-level usage tracking.

API keys are for project identification only, not for authentication or agent attribution.
Agent attribution is handled separately via the `agentIdProvider`.

**requestRetryHandler**

This function is called when a request fails and needs to be retried.
It provides the HTTP status code, error message, and the number of retry attempts made so far.

## Enums

### AccountType

Enum that represents account types.

- `ASSET` — Asset account type
- `INCOMING` — Incoming account type
- `LIABILITY` — Liability account type
- `OUTGOING` — Outgoing account type

### BalanceType

Enum that represents balance types.

- `CUMULATIVE` — Cumulative balance
- `PERIOD` — Period balance
- `TOTAL` — Total balance

### BotResponseType

Enum that represents the type of a Bot Response

- `ERROR` — Error bot response
- `INFO` — Info bot response
- `WARNING` — Warning bot response

### DecimalSeparator

Decimal separator of numbers on book

- `COMMA` — ,
- `DOT` — .

### EventType

Enum that represents event types.

- `ACCOUNT_CREATED`
- `ACCOUNT_DELETED`
- `ACCOUNT_UPDATED`
- `BOOK_DELETED`
- `BOOK_UPDATED`
- `COLLABORATOR_ADDED`
- `COLLABORATOR_REMOVED`
- `COLLABORATOR_UPDATED`
- `COMMENT_CREATED`
- `COMMENT_DELETED`
- `FILE_CREATED`
- `FILE_UPDATED`
- `GROUP_CREATED`
- `GROUP_DELETED`
- `GROUP_UPDATED`
- `INTEGRATION_CREATED`
- `INTEGRATION_DELETED`
- `INTEGRATION_UPDATED`
- `QUERY_CREATED`
- `QUERY_DELETED`
- `QUERY_UPDATED`
- `TRANSACTION_CHECKED`
- `TRANSACTION_CREATED`
- `TRANSACTION_DELETED`
- `TRANSACTION_POSTED`
- `TRANSACTION_RESTORED`
- `TRANSACTION_UNCHECKED`
- `TRANSACTION_UPDATED`

### Month

Enum that represents a Month.

- `APRIL`
- `AUGUST`
- `DECEMBER`
- `FEBRUARY`
- `JANUARY`
- `JULY`
- `JUNE`
- `MARCH`
- `MAY`
- `NOVEMBER`
- `OCTOBER`
- `SEPTEMBER`

### Period

Enum that represents a period slice.

- `MONTH` — Monthly period
- `QUARTER` — Quarterly period
- `YEAR` — Yearly period

### Periodicity

The Periodicity of the query. It may depend on the level of granularity you write the range params.

- `DAILY` — Example: after:25/01/1983, before:04/03/2013, after:$d-30, before:$d, after:$d-15/$m
- `MONTHLY` — Example: after:jan/2013, before:mar/2013, after:$m-1, before:$m
- `YEARLY` — Example: on:2013, after:2013, $y

### Permission

Enum representing permissions of user in the Book

- `EDITOR` — Manage accounts, transactions, book configuration and sharing
- `NONE` — No permission
- `OWNER` — Manage everything, including book visibility and deletion. Only one owner per book.
- `POSTER` — View transactions, accounts, record and delete drafts
- `RECORDER` — Record and delete drafts only. Useful to collect data only
- `VIEWER` — View transactions, accounts and balances.

### TransactionStatus

Enum that represents the status of a Transaction.

- `CHECKED` — Transaction is posted and checked
- `DRAFT` — Transaction is a draft, not yet posted
- `TRASHED` — Transaction is in the trash
- `UNCHECKED` — Transaction is posted but not checked

### Visibility

Enum representing the visibility of a Book

- `PRIVATE` — The book can be accessed by the owner and collaborators
- `PUBLIC` — The book can be accessed by anyone with the link

---
source: /docs/api/bkper-web-auth.md

# @bkper/web-auth

> Web authentication SDK for Bkper — OAuth flows, token management, and session handling.

[![npm](https://img.shields.io/npm/v/@bkper/web-auth?color=%235889e4)](https://www.npmjs.com/package/@bkper/web-auth) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--web--sdks-blue?logo=github)](https://github.com/bkper/bkper-web-sdks)

# @bkper/web-auth

OAuth authentication SDK for apps on the [Bkper Platform](https://bkper.com/docs/build/apps/overview) (`*.bkper.app` subdomains).

## Quick Start

```typescript
import { BkperAuth } from '@bkper/web-auth';

// Initialize client with callbacks
const auth = new BkperAuth({
    onLoginSuccess: () => {
        console.log('User authenticated!');
        loadUserData();
    },
    onLoginRequired: () => {
        console.log('Please sign in');
        showLoginButton();
    },
});

// Initialize authentication flow on app load
await auth.init();

// Get access token for API calls
const token = auth.getAccessToken();
if (token) {
    fetch('/api/data', {
        headers: { Authorization: `Bearer ${token}` },
    });
}
```

## Handling Token Expiration

Access tokens expire and need to be refreshed. The recommended pattern is to handle authentication errors and retry:

```typescript
async function apiRequest(url: string, options: RequestInit = {}) {
    // Add auth header
    const token = auth.getAccessToken();
    options.headers = {
        ...options.headers,
        Authorization: `Bearer ${token}`,
    };

    const response = await fetch(url, options);

    // Handle expired token
    if (response.status === 403) {
        try {
            await auth.refresh();
            options.headers = {
                ...options.headers,
                Authorization: `Bearer ${auth.getAccessToken()}`,
            };
            return fetch(url, options); // Retry once
        } catch (error) {
            // Refresh failed - the onError callback will be triggered
            // Handle the error appropriately (e.g., redirect to login, show error message)
            throw error;
        }
    }

    return response;
}
```

## What's Included

-   OAuth authentication SDK for apps on `*.bkper.app` subdomains
-   Callback-based API for authentication events
-   OAuth flow with in-memory token management
-   Token refresh mechanism
-   TypeScript support with full type definitions

## How It Works

**Session Persistence:**

-   Access tokens are stored in-memory (cleared on page refresh)
-   Sessions persist via HTTP-only cookies scoped to the `.bkper.app` domain
-   Call `init()` on app load to restore the session from cookies

> **Note:** This SDK only works for apps hosted on `*.bkper.app` subdomains. For apps on other domains, use a valid access token directly with [bkper-js](https://github.com/bkper/bkper-js#cdn--browser).

**Security:**

-   HTTP-only cookies protect refresh tokens from XSS
-   In-memory access tokens minimize exposure

## TypeScript Support

This package is written in TypeScript and provides full type definitions out of the box. All public APIs are fully typed, including callbacks and configuration options.

```typescript
import { BkperAuth, BkperAuthConfig } from '@bkper/web-auth';

const config: BkperAuthConfig = {
    onLoginSuccess: () => console.log('Authenticated'),
    onError: error => console.error('Auth error:', error),
};

const auth = new BkperAuth(config);
```

## Browser Compatibility

This package requires a modern browser with support for:

-   [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#browser_compatibility) for HTTP requests
-   [Location API](https://developer.mozilla.org/en-US/docs/Web/API/Location) for login/logout redirects

The app must be deployed to a `*.bkper.app` subdomain for session cookies to work.

## Classes

### BkperAuth

OAuth authentication client for the Bkper API.

Provides framework-agnostic authentication with callback-based event handling.
Access tokens are stored in-memory; sessions persist via HTTP-only cookies.

```typescript
// Initialize authentication client
const auth = new BkperAuth({
  onLoginSuccess: () => loadUserData(),
  onLoginRequired: () => showLoginButton()
});

// Restore session on app load
await auth.init();
```

**Constructor:** `new BkperAuth(config?: BkperAuthConfig)`

Creates a new BkperAuth instance.

```typescript
// Simple usage with defaults
const auth = new BkperAuth();

// With callbacks
const auth = new BkperAuth({
  onLoginSuccess: () => console.log('Logged in!'),
  onLoginRequired: () => showLoginDialog(),
  onError: (error) => console.error(error)
});
```

**Methods:**

- `getAccessToken()` → `string | undefined` — Gets the current access token.
- `init()` → `Promise<void>` — Initializes the authentication state by attempting to refresh the access token.
- `login()` → `void` — Redirects the user to the login page.
- `logout()` → `void` — Logs out the user and redirects to the logout page.
- `refresh()` → `Promise<void>` — Refreshes the access token using the current session.

**getAccessToken**

```typescript
const token = auth.getAccessToken();
if (token) {
  // Make authenticated API calls
  fetch('/api/data', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
}
```

**init**

Call this method when your app loads to restore the user's session.
Triggers `onLoginSuccess` if a valid session exists, or `onLoginRequired` if login is needed.

**login**

The user will be redirected to the authentication service to complete the login flow.
After successful login, they will be redirected back to the current page.

```typescript
// Trigger login when user clicks a button
loginButton.addEventListener('click', () => {
  auth.login();
});
```

**logout**

Triggers the `onLogout` callback before redirecting.
The user's session will be terminated.

```typescript
// Logout when user clicks logout button
logoutButton.addEventListener('click', () => {
  auth.logout();
});
```

**refresh**

Call this when API requests return 403 to get a new token and retry.
Triggers `onTokenRefresh` callback if successful.
Throws error if the refresh fails (network error, expired session, etc.).

```typescript
// Handle 403 by refreshing and retrying
const response = await fetch('/api/data', {
  headers: { 'Authorization': `Bearer ${auth.getAccessToken()}` }
});

if (response.status === 403) {
  await auth.refresh();
  // Retry with new token
  return fetch('/api/data', {
    headers: { 'Authorization': `Bearer ${auth.getAccessToken()}` }
  });
}
```

## Interfaces

### BkperAuthConfig

Configuration options for the BkperAuth class.

**Properties:**

- `baseUrl?`: `string` — Override the authentication service base URL.
- `getAdditionalAuthParams?`: `() => Record<string, string>` — Provide additional parameters to send to the authentication service.
- `onError?`: `(error: unknown) => void` — Called when an error occurs during authentication.
- `onLoginRequired?`: `() => void` — Called when login is required (user needs to sign in).
- `onLoginSuccess?`: `() => void` — Called when login succeeds (user is authenticated).
- `onLogout?`: `() => void` — Called when the user logs out.
- `onTokenRefresh?`: `(token: string) => void` — Called when the access token is refreshed.

**baseUrl**

Most users don't need this. The default production URL works out of the box.

Use cases:
- Testing: Point to a mock authentication service for integration tests
- Development: Use a local mock server

```typescript
// Testing with mock server
const auth = new BkperAuth({
  baseUrl: 'http://localhost:3000/mock-auth'
});
```

**getAdditionalAuthParams**

Useful for custom authentication flows or passing additional context
to your authentication implementation.

```typescript
// Custom authentication context
const auth = new BkperAuth({
  getAdditionalAuthParams: () => {
    const token = new URLSearchParams(location.search).get('custom-token');
    return token ? { customToken: token } : {};
  }
});
```

---
source: /docs/api/rest.md

# REST API

> Full OpenAPI reference for the Bkper REST API — endpoints, parameters, and response schemas.

RESTful API for managing financial books, accounts, transactions, and balances in [Bkper](https://bkper.com).

## Base URL

```
https://api.bkper.app
```

All endpoints are under `/v5/`. For example:
- `GET https://api.bkper.app/v5/user` — Get the authenticated user
- `GET https://api.bkper.app/v5/books` — List books
- `GET https://api.bkper.app/v5/books/{bookId}` — Get a specific book

## Authentication

All requests require a [Google OAuth2](https://developers.google.com/identity/protocols/oauth2) access token with the `email` scope, sent as a Bearer token:

```
Authorization: Bearer <access_token>
```

### Getting a token

The easiest way to authenticate is through the [Bkper CLI](https://www.npmjs.com/package/bkper), which manages the OAuth flow for you:

```bash
npm i -g bkper
bkper auth login  # Opens browser for Google sign-in
bkper book list   # You're connected
```

For programmatic access, use a client library that handles token management:

- **Node.js** — [bkper-js](https://www.npmjs.com/package/bkper-js) with the CLI's `getOAuthToken()` for local scripts, or with [@bkper/web-auth](https://www.npmjs.com/package/@bkper/web-auth) for browser apps
- **Google Apps Script** — [bkper-gs](https://www.npmjs.com/package/@bkper/bkper-gs) library, which uses Apps Script's built-in OAuth

You can also set up your own [OAuth2 client credentials](https://developers.google.com/identity/protocols/oauth2) in a Google Cloud project if you need full control over the authentication flow.

## API Key (optional)

For dedicated quota and project-level usage tracking, you can pass an API key via the `key` query parameter. API keys are for quota management only — they do not replace OAuth2 authentication.

## OpenAPI Specification

The machine-readable spec is available at [`https://bkper.com/docs/api/rest/openapi.json`](https://bkper.com/docs/api/rest/openapi.json). Use it with Swagger UI, Postman, or any OpenAPI-compatible tool.

Content-Type: `application/json`

## Endpoints

All `/v5/books/{bookId}/...` endpoints require `bookId` (path, string, required) — the book's unique identifier.

### Apps

#### `GET /v5/apps` — listApps

**Response 200:** AppList

#### `POST /v5/apps` — createApp

**Request body:** App

**Response 200:** App

#### `PUT /v5/apps` — updateApp

**Request body:** App

**Response 200:** App

#### `GET /v5/apps/{agentId}` — getApp

**Parameters:**

- `agentId` (path, string, required)

**Response 200:** App

### Books

#### `GET /v5/books` — listBooks

**Parameters:**

- `query` (query, string) — Optional search term to filter books

**Response 200:** BookList

#### `POST /v5/books` — createNewBook

**Parameters:**

- `name` (query, string)

**Request body:** Book

**Response 200:** Book

#### `PUT /v5/books` — updateBook

**Request body:** Book

**Response 200:** Book

#### `GET /v5/books/{bookId}` — getBook

Load a book

**Parameters:**

- `loadAccounts` (query, boolean) — Optionally load accounts and groups
- `loadGroups` (query, boolean) — Optionally load groups

**Response 200:** Book

#### `PUT /v5/books/{bookId}` *(deprecated)* — updateBookDeprecated

**Request body:** Book

**Response 200:** Book

#### `DELETE /v5/books/{bookId}` — deleteBook

**Response 200:** Book

#### `GET /v5/books/{bookId}/apps` — listBookApps

**Response 200:** AppList

#### `PATCH /v5/books/{bookId}/audit` — auditBook

Audit a book async

**Response 204:** A successful response

#### `POST /v5/books/{bookId}/copy` — copyBook

Copy a book with optional transaction copying

**Parameters:**

- `name` (query, string) — Name for the copied book
- `copyTransactions` (query, boolean) — Whether to copy transactions
- `fromDate` (query, integer (int32)) — Start date for copying transactions (YYYYMMDD format)

**Response 200:** Book

### Accounts

#### `GET /v5/books/{bookId}/accounts` — listAccounts

**Response 200:** AccountList

#### `POST /v5/books/{bookId}/accounts` — createAccount

**Request body:** Account

**Response 200:** Account

#### `PUT /v5/books/{bookId}/accounts` — updateAccount

**Request body:** Account

**Response 200:** Account

#### `POST /v5/books/{bookId}/accounts/batch` — createAccountsBatch

Batch create accounts

**Request body:** AccountList

**Response 200:** AccountList

#### `PUT /v5/books/{bookId}/accounts/batch` — updateAccountsBatch

Batch update accounts

**Request body:** AccountList

**Response 200:** AccountList

#### `POST /v5/books/{bookId}/accounts/delete/batch` — deleteAccountsBatch

Batch delete accounts

**Request body:** AccountList

**Response 200:** AccountList

#### `GET /v5/books/{bookId}/accounts/{id}` — getAccount

**Parameters:**

- `id` (path, string, required) — The account id or name

**Response 200:** Account

#### `DELETE /v5/books/{bookId}/accounts/{id}` — deleteAccount

**Parameters:**

- `id` (path, integer (int64), required) — The account id

**Response 200:** Account

#### `GET /v5/books/{bookId}/accounts/{id}/groups` — listAccountGroups

List the groups of an account

**Parameters:**

- `id` (path, string, required) — The account id or name

**Response 200:** GroupList

### Balances

#### `GET /v5/books/{bookId}/balances` — getBalances

**Parameters:**

- `query` (query, string, required) — The query to filter balances

**Response 200:** Balances

### Collaborators

#### `GET /v5/books/{bookId}/collaborators` — listCollaborators

List collaborators of the book

**Response 200:** CollaboratorPayloadCollection

#### `POST /v5/books/{bookId}/collaborators` — addCollaborator

Add or update a collaborator to the book

**Parameters:**

- `message` (query, string) — Optional message to send with the invitation email

**Request body:** Collaborator

**Response 200:** Collaborator

#### `DELETE /v5/books/{bookId}/collaborators/{id}` — removeCollaborator

Remove a collaborator from the book

**Parameters:**

- `id` (path, string, required) — The collaborator id or email

**Response 200:** Collaborator

### Collections

#### `GET /v5/collections` — listCollections

**Response 200:** CollectionList

#### `POST /v5/collections` — createCollection

**Request body:** Collection

**Response 200:** Collection

#### `PUT /v5/collections` — updateCollection

**Request body:** Collection

**Response 200:** Collection

#### `DELETE /v5/collections/{id}` — deleteCollection

**Parameters:**

- `id` (path, string, required)

**Response 200:** BookList

#### `PATCH /v5/collections/{id}/books/add` — addBooksToCollection

**Parameters:**

- `id` (path, string, required)

**Request body:** BookList

**Response 200:** BookList

#### `PATCH /v5/collections/{id}/books/remove` — removeBooksFromCollection

**Parameters:**

- `id` (path, string, required)

**Request body:** BookList

**Response 200:** BookList

### Events

#### `GET /v5/books/{bookId}/events` — listEvents

**Parameters:**

- `after` (query, string (date-time)) — After date and time, on RFC3339 format
- `before` (query, string (date-time)) — Before date and time, on RFC3339 format
- `error` (query, boolean) — Filter by error
- `resoureId` (query, string) — The resourceId associated
- `limit` (query, integer (int32)) — The dataset limit. Useful for pagination

**Response 200:** EventList

#### `GET /v5/books/{bookId}/events/backlog` — getBookEventsBacklog

Get book events backlog

**Response 200:** Backlog

#### `PATCH /v5/books/{bookId}/events/replay/batch` — replayEvents

Batch replay events responses

**Parameters:**

- `errorsOnly` (query, boolean) — Replay errors only

**Request body:** EventList

**Response 204:** A successful response

#### `PUT /v5/books/{bookId}/events/{id}/responses/{agentId}` — replayEventResponse

Replay an event response

**Parameters:**

- `id` (path, string, required) — The event id
- `agentId` (path, string, required) — The agent id

**Response 200:** Event

#### `DELETE /v5/books/{bookId}/events/{id}/responses/{agentId}` — deleteEventResponse

Delete an event response

**Parameters:**

- `id` (path, string, required) — The event id
- `agentId` (path, string, required) — The agent id

**Response 200:** Event

### Files

#### `POST /v5/books/{bookId}/files` — createFile

**Request body:** File

**Response 200:** File

#### `PUT /v5/books/{bookId}/files` — updateFile

**Request body:** File

**Response 200:** File

#### `GET /v5/books/{bookId}/files/{id}` — getFile

**Parameters:**

- `id` (path, string, required) — The file id

**Response 200:** File

### Groups

#### `GET /v5/books/{bookId}/groups` — listGroups

**Response 200:** GroupList

#### `POST /v5/books/{bookId}/groups` — createGroup

Group a group

**Request body:** Group

**Response 200:** Group

#### `PUT /v5/books/{bookId}/groups` — updateGroup

**Request body:** Group

**Response 200:** Group

#### `POST /v5/books/{bookId}/groups/batch` — createGroupsBatch

Batch create groups

**Request body:** GroupList

**Response 200:** GroupList

#### `GET /v5/books/{bookId}/groups/{id}` — getGroup

**Parameters:**

- `id` (path, string, required) — The group id or name

**Response 200:** Group

#### `DELETE /v5/books/{bookId}/groups/{id}` — deleteGroup

**Parameters:**

- `id` (path, integer (int64), required) — The group id

**Response 200:** Group

#### `GET /v5/books/{bookId}/groups/{id}/accounts` — listGroupAccounts

List the accounts of a group

**Parameters:**

- `id` (path, string, required) — The group id or name

**Response 200:** AccountList

### Integrations

#### `GET /v5/books/{bookId}/integrations` — listIntegrations

List the integrations of the book

**Response 200:** IntegrationList

#### `POST /v5/books/{bookId}/integrations` — createIntegration

**Request body:** Integration

**Response 200:** Integration

#### `PUT /v5/books/{bookId}/integrations` — updateIntegration

**Request body:** Integration

**Response 200:** Integration

#### `DELETE /v5/books/{bookId}/integrations/{id}` — deleteIntegration

**Parameters:**

- `id` (path, integer (int64), required)

**Response 200:** Integration

### Queries

#### `GET /v5/books/{bookId}/queries` — listQueries

**Response 200:** QueryList

#### `POST /v5/books/{bookId}/queries` — saveQuery

Create a saved query

**Request body:** Query

**Response 200:** Query

#### `PUT /v5/books/{bookId}/queries` — updateQuery

Update a saved query

**Request body:** Query

**Response 200:** Query

#### `DELETE /v5/books/{bookId}/queries/{id}` — deleteQuery

Delete a saved query

**Parameters:**

- `id` (path, integer (int64), required) — The query id

**Response 200:** Query

### Templates

#### `GET /v5/templates` — listTemplates

**Response 200:** TemplateList

### Transactions

#### `GET /v5/books/{bookId}/transactions` — listTransactions

**Parameters:**

- `query` (query, string) — The query to filter transactions
- `limit` (query, integer (int32)) — The dataset limit. Useful for pagination

**Response 200:** TransactionList

#### `POST /v5/books/{bookId}/transactions` — createTransaction

**Parameters:**

- `timeZone` (query, string) — Optional time zone for parsing dates when recording from different book time zone

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PUT /v5/books/{bookId}/transactions` — updateTransaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `POST /v5/books/{bookId}/transactions/batch` — createTransactionsBatch

Batch create transactions

**Parameters:**

- `timeZone` (query, string) — Optional time zone for parsing dates when recording from different book time zone

**Request body:** TransactionList

**Response 200:** TransactionList

#### `PUT /v5/books/{bookId}/transactions/batch` — updateTransactionsBatch

Batch update transactions

**Parameters:**

- `updateChecked` (query, boolean) — True to also update checked transactions

**Request body:** TransactionList

**Response 200:** TransactionList

#### `PATCH /v5/books/{bookId}/transactions/check` — checkTransaction

Check a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/check/batch` — checkTransactionsBatch

Batch check transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `GET /v5/books/{bookId}/transactions/count` — countTransactions

Count transactions

**Parameters:**

- `query` (query, string) — The query to filter transactions

**Response 200:** Count

#### `GET /v5/books/{bookId}/transactions/count/posted` — countTransactionsPosted

Count transactions posted

**Parameters:**

- `after` (query, string (date), required) — After date, on yyyy-mm-dd format.
- `before` (query, string (date), required) — Before date, on yyyy-mm-dd format.
- `periodicity` (query, string — `DAILY` | `MONTHLY` | `YEARLY`, required) — Periodicity DAILY or MONTHLY

**Response 200:** Counts

#### `PATCH /v5/books/{bookId}/transactions/merge` — mergeTransactions

Merge two transactions into a single new canonical transaction

**Request body:** TransactionList

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/post` — postTransaction

Post a transaction into accounts

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/post/batch` — postTransactionsBatch

Batch post transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `PATCH /v5/books/{bookId}/transactions/remove` *(deprecated)* — removeTransaction

Remove a transaction, sending to trash

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/restore` *(deprecated)* — restoreTransaction

Restore a transaction from trash

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/trash` — trashTransaction

Trash a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/trash/batch` — trashTransactionsBatch

Batch trash transactions

**Parameters:**

- `trashChecked` (query, boolean) — True to also trash checked transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `PATCH /v5/books/{bookId}/transactions/uncheck` — uncheckTransaction

Uncheck a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/uncheck/batch` — uncheckTransactionsBatch

Batch uncheck a transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `PATCH /v5/books/{bookId}/transactions/untrash` — untrashTransaction

Untrash a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/untrash/batch` — untrashTransactionsBatch

Batch untrash transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `GET /v5/books/{bookId}/transactions/{id}` — getTransaction

**Parameters:**

- `id` (path, string, required) — The transaction id

**Response 200:** Transaction

### User

#### `GET /v5/user` — getUser

Retrieve the current user

**Response 200:** User

#### `GET /v5/user/billing` — getBilling

Retrieve the user billing information

**Response 200:** Billing

#### `GET /v5/user/billing/checkout` — getBillingCheckout

Retrieve the user billing checkout url for a plan

**Parameters:**

- `plan` (query, string, required)
- `cycle` (query, string)
- `successUrl` (query, string, required)
- `cancelUrl` (query, string, required)

**Response 200:** Url

#### `GET /v5/user/billing/counts` — listBillingCounts

List user billing transaction counts for last 12 months

**Response 200:** Counts

#### `GET /v5/user/billing/portal` — getBillingPortal

Retrieve the user billing portal url

**Parameters:**

- `returnUrl` (query, string, required)

**Response 200:** Url

#### `GET /v5/user/connections` — listConnections

**Response 200:** ConnectionList

#### `POST /v5/user/connections` — createConnection

**Request body:** Connection

**Response 200:** Connection

#### `PUT /v5/user/connections` — updateConnection

**Request body:** Connection

**Response 200:** Connection

#### `GET /v5/user/connections/{id}` — getConnection

Retrieve a connection by id

**Parameters:**

- `id` (path, string, required)

**Response 200:** Connection

#### `DELETE /v5/user/connections/{id}` — deleteConnection

**Parameters:**

- `id` (path, string, required)

**Response 200:** Connection

#### `GET /v5/user/connections/{id}/integrations` — listConnectionIntegrations

List integrations by connection

**Parameters:**

- `id` (path, string, required)

**Response 200:** IntegrationList

## Data Models

### Account

- `agentId`: string — The id of agent that created the resource
- `archived`: boolean — Archived accounts are kept for history
- `balance`: string — The running balance of the account at the transaction date. Only present when the account is part of a transaction response filtered by account. NOT the current account balance. To get current balances, use the Balances endpoint: GET /books/{bookId}/balances
- `balanceVerified`: boolean — Whether the account balance has been verified/audited
- `createdAt`: string — The creation timestamp, in milliseconds
- `credit`: boolean — Credit nature or Debit otherwise
- `groups`: Group[] — The groups of the account
- `hasTransactionPosted`: boolean — Whether the account has any transactions posted
- `id`: string — The unique id that identifies the Account in the Book
- `name`: string — The name of the Account
- `normalizedName`: string — The name of the Account, lowercase, without spaces or special characters
- `permanent`: boolean — Permanent are such as bank accounts, customers or the like
- `properties`: Record<string, string> — The key/value custom properties of the Account
- `type`: string — `ASSET` | `LIABILITY` | `INCOMING` | `OUTGOING` — The type of the account
- `updatedAt`: string — The last update timestamp, in milliseconds

### AccountBalances

- `archived`: boolean
- `balances`: Balance[]
- `credit`: boolean
- `cumulativeBalance`: string
- `cumulativeCredit`: string
- `cumulativeDebit`: string
- `empty`: boolean
- `name`: string
- `normalizedName`: string
- `periodBalance`: string
- `periodCredit`: string
- `periodDebit`: string
- `permanent`: boolean
- `properties`: Record<string, string>

### AccountList

- `items`: Account[] — List items

### Agent

- `id`: string — The agent id
- `logo`: string — The agent logo. Public url or Base64 encoded
- `logoDark`: string — The agent logo on dark mode. Public url or Base64 encoded
- `name`: string — The agent name

### App

- `apiVersion`: string — `v0` | `v1` | `v2` | `v3` | `v4` | `v5` — The API version of the event payload
- `clientId`: string — The Google OAuth Client ID
- `clientSecret`: string — The Google OAuth Client Secret
- `connectable`: boolean — Whether this app is connectable by a user
- `deprecated`: boolean — Whether the app is deprecated
- `description`: string — The App description
- `developers`: string — The developers (usernames and domain patterns), comma or space separated
- `events`: string[] — `FILE_CREATED` | `FILE_UPDATED` | `TRANSACTION_CREATED` | `TRANSACTION_UPDATED` | `TRANSACTION_DELETED` | `TRANSACTION_POSTED` | `TRANSACTION_CHECKED` | `TRANSACTION_UNCHECKED` | `TRANSACTION_RESTORED` | `ACCOUNT_CREATED` | `ACCOUNT_UPDATED` | `ACCOUNT_DELETED` | `QUERY_CREATED` | `QUERY_UPDATED` | `QUERY_DELETED` | `GROUP_CREATED` | `GROUP_UPDATED` | `GROUP_DELETED` | `COMMENT_CREATED` | `COMMENT_DELETED` | `COLLABORATOR_ADDED` | `COLLABORATOR_UPDATED` | `COLLABORATOR_REMOVED` | `INTEGRATION_CREATED` | `INTEGRATION_UPDATED` | `INTEGRATION_DELETED` | `BOOK_CREATED` | `BOOK_AUDITED` | `BOOK_UPDATED` | `BOOK_DELETED` — Event types the App listen to
- `filePatterns`: string[] — File patterns the App handles - wildcard accepted. E.g. *.pdf, *-bank.csv
- `id`: string — The unique agent id of the App - this can't be changed after created
- `installable`: boolean — Whether this app is installable in a book
- `logoUrl`: string — The App logo url
- `logoUrlDark`: string — The App logo url in dark mode
- `menuPopupHeight`: string — The menu popup window height
- `menuPopupWidth`: string — The menu popup window width
- `menuText`: string — The contex menu text - default to the App name
- `menuUrl`: string — The context menu url
- `menuUrlDev`: string — The context menu url in dev mode
- `name`: string — The App name
- `ownerEmail`: string — The owner user email
- `ownerId`: string — The owner user id
- `ownerLogoUrl`: string — The owner company logo url
- `ownerName`: string — The owner company name
- `ownerWebsite`: string — The owner company website url
- `propertiesSchema`: AppPropertiesSchema
- `published`: boolean — Whether this app is already published
- `readme`: string — The readme.md file as string
- `readmeMd`: string — The readme.md file as raw markdown string
- `repoPrivate`: boolean — Whether the code repository is private
- `repoUrl`: string — The code repository url
- `scopes`: string[] — The Google OAuth Scopes used by the app
- `users`: string — The users (usernames and domain patterns) to enable the App while not yet published
- `webhookUrl`: string — The Webhook endpoint URL to listen for book events
- `webhookUrlDev`: string — The Webhook endpoint URL to listen for book events in dev mode
- `website`: string — The App website url

### AppList

- `items`: App[]

### AppPropertiesSchema

- `account`: AppPropertySchema
- `book`: AppPropertySchema
- `group`: AppPropertySchema
- `transaction`: AppPropertySchema

### AppPropertySchema

- `keys`: string[] — The property keys schema
- `values`: string[] — The property values schema

### Backlog

- `count`: integer (int32)

### Balance

- `cumulativeBalance`: string
- `cumulativeCredit`: string
- `cumulativeDebit`: string
- `day`: integer (int32)
- `fuzzyDate`: integer (int32)
- `month`: integer (int32)
- `periodBalance`: string
- `periodCredit`: string
- `periodDebit`: string
- `year`: integer (int32)

### Balances

- `accountBalances`: AccountBalances[]
- `balancesUrl`: string
- `groupBalances`: GroupBalances[]
- `nextRange`: string
- `periodicity`: string — `DAILY` | `MONTHLY` | `YEARLY`
- `previousRange`: string
- `range`: string
- `rangeBeginLabel`: string
- `rangeEndLabel`: string

### Billing

- `adminEmail`: string — The billing admin email for the user's billing account
- `daysLeftInTrial`: integer (int32) — How many days the user has left in the trial period
- `email`: string — The user's email address
- `enabled`: boolean — True if billing is enabled for the user
- `hostedDomain`: string — The user hosted domain
- `plan`: string — The user's current plan
- `planOverdue`: boolean — True if subscription payment is overdue
- `startedTrial`: boolean — True if the user has started the trial period
- `totalTransactionsThisMonth`: integer (int64) — User-level total transactions this month
- `totalTransactionsThisYear`: integer (int64) — User-level total transactions this year

### Book

- `accounts`: Account[] — The book Accounts
- `agentId`: string — The id of agent that created the resource
- `autoPost`: boolean — Tells if the Book has auto post enabled
- `closingDate`: string — The book closing date, in ISO format yyyy-MM-dd. Transactions on or before this date are closed for the period
- `collection`: Collection
- `createdAt`: string — The creation timestamp, in milliseconds
- `datePattern`: string — The date pattern of the Book. Example: dd/MM/yyyy
- `decimalSeparator`: string — `DOT` | `COMMA` — The decimal separator of the Book
- `fractionDigits`: integer (int32) — The number of fraction digits (decimal places) of the Book. E.g. 2 for ####.##, 4 for ####.####
- `groups`: Group[] — The book account Groups
- `id`: string — The unique id that identifies the Book in the system. Found at bookId url param
- `lastUpdateMs`: string — The last update date of the Book, in milliseconds
- `lockDate`: string — The book lock date, in ISO format yyyy-MM-dd. Transactions on or before this date are locked
- `logoUrl`: string — The logo URL of the book owner's custom domain
- `name`: string — The name of the Book
- `ownerName`: string — The Book owner username
- `pageSize`: integer (int32) — The transactions pagination page size
- `period`: string — `MONTH` | `QUARTER` | `YEAR` — The period slice for balances visualization
- `periodStartMonth`: string — `JANUARY` | `FEBRUARY` | `MARCH` | `APRIL` | `MAY` | `JUNE` | `JULY` | `AUGUST` | `SEPTEMBER` | `OCTOBER` | `NOVEMBER` | `DECEMBER` — The start month when YEAR period set
- `permission`: string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE` — The Permission the current user has in the Book
- `properties`: Record<string, string> — The key/value custom properties of the Book
- `timeZone`: string — The time zone of the Book, in IANA format. E.g. America/New_York, Europe/London
- `timeZoneOffset`: integer (int32) — The time zone offset of the Book, in minutes
- `totalTransactions`: integer (int64) — The total transactions posted
- `totalTransactionsCurrentMonth`: integer (int64) — The total transactions posted on current month
- `totalTransactionsCurrentYear`: integer (int64) — The total transactions posted on current year
- `updatedAt`: string — The last update timestamp, in milliseconds
- `visibility`: string — `PUBLIC` | `PRIVATE` — The Visibility of the Book

### BookList

- `items`: Book[] — List items

### BotResponse

- `agentId`: string
- `createdAt`: string
- `message`: string
- `type`: string — `INFO` | `WARNING` | `ERROR`

### Collaborator

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `email`: string — The email of the Collaborator
- `id`: string — The unique id that identifies the Collaborator in the Book
- `permission`: string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE` — The permission the Collaborator has in the Book
- `updatedAt`: string — The last update timestamp, in milliseconds

### CollaboratorPayloadCollection

An ordered list of Collaborator

- `items`: Collaborator[]

### Collection

- `agentId`: string — The id of agent that created the resource
- `books`: Book[] — The Books contained in the Collection
- `createdAt`: string — The creation timestamp, in milliseconds
- `id`: string — The unique id of the Collection
- `name`: string — The name of the Collection
- `ownerUsername`: string — The username of the Collection owner
- `permission`: string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE` — The permission the current user has in the Collection. E.g. OWNER, EDITOR, NONE
- `updatedAt`: string — The last update timestamp, in milliseconds

### CollectionList

- `items`: Collection[] — List items

### Connection

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `dateAddedMs`: string
- `email`: string
- `id`: string
- `logo`: string
- `name`: string
- `properties`: Record<string, string>
- `type`: string — `APP` | `BANK`
- `updatedAt`: string — The last update timestamp, in milliseconds
- `userId`: string
- `uuid`: string

### ConnectionList

- `items`: Connection[] — List items

### Count

- `day`: integer (int32)
- `fuzzyDate`: integer (int32)
- `month`: integer (int32)
- `total`: integer (int64)
- `year`: integer (int32)

### Counts

- `posted`: Count[]
- `trashed`: Count[]

### Event

- `agent`: Agent
- `book`: Book
- `bookId`: string — The id of the Book associated to the Event
- `botResponses`: BotResponse[] — The list of bot responses associated to the Event
- `createdAt`: string — The creation timestamp, in milliseconds
- `createdOn`: string (date-time) — The creation date time on RFC3339 format
- `data`: EventData
- `id`: string — The unique id that identifies the Event
- `resource`: string — The resource associated to the Event
- `type`: string — `FILE_CREATED` | `FILE_UPDATED` | `TRANSACTION_CREATED` | `TRANSACTION_UPDATED` | `TRANSACTION_DELETED` | `TRANSACTION_POSTED` | `TRANSACTION_CHECKED` | `TRANSACTION_UNCHECKED` | `TRANSACTION_RESTORED` | `ACCOUNT_CREATED` | `ACCOUNT_UPDATED` | `ACCOUNT_DELETED` | `QUERY_CREATED` | `QUERY_UPDATED` | `QUERY_DELETED` | `GROUP_CREATED` | `GROUP_UPDATED` | `GROUP_DELETED` | `COMMENT_CREATED` | `COMMENT_DELETED` | `COLLABORATOR_ADDED` | `COLLABORATOR_UPDATED` | `COLLABORATOR_REMOVED` | `INTEGRATION_CREATED` | `INTEGRATION_UPDATED` | `INTEGRATION_DELETED` | `BOOK_CREATED` | `BOOK_AUDITED` | `BOOK_UPDATED` | `BOOK_DELETED` — The type of the Event
- `user`: User

### EventData

- `object`: object
- `previousAttributes`: Record<string, string> — The object previous attributes when updated

### EventList

- `cursor`: string — The cursor, for pagination
- `items`: Event[] — List items

### File

- `agentId`: string — The id of agent that created the resource
- `content`: string — The file content Base64 encoded
- `contentType`: string — The file content type
- `createdAt`: string — The creation timestamp, in milliseconds
- `id`: string — The unique id that identifies the file in the book
- `name`: string — The file name
- `properties`: Record<string, string> — The key/value custom properties of the File
- `size`: integer (int64) — The file size in bytes
- `updatedAt`: string — The last update timestamp, in milliseconds
- `url`: string — The file serving url

### Group

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `credit`: boolean — Whether the group has credit nature
- `hasAccounts`: boolean — Whether the group has any accounts
- `hasGroups`: boolean — Whether the group has any children groups
- `hidden`: boolean — Whether the group is hidden on the transactions main menu
- `id`: string — The unique id that identifies the Group in the Book
- `locked`: boolean — Whether the group is locked by the Book owner
- `mixed`: boolean — Whether the group has mixed types of accounts
- `name`: string — The name of the Group
- `normalizedName`: string — The name of the Group, lowercase, without spaces or special characters
- `parent`: Group
- `permanent`: boolean — Whether the group is permanent
- `properties`: Record<string, string> — The key/value custom properties of the Group
- `type`: string — `ASSET` | `LIABILITY` | `INCOMING` | `OUTGOING` — The type of the accounts in the group. E.g. ASSET, LIABILITY, INCOMING, OUTGOING
- `updatedAt`: string — The last update timestamp, in milliseconds

### GroupBalances

- `accountBalances`: AccountBalances[]
- `balances`: Balance[]
- `credit`: boolean
- `cumulativeBalance`: string
- `cumulativeCredit`: string
- `cumulativeDebit`: string
- `groupBalances`: GroupBalances[]
- `name`: string
- `normalizedName`: string
- `periodBalance`: string
- `periodCredit`: string
- `periodDebit`: string
- `permanent`: boolean
- `properties`: Record<string, string>

### GroupList

- `items`: Group[] — List items

### Integration

- `addedBy`: string
- `agentId`: string — The id of agent that created the resource
- `bookId`: string
- `connectionId`: string
- `createdAt`: string — The creation timestamp, in milliseconds
- `dateAddedMs`: string
- `id`: string
- `lastUpdateMs`: string
- `logo`: string
- `logoDark`: string
- `name`: string
- `normalizedName`: string
- `properties`: Record<string, string>
- `updatedAt`: string — The last update timestamp, in milliseconds
- `userId`: string

### IntegrationList

- `items`: Integration[] — List items

### Query

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `id`: string — The unique id that identifies the saved Query in the Book
- `query`: string — The Query string to be executed
- `title`: string — The title of the saved Query
- `updatedAt`: string — The last update timestamp, in milliseconds

### QueryList

- `items`: Query[] — List items

### Template

- `bookId`: string
- `bookLink`: string
- `category`: string
- `description`: string
- `imageUrl`: string
- `name`: string
- `sheetsLink`: string
- `timesUsed`: integer (int32)

### TemplateList

- `items`: Template[] — List items

### Transaction

- `agentId`: string — The id of agent that created the resource
- `agentLogo`: string — The logo of the agent that created the transaction
- `agentLogoDark`: string — The logo in dark mode, of the agent that created the transaction
- `agentName`: string — The name of the agent that created the transaction
- `amount`: string — The amount on format ####.##
- `checked`: boolean — Whether the transaction is checked
- `createdAt`: string — The creation timestamp, in milliseconds
- `createdBy`: string — The actor username that created the transaction
- `creditAccount`: Account
- `date`: string — The date on ISO format yyyy-MM-dd
- `dateFormatted`: string — The date on format of the Book
- `dateValue`: integer (int32) — The date number representation on format YYYYMMDD
- `debitAccount`: Account
- `description`: string — The transaction description
- `draft`: boolean — Whether the transaction is a draft
- `files`: File[] — The files attached to the transaction
- `id`: string — The unique id that identifies the transaction in the book
- `posted`: boolean — Whether the transaction is already posted on accounts, otherwise is a draft
- `properties`: Record<string, string> — The key/value custom properties of the Transaction
- `remoteIds`: string[] — The transaction remote ids, to avoid duplication
- `tags`: string[] — The transaction #hashtags
- `trashed`: boolean — Whether the transaction is trashed
- `updatedAt`: string — The last update timestamp, in milliseconds
- `urls`: string[] — The transaction urls

### TransactionList

- `account`: string — The account id when filtering by a single account. E.g. account='Bank'
- `cursor`: string — The cursor, for pagination
- `items`: Transaction[] — List items

### TransactionOperation

- `accounts`: Account[] — The affected accounts
- `transaction`: Transaction

### Url

- `url`: string

### User

- `avatarUrl`: string — The user public avatar url
- `bankConnections`: boolean — True if user already had any bank connection
- `billingAdminEmail`: string — The billing admin email for this user's billing account
- `billingEnabled`: boolean — True if billing is enabled for the user
- `daysLeftInTrial`: integer (int32) — How many days left in trial
- `email`: string — The user email
- `free`: boolean — True if user is in the free plan
- `fullName`: string — The user full name
- `givenName`: string — The user given name
- `hash`: string — The user hash
- `hostedDomain`: string — The user hosted domain
- `id`: string — The user unique id
- `name`: string — The user display name
- `plan`: string — The user plan
- `planOverdue`: boolean — True if subscription payment is overdue
- `startedTrial`: boolean — True if user started trial
- `totalTransactionsThisMonth`: integer (int64) — User-level total transactions this month
- `totalTransactionsThisYear`: integer (int64) — User-level total transactions this year
- `username`: string — The Bkper username of the user
