# 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/api/rest) 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/api/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/api/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/api/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/api/bkper-gs/#account).

When you retrieve transactions, the [getTransactions](https://bkper.com/docs/api/bkper-gs/#book_gettransactions) method returns an [TransactionIterator](https://bkper.com/docs/api/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

