├── .commitlintrc.json ├── .eslintignore ├── .eslintrc.js ├── .github └── workflows │ └── release.yml ├── .gitignore ├── .lintstagedrc ├── .prettierignore ├── .prettierrc.js ├── .releaserc.json ├── LICENSE ├── README.md ├── babel.config.js ├── jest.config.js ├── package.json ├── pnpm-lock.yaml ├── src ├── client │ ├── client.test.ts │ └── client.ts ├── index.ts ├── service │ ├── bankaccount.test.ts │ ├── bankaccount.ts │ ├── contact.test.ts │ ├── contact.ts │ ├── contactperson.test.ts │ ├── contactperson.ts │ ├── index.ts │ ├── invoice.test.ts │ ├── invoice.ts │ ├── item.test.ts │ ├── item.ts │ ├── organizations.test.ts │ ├── organizations.ts │ ├── package.test.ts │ ├── package.ts │ ├── payment.test.ts │ ├── payment.ts │ ├── salesOrder.test.ts │ ├── salesOrder.ts │ ├── tax.test.ts │ ├── tax.ts │ ├── util.test.ts │ ├── util.ts │ ├── warehouse.test.ts │ └── warehouse.ts ├── types │ ├── address.ts │ ├── bankaccount.ts │ ├── contact.ts │ ├── contactPerson.ts │ ├── customField.ts │ ├── document.ts │ ├── index.ts │ ├── invoice.ts │ ├── item.ts │ ├── lineItem.ts │ ├── organizations.ts │ ├── package.ts │ ├── payment.ts │ ├── salesOrder.ts │ ├── tax.ts │ └── warehouse.ts └── util │ ├── format.ts │ └── retry.ts └── tsconfig.json /.commitlintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["@commitlint/config-conventional"] 3 | } 4 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | 2 | node_modules 3 | dist 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: "@trieb.work/eslint-config-base", 3 | ignorePatterns: ["dist", "src/**/*.test.*", ".eslintrc.js"], 4 | }; 5 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | permissions: 8 | contents: read # for checkout 9 | 10 | jobs: 11 | release: 12 | name: Release 13 | runs-on: ubuntu-latest 14 | permissions: 15 | contents: write # to be able to publish a GitHub release 16 | issues: write # to be able to comment on released issues 17 | pull-requests: write # to be able to comment on released pull requests 18 | id-token: write # to enable use of OIDC for npm provenance 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@v3 22 | with: 23 | fetch-depth: 0 24 | - uses: pnpm/action-setup@v2 25 | with: 26 | version: 8.6.12 27 | - name: Setup Node.js 28 | uses: actions/setup-node@v3 29 | with: 30 | node-version: "lts/*" 31 | cache: "pnpm" 32 | 33 | - name: Install dependencies 34 | run: pnpm i 35 | - name: Verify the integrity of provenance attestations and registry signatures for installed dependencies 36 | run: pnpm audit signatures --audit-level high 37 | - name: Build package 38 | run: pnpm build 39 | - name: Release 40 | env: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 43 | run: npx semantic-release -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .env 4 | .DS_Store -------------------------------------------------------------------------------- /.lintstagedrc: -------------------------------------------------------------------------------- 1 | { 2 | "**.{ts,tsx}": ["yarn prettier --write", "yarn eslint --fix"], 3 | "**.{json,md,mdx,css,html,js}": ["yarn prettier --write"] 4 | } 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | ...require("@trieb.work/prettier-base"), 3 | }; 4 | -------------------------------------------------------------------------------- /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "@semantic-release/commit-analyzer", 4 | "@semantic-release/release-notes-generator", 5 | "@semantic-release/changelog", 6 | "@semantic-release/npm", 7 | "@semantic-release/github" 8 | ] 9 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://badge.fury.io/js/@trieb.work%2Fzoho-ts.svg)](https://badge.fury.io/js/@trieb.work%2Fzoho-ts) 2 | 3 | # Zoho TS 4 | 5 | A typescript / node.js library used to work with Zoho Finance Suite APIs: Zoho Inventory, Zoho Books and Zoho Invoice. 6 | These APIs are for most entities the same, apart from some specific functions. 7 | There are several functions already created, but in the end they are all custom. Some of them are documented and some are reverse-engineered and implemented in this library to have an optimised, easy way working with the Zoho APIs. 8 | 9 | All entities are fully typed. 10 | 11 | 12 | ## Installation 13 | ``` 14 | yarn add @trieb.work/zoho-ts 15 | ``` 16 | ``` 17 | npm i @trieb.work/zoho-ts 18 | ``` 19 | ``` 20 | pnpm i @trieb.work/zoho-ts 21 | ``` 22 | 23 | ## Usage on server 24 | Make sure to select the correct datacenter for your API client credentials: e.g. ".com" or ".eu". 25 | You can also select, which API endpoint to use - Zoho Books, Zoho Invoice or Zoho Inventory. Most API endpoints are the same 26 | and work the same. You just need to select the product, that you have licensed. 27 | 28 | 29 | ``` 30 | import { Zoho, ZohoApiClient } from "@trieb.work/zoho-ts"; 31 | 32 | const zoho = new Zoho( 33 | await ZohoApiClient.fromOAuth({ 34 | orgId: "243546", 35 | dc: ".com", 36 | apiFlavour: "invoice", 37 | scope: "ZohoInvoice.fullaccess.all" 38 | client: { 39 | id: "", 40 | secret: "", 41 | }, 42 | }), 43 | ); 44 | 45 | ``` 46 | 47 | You can decide, which API to use - Zoho Inventory, Zoho Books, Zoho Invoice. Currently, you can only decide per instance. It is planned 48 | to make it possible to decide which API to use on function level. 49 | 50 | ### Authentication with OAuth 51 | The library on the server should be used with a client ID and a client secret, that you can register at the developer console: https://api-console.zoho.eu/ (Self Client) 52 | 53 | 54 | ## Usage in Browser Context (use cookies for auth) 55 | The library can run in the browser as well (for example with browser extensions) 56 | 57 | ``` 58 | import { Zoho, ZohoApiClient } from "@trieb.work/zoho-ts"; 59 | 60 | const zoho = new Zoho( 61 | await ZohoApiClient.fromCookies({ 62 | orgId: "", 63 | cookie: "", 64 | zsrfToken: "" 65 | }), 66 | ); 67 | 68 | ``` 69 | 70 | ## Implemented entities 71 | |Entity|Functions| 72 | |---|---| 73 | |bankaccount|`list`| 74 | |contact|`create`, `get`, `update`, `delete`, `list`, `addAddress`,`updateAddress`, `listContactPersons`| 75 | |contactperson|`create`, `get`, `delete`, `list`| 76 | |invoice|`create`, `get`, `delete`, `list`, `createFromSalesOrder`, `sent`| 77 | |item|`create`, `get`, `delete`, `list`, `createGroup`, `deleteGroup`, `getComposite`| 78 | |organizations|`list`| 79 | |package|`create`, `get`, `delete`, `list`,`bulkCreateQuickShipment`, `createShipment`, `markDelivered`, `deleteShipmentOrder`| 80 | |payment|`create`, `get`, `delete`, `list`| 81 | |salesorder|`create`, `get`, `delete`, `list`, `update`, `confirm`, `markVoid`, `setCustomFieldValue`, `search`| 82 | |tax|`list`| 83 | |warehouse|`get`, `list`| 84 | 85 | Usage example: 86 | ``` 87 | import { Zoho, ZohoApiClient } from "@trieb.work/zoho-ts"; 88 | 89 | const zoho = new Zoho( 90 | await ZohoApiClient.fromOAuth({ 91 | orgId: "243546", 92 | dc: ".com", 93 | client: { 94 | id: "", 95 | secret: "", 96 | }, 97 | }), 98 | ); 99 | 100 | /// Get all payments that were modified in the last hour 101 | const payments = await zoho.payment.list({ 102 | lastModifiedTime: subHours(new Date(), 1), 103 | }) 104 | ``` 105 | 106 | ## Error Handling 107 | The library includes a custom error type, that you can use to handle the from Zoho returned error type: 108 | ``` 109 | try { 110 | 111 | await zoho.invoice.createFromSalesOrder(id) 112 | 113 | } catch(err) { 114 | if ((err as ZohoApiError).code === 36026) { 115 | console.warn( 116 | "Aborting sync of this invoice since it was already created. Original Error: " + 117 | err.message, 118 | ); 119 | } else { 120 | console.error(err.message); 121 | } 122 | } 123 | 124 | ``` 125 | 126 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ["@babel/preset-env", { targets: { node: "current" } }], 4 | "@babel/preset-typescript", 5 | ], 6 | }; 7 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | /** @type {import('@ts-jest/dist/types').InitialOptionsTsJest} */ 3 | module.exports = { 4 | preset: "ts-jest", 5 | testEnvironment: "node", 6 | }; 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@trieb.work/zoho-ts", 3 | "version": "0.0.0-development", 4 | "description": "Node Library for Zoho Inventory, Invoice and Zoho Books", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "files": [ 8 | "dist" 9 | ], 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/trieb-work/zoho-ts.git" 13 | }, 14 | "author": "Jannik Zinkl | trieb.work", 15 | "license": "MIT", 16 | "keywords": [ 17 | "Zoho", 18 | "Node", 19 | "Typescript", 20 | "Zoho Inventory", 21 | "zoho", 22 | "inventory", 23 | "books", 24 | "invoice", 25 | "Zoho Invoice" 26 | ], 27 | "scripts": { 28 | "build": "tsc", 29 | "dev": "pnpm tsc --watch --preserveWatchOutput", 30 | "prepublish": "pnpm build", 31 | "format": "prettier --write .", 32 | "fmt": "pnpm lint && pnpm format", 33 | "lint": "eslint . --ext ts --ext tsx --ext js --fix", 34 | "test": "jest", 35 | "semantic-release": "semantic-release" 36 | }, 37 | "dependencies": { 38 | "async-retry": "^1.3.3", 39 | "await-timeout": "^1.1.1", 40 | "axios": "^1.4.0", 41 | "axios-retry": "^3.4.0", 42 | "date-fns": "^2.30.0", 43 | "dayjs": "^1.11.7", 44 | "form-data": "^4.0.0", 45 | "http": "0.0.1-security", 46 | "https": "^1.0.0", 47 | "simple-oauth2": "^5.0.0", 48 | "stream": "^0.0.2", 49 | "ts-mixer": "^6.0.3", 50 | "zlib": "^1.0.5" 51 | }, 52 | "devDependencies": { 53 | "@babel/core": "^7.21.8", 54 | "@babel/preset-env": "^7.21.5", 55 | "@babel/preset-typescript": "^7.21.5", 56 | "@commitlint/config-conventional": "^17.7.0", 57 | "@trieb.work/eslint-config-base": "^1.13.4", 58 | "@trieb.work/prettier-base": "^0.3.1", 59 | "@trieb.work/tsconfig-base": "^1.6.5", 60 | "@types/async-retry": "^1.4.5", 61 | "@types/await-timeout": "^0.3.1", 62 | "@types/jest": "^29.5.1", 63 | "@types/node": "^18.16.3", 64 | "@types/simple-oauth2": "^5.0.4", 65 | "babel-jest": "^29.7.0", 66 | "commitlint": "^17.6.1", 67 | "dotenv": "^16.0.3", 68 | "eslint": "^8.39.0", 69 | "husky": "^8.0.3", 70 | "jest": "^29.7.0", 71 | "lint-staged": "^13.2.2", 72 | "prettier": "^3.0.3", 73 | "rimraf": "^5.0.0", 74 | "semantic-release": "^21.1.1", 75 | "ts-jest": "^29.1.1", 76 | "ts-node": "^10.9.1", 77 | "typescript": "^5.0.4" 78 | }, 79 | "release": { 80 | "branches": [ 81 | "main" 82 | ] 83 | }, 84 | "publishConfig": { 85 | "access": "public" 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/client/client.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | dotenv.config({ path: "./.env" }); 3 | 4 | import { ZohoApiClient } from "./client"; 5 | 6 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 7 | const clientId = process.env.ZOHO_CLIENT_ID as string; 8 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 9 | const clientIdUS = process.env.ZOHO_CLIENT_ID_US as string; 10 | const clientSecretUS = process.env.ZOHO_CLIENT_SECRET_US as string; 11 | 12 | it("works to create a new Zoho Client Instance without specifying the datacenter (using .eu)", async () => { 13 | 14 | const client = await ZohoApiClient.fromOAuth({ 15 | orgId, 16 | client: { 17 | id: clientId, 18 | secret: clientSecret, 19 | }, 20 | }); 21 | expect(client).toBeInstanceOf(ZohoApiClient); 22 | }); 23 | 24 | it("works to create a new Zoho Client Instance with datacenter .com", async () => { 25 | 26 | const client = await ZohoApiClient.fromOAuth({ 27 | orgId, 28 | client: { 29 | id: clientIdUS, 30 | secret: clientSecretUS, 31 | }, 32 | dc: ".com", 33 | }); 34 | expect(client).toBeInstanceOf(ZohoApiClient); 35 | }); 36 | 37 | it("works to create a new Zoho Client Instance with API flavour invoice", async () => { 38 | 39 | const client = await ZohoApiClient.fromOAuth({ 40 | orgId, 41 | client: { 42 | id: clientId, 43 | secret: clientSecret, 44 | }, 45 | apiFlavour: "invoice", 46 | scope: "ZohoInvoice.fullaccess.all" 47 | }); 48 | expect(client).toBeInstanceOf(ZohoApiClient); 49 | }); 50 | -------------------------------------------------------------------------------- /src/client/client.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from "axios"; 2 | import { ClientCredentials } from "simple-oauth2"; 3 | 4 | /** 5 | * Use it to select the Zoho API to use (/books /inventory /invoice). 6 | * The main API of the Zoho finance suite to connect to. Some API endpoints, 7 | * that are existing for example only for Zoho Books (like "bankaccount") will still 8 | * use a specific API endpoint. Use together with "scope" to use the correct security scope 9 | */ 10 | export type APIFlavour = "inventory" | "books" | "invoice"; 11 | 12 | export type Request = { 13 | path: string[]; 14 | /** 15 | * Url Paramters 16 | */ 17 | params?: Record; 18 | /** 19 | * Request body will be serialized to json 20 | */ 21 | body?: unknown; 22 | 23 | headers?: Record; 24 | 25 | /** 26 | * Retry the request a number of times while backing off exponentially 27 | */ 28 | retry?: number; 29 | 30 | /** 31 | * in milliseconds 32 | * @default 7000 33 | */ 34 | timeout?: number; 35 | 36 | /** 37 | * Override the base Url for this request 38 | */ 39 | baseUrl?: string; 40 | 41 | /** 42 | * Should we use Zoho Books or Zoho Inventory API. Defaults to "inventory" 43 | */ 44 | overwriteApiType?: APIFlavour; 45 | }; 46 | 47 | /** 48 | * Enum definition of the different entities, 49 | * that Zoho offers. 50 | */ 51 | enum ZohoEntities { 52 | SALESORDERS = "salesorders", 53 | INVOICES = "invoices", 54 | CONTACTS = "contacts", 55 | ITEMS = "items", 56 | PURCHASEORDERS = "purchaseorders", 57 | } 58 | 59 | export type ZohoResponse = TResponse & { 60 | /** 61 | * Zoho Inventory error code. This will be zero for a success response and non-zero in case of an error. 62 | */ 63 | code: number; 64 | /** 65 | * Message for the invoked API. 66 | */ 67 | message: string; 68 | 69 | page_context?: { 70 | page: number; 71 | per_page: number; 72 | has_more_page: boolean; 73 | }; 74 | } & { 75 | [key in ZohoEntities]?: { 76 | code: number; 77 | message: string; 78 | }[]; 79 | }; 80 | 81 | export class ZohoApiError extends Error { 82 | url?: string; 83 | 84 | code?: number; 85 | 86 | constructor(err: AxiosError<{ code: number; message: string }>) { 87 | super(err.response?.data.message ?? err.message); 88 | this.url = err?.config?.baseURL + err.request?.path; 89 | this.code = err.response?.data.code; 90 | // 👇️ because we are extending a built-in class 91 | Object.setPrototypeOf(this, ZohoApiError.prototype); 92 | } 93 | } 94 | 95 | export type DataCenter = ".com" | ".eu" | ".in" | ".com.au" | ".jp"; 96 | 97 | export type ZohoApiClientConfig = { 98 | orgId: string; 99 | /** 100 | * The data center of Zoho you want to connect to 101 | */ 102 | dc?: DataCenter; 103 | apiFlavour?: APIFlavour; 104 | headers: Record; 105 | baseUrl?: string; 106 | }; 107 | 108 | export class ZohoApiClient { 109 | private httpClientInventory: AxiosInstance; 110 | 111 | private httpClientBooks: AxiosInstance; 112 | 113 | private httpClientInvoice: AxiosInstance; 114 | 115 | private dataCenter: DataCenter; 116 | 117 | private apiFlavour: APIFlavour; 118 | 119 | private BASE_URL: { 120 | inventory: string; 121 | books: string; 122 | invoice: string; 123 | }; 124 | 125 | private constructor(config: ZohoApiClientConfig) { 126 | this.dataCenter = config.dc || ".eu"; 127 | this.BASE_URL = { 128 | inventory: `https://inventory.zoho${this.dataCenter}/api/v1`, 129 | books: `https://books.zoho${this.dataCenter}/api/v3`, 130 | invoice: `https://invoice.zoho${this.dataCenter}/api/v3`, 131 | }; 132 | this.httpClientInventory = axios.create({ 133 | baseURL: config.baseUrl ?? this.BASE_URL.inventory, 134 | headers: config.headers, 135 | params: { 136 | organization_id: config.orgId, 137 | }, 138 | timeout: 30_000, 139 | }); 140 | this.httpClientInvoice = axios.create({ 141 | baseURL: config.baseUrl ?? this.BASE_URL.invoice, 142 | headers: config.headers, 143 | params: { 144 | organization_id: config.orgId, 145 | }, 146 | timeout: 30_000, 147 | }); 148 | this.httpClientBooks = axios.create({ 149 | baseURL: this.BASE_URL.books, 150 | headers: config.headers, 151 | params: { 152 | organization_id: config.orgId, 153 | }, 154 | timeout: 30_000, 155 | }); 156 | this.apiFlavour = config.apiFlavour || "inventory"; 157 | } 158 | 159 | /** 160 | * Create a zoho api instance from client id and secret 161 | */ 162 | static async fromOAuth(config: { 163 | orgId: string; 164 | client: { id: string; secret: string }; 165 | baseUrl?: string; 166 | /** 167 | * The datacenter you want to use. Defaults to .eu 168 | */ 169 | dc?: DataCenter; 170 | /** 171 | * The API authentication scope, that we are requesting. You might change it to 172 | * less, if you need just certain requests. Defaults to: 173 | * ZohoInventory.FullAccess.all,ZohoBooks.fullaccess.all 174 | */ 175 | scope?: string; 176 | apiFlavour?: APIFlavour; 177 | }): Promise { 178 | const dataCenter = config.dc || ".eu"; 179 | const clientCredentials = new ClientCredentials({ 180 | client: config.client, 181 | auth: { 182 | tokenHost: `https://accounts.zoho${dataCenter}`, 183 | tokenPath: "/oauth/v2/token", 184 | }, 185 | options: { 186 | authorizationMethod: "body", 187 | }, 188 | }); 189 | 190 | /** 191 | * Select an API scope that we request for our auth token. If we got one from the user, we 192 | * always use this one 193 | * @returns 194 | */ 195 | const scopeSelect = () => { 196 | if (config.scope) return config.scope; 197 | switch (config.apiFlavour) { 198 | case "books": 199 | return "ZohoBooks.fullaccess.all"; 200 | case "inventory": 201 | return "ZohoInventory.FullAccess.all"; 202 | case "invoice": 203 | return "ZohoInvoice.FullAccess.all"; 204 | default: 205 | return "ZohoInventory.FullAccess.all"; 206 | } 207 | }; 208 | const res = await clientCredentials.getToken({ 209 | scope: scopeSelect(), 210 | }); 211 | 212 | if (res.token.error) { 213 | throw new Error(res.token.error as string); 214 | } 215 | 216 | return new ZohoApiClient({ 217 | orgId: config.orgId, 218 | headers: { 219 | authorization: `${res.token.token_type} ${res.token.access_token}`, 220 | }, 221 | baseUrl: config.baseUrl, 222 | dc: dataCenter, 223 | }); 224 | } 225 | 226 | /** 227 | * Create a zoho api instance from cookies 228 | * 229 | * This is an undocumented unsupported hack 230 | */ 231 | static async fromCookies(config: { 232 | orgId: string; 233 | cookie: string; 234 | zsrfToken: string; 235 | baseUrl?: string; 236 | }): Promise { 237 | return new ZohoApiClient({ 238 | orgId: config.orgId, 239 | headers: { 240 | Cookie: config.cookie, 241 | "X-ZCSRF-TOKEN": config.zsrfToken, 242 | "User-Agent": 243 | "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36", 244 | }, 245 | baseUrl: config.baseUrl, 246 | }); 247 | } 248 | 249 | private async request( 250 | method: "GET" | "POST" | "PUT" | "DELETE", 251 | req: Request, 252 | ): Promise> { 253 | const axiosRequest: AxiosRequestConfig = { 254 | method, 255 | url: `/${req.path.join("/")}`, 256 | headers: req.headers ?? {}, 257 | params: req.params, 258 | }; 259 | if (req.baseUrl) { 260 | axiosRequest.baseURL = req.baseUrl; 261 | } 262 | if (req.timeout) { 263 | axiosRequest.timeout = req.timeout; 264 | } 265 | 266 | if (req.body) { 267 | if (typeof req.body === "string") { 268 | axiosRequest.data = req.body; 269 | } else { 270 | axiosRequest.data = req.body; 271 | if (!axiosRequest.headers) axiosRequest.headers = {}; 272 | axiosRequest.headers["Content-Type"] = 273 | "application/json;charset=UTF-8"; 274 | } 275 | } 276 | 277 | const selectApiClient = (apiType: APIFlavour) => { 278 | switch (apiType) { 279 | case "books": 280 | return this.httpClientBooks; 281 | case "inventory": 282 | return this.httpClientInventory; 283 | case "invoice": 284 | return this.httpClientInvoice; 285 | default: 286 | return this.httpClientInventory; 287 | } 288 | }; 289 | 290 | // Selection, if this request should use the Zoho Books, Inventory or Invoice API. Can be overwritten by every request 291 | const res = await selectApiClient( 292 | req.overwriteApiType || this.apiFlavour, 293 | ) 294 | .request>(axiosRequest) 295 | .catch((err) => { 296 | throw new ZohoApiError(err); 297 | }); 298 | 299 | if (res.data.code === undefined) { 300 | /** 301 | * The response object looks different for bulk update requests. 302 | * We check here, if this is a bulk response object 303 | */ 304 | const bulkResponse = Object.keys(res.data).find((x) => 305 | Object.values(ZohoEntities).includes( 306 | x as unknown as ZohoEntities, 307 | ), 308 | ); 309 | 310 | if (bulkResponse) { 311 | res.data[bulkResponse as ZohoEntities]?.map((x) => { 312 | if (x.code !== 0) 313 | throw new Error( 314 | `Zoho response error [${x.code}]: ${x.message}`, 315 | ); 316 | }); 317 | } else { 318 | throw new Error( 319 | `Zoho returned not valid response object: ${JSON.stringify( 320 | res.data, 321 | )}`, 322 | ); 323 | } 324 | } else { 325 | if (res.data.code !== 0) { 326 | console.error( 327 | `Zoho response error [${res.data.code}]: ${res.data.message}`, 328 | ); 329 | } 330 | } 331 | 332 | return res.data; 333 | } 334 | 335 | public async get( 336 | req: Request, 337 | ): Promise> { 338 | return this.request("GET", req); 339 | } 340 | 341 | public async post( 342 | req: Request, 343 | ): Promise> { 344 | return this.request("POST", req); 345 | } 346 | 347 | public async put( 348 | req: Request, 349 | ): Promise> { 350 | return this.request("PUT", req); 351 | } 352 | 353 | public async delete( 354 | req: Request, 355 | ): Promise> { 356 | return this.request("DELETE", req); 357 | } 358 | } 359 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./service"; 2 | export * from "./client/client"; 3 | export * from "./types"; 4 | -------------------------------------------------------------------------------- /src/service/bankaccount.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | dotenv.config({ path: "./.env" }); 5 | 6 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 7 | const clientId = process.env.ZOHO_CLIENT_ID as string; 8 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 9 | 10 | let zoho: Zoho; 11 | 12 | describe("Contact Tests", () => { 13 | beforeAll(async () => { 14 | const client = await ZohoApiClient.fromOAuth({ 15 | orgId, 16 | client: { 17 | id: clientId, 18 | secret: clientSecret, 19 | }, 20 | }); 21 | zoho = new Zoho(client); 22 | }); 23 | 24 | test("it should work to list all bankaccounts", async () => { 25 | const res = await zoho.bankaccount.list() 26 | expect(res?.length).toBeGreaterThan(0); 27 | }) 28 | }); 29 | -------------------------------------------------------------------------------- /src/service/bankaccount.ts: -------------------------------------------------------------------------------- 1 | import { ListBankaccount } from "../types/bankaccount"; 2 | import { ZohoApiClient } from "../client/client"; 3 | 4 | export class BankAccountHandler { 5 | private client: ZohoApiClient; 6 | 7 | constructor(client: ZohoApiClient) { 8 | this.client = client; 9 | } 10 | 11 | public async list() { 12 | const res = await this.client.get<{ bankaccounts: ListBankaccount[] }>({ 13 | path: ["bankaccounts"], 14 | overwriteApiType: "books", 15 | }); 16 | return res.bankaccounts; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/service/contact.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | dotenv.config({ path: "./.env" }); 5 | 6 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 7 | const clientId = process.env.ZOHO_CLIENT_ID as string; 8 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 9 | 10 | let zoho: Zoho; 11 | 12 | describe("Contact Tests", () => { 13 | beforeAll(async () => { 14 | const client = await ZohoApiClient.fromOAuth({ 15 | orgId, 16 | client: { 17 | id: clientId, 18 | secret: clientSecret, 19 | }, 20 | }); 21 | zoho = new Zoho(client); 22 | }); 23 | 24 | const contactIds: string[] = []; 25 | let createdContact: string; 26 | 27 | test("It should work to create a contact", async () => { 28 | const contactCreate = await zoho.contact.create({ 29 | contact_persons: [ 30 | { 31 | first_name: "Test User", 32 | last_name: "Lastname", 33 | }, 34 | ], 35 | contact_name: "Test User Lastname", 36 | customer_sub_type: "individual", 37 | billing_address: { 38 | address: "Teststreet billing 101", 39 | zip: "90459", 40 | country: "Germany", 41 | }, 42 | shipping_address: { 43 | address: "Teststreet shipping 101", 44 | zip: "90459", 45 | country: "Germany", 46 | }, 47 | }); 48 | contactIds.push(contactCreate.contact_id); 49 | createdContact = contactCreate.contact_id; 50 | 51 | expect(contactCreate.first_name).toBe("Test User"); 52 | expect(contactCreate.contact_name).toBe("Test User Lastname"); 53 | }); 54 | 55 | let zohoAddressId :string; 56 | test("It should work to add an new address for a contact", async () => { 57 | zohoAddressId = await zoho.contact.addAddress(createdContact, { 58 | address: "New Address 44", 59 | city: "Nürnberg", 60 | zip: "90446", 61 | country: "Germany", 62 | }); 63 | }); 64 | test("It should work to update the address of an contact", async () => { 65 | const resp = await zoho.contact.updateAddress(createdContact, zohoAddressId, { 66 | address: "New Address 44", 67 | city: "Nürnberg", 68 | zip: "90446", 69 | country: "Germany", 70 | }); 71 | expect(resp).toBeDefined(); 72 | 73 | }) 74 | 75 | test("It should work to get a certain contact", async () => { 76 | const contact = await zoho.contact.get(createdContact); 77 | 78 | expect(contact?.shipping_address.address).toBe( 79 | "Teststreet shipping 101", 80 | ); 81 | expect(contact?.shipping_address.country_code).toBe("DE"); 82 | expect(contact?.addresses[0].address).toBe("New Address 44"); 83 | expect(contact?.contact_persons[0].first_name).toBe("Test User"); 84 | }); 85 | 86 | test("It should work to list all contacts", async () => { 87 | const contacts = await zoho.contact.list({}); 88 | 89 | expect(contacts.length).toBeGreaterThan(0); 90 | expect(contacts[0].contact_id).toBeDefined; 91 | const searchForContact = contacts.find( 92 | (x) => x.contact_name === "Test User Lastname", 93 | ); 94 | expect(searchForContact?.contact_id).toBeDefined(); 95 | }, 10000); 96 | 97 | test("It should work to list all contacts with last modified time filter", async () => { 98 | const contacts = await zoho.contact.list({ 99 | lastModifiedTime: new Date("2022-11-10T00:00:00+0100") 100 | }); 101 | 102 | expect(contacts.length).toBeGreaterThan(0); 103 | expect(contacts[0].contact_id).toBeDefined; 104 | const searchForContact = contacts.find( 105 | (x) => x.contact_name === "Test User Lastname", 106 | ); 107 | expect(searchForContact?.contact_id).toBeDefined(); 108 | }); 109 | 110 | test("It should work to list the contactpersons of a contact", async () => { 111 | const response = await zoho.contact.listContactPersons(contactIds[0]); 112 | expect(response.length).toBeGreaterThan(0); 113 | }); 114 | 115 | test("It should work to update a contact", async () => { 116 | const updateContact = { 117 | contact_id: contactIds[0], 118 | contact_name: "Neuer Name" 119 | } 120 | const response = await zoho.contact.update(updateContact); 121 | expect(response.contact_name).toBe("Neuer Name") 122 | }); 123 | 124 | test("It should work to delete a contact", async () => { 125 | await zoho.contact.delete(contactIds); 126 | }); 127 | }); 128 | -------------------------------------------------------------------------------- /src/service/contact.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Contact, 3 | CreateContact, 4 | GetContact, 5 | UpdateContact, 6 | } from "../types/contact"; 7 | import { ZohoApiClient } from "../client/client"; 8 | import { CreateAddress } from "../types/address"; 9 | import { sleep } from "../util/retry"; 10 | import { ContactPersonWithoutContact } from "../types/contactPerson"; 11 | import { lastModifiedDateFormat } from "../util/format"; 12 | 13 | /** 14 | * Handling all methods related to the Zoho Contact Entity 15 | */ 16 | export class ContactHandler { 17 | private client: ZohoApiClient; 18 | 19 | constructor(client: ZohoApiClient) { 20 | this.client = client; 21 | } 22 | 23 | /** 24 | * Create a new contact. User the contact_person array to add first name and last name to the contact 25 | * @param contact 26 | * @returns 27 | */ 28 | public async create(contact: CreateContact): Promise { 29 | const res = await this.client.post<{ contact: GetContact }>({ 30 | path: ["contacts"], 31 | body: contact, 32 | }); 33 | 34 | return res.contact; 35 | } 36 | 37 | /** 38 | * Update a contact. User the contact_person array to add first name and last name to the contact 39 | * @param contact 40 | * @returns 41 | */ 42 | public async update(contact: UpdateContact): Promise { 43 | const res = await this.client.put<{ contact: GetContact }>({ 44 | path: ["contacts", contact.contact_id.toString()], 45 | body: contact, 46 | }); 47 | 48 | return res.contact; 49 | } 50 | 51 | public async get(id: string): Promise { 52 | const res = await this.client.get<{ contact?: GetContact }>({ 53 | path: ["contacts", id], 54 | }); 55 | return res.contact ?? null; 56 | } 57 | 58 | /** 59 | * Delete one ore more contacts 60 | * @param ids 61 | * @returns 62 | */ 63 | public async delete(ids: string[]): Promise { 64 | if (ids.length === 0) { 65 | return; 66 | } 67 | 68 | if (ids.length === 1) { 69 | await this.client.delete({ 70 | path: ["contacts", ids[0]], 71 | }); 72 | return; 73 | } 74 | 75 | await this.client.delete({ 76 | path: ["contacts"], 77 | params: { 78 | contact_ids: ids.join(","), 79 | }, 80 | }); 81 | } 82 | 83 | /** 84 | * Add an address to a contact 85 | * @param contactId the contact ID that this address is related to 86 | * @param address the address as Zoho Address Object 87 | * @returns the Address ID 88 | */ 89 | public async addAddress( 90 | contactId: string, 91 | address: CreateAddress, 92 | ): Promise { 93 | const res = await this.client.post<{ 94 | address_info: { address_id: string }; 95 | }>({ 96 | path: ["contacts", contactId, "address"], 97 | body: { 98 | update_existing_transactions_address: false, 99 | ...address, 100 | }, 101 | }); 102 | 103 | return res.address_info.address_id; 104 | } 105 | 106 | /** 107 | * Add an address to a contact 108 | * @param contactId the contact ID that this address is related to 109 | * @param address the address as Zoho Address Object 110 | * @returns the Address ID 111 | */ 112 | public async updateAddress( 113 | contactId: string, 114 | addressId: string, 115 | address: CreateAddress, 116 | ): Promise { 117 | const res = await this.client.put<{ 118 | address_info: { address_id: string }; 119 | }>({ 120 | path: ["contacts", contactId, "address", addressId], 121 | body: { 122 | ...address, 123 | }, 124 | }); 125 | 126 | return res.address_info.address_id; 127 | } 128 | 129 | /** 130 | * List contact using different filters and sort Orders. Default Limit is 200, resulting in 1 API calls - using pagination automatically. 131 | * Limit the total result using the fields "createdDateStart" (GTE) or "createdDateEnd" (LTE) 132 | * Contacts can be vendors or customers. 133 | * @param opts 134 | * @returns 135 | */ 136 | public async list(opts: { 137 | sortColumn?: "created_time" | "last_modified_time"; 138 | sortOrder?: "ascending" | "descending"; 139 | limit?: number; 140 | /** 141 | * Filter for contacts last modified after this date. 142 | */ 143 | lastModifiedTime?: Date; 144 | /** 145 | * Filter by only active contacts 146 | */ 147 | filterBy?: "active" | "inactive"; 148 | /** 149 | * Filter contacts by either customer or vendor 150 | */ 151 | contactType?: "customer" | "vendor"; 152 | }): Promise { 153 | const contacts: Contact[] = []; 154 | let hasMorePages = true; 155 | let page = 1; 156 | 157 | while (hasMorePages) { 158 | const res = await this.client.get<{ contacts: Contact[] }>({ 159 | path: ["contacts"], 160 | params: { 161 | sort_column: opts.sortColumn ?? "created_time", 162 | sort_order: opts.sortOrder === "ascending" ? "A" : "D", 163 | per_page: "200", 164 | page, 165 | status: opts.filterBy || "", 166 | contact_type: opts.contactType || "", 167 | last_modified_time: opts.lastModifiedTime 168 | ? lastModifiedDateFormat(opts.lastModifiedTime) 169 | : "", 170 | }, 171 | }); 172 | 173 | contacts.push(...res.contacts); 174 | if (!res.page_context) continue; 175 | hasMorePages = res.page_context?.has_more_page ?? false; 176 | page = res.page_context.page + 1 ?? 0 + 1; 177 | } 178 | 179 | return contacts; 180 | } 181 | 182 | /** 183 | * Get a list of all contact persons of this contact 184 | * @param contactId 185 | * @returns 186 | */ 187 | public async listContactPersons(contactId: string) { 188 | let hasMorePages = true; 189 | let page = 1; 190 | const contactPersons: ContactPersonWithoutContact[] = []; 191 | 192 | while (hasMorePages) { 193 | const res = await this.client.get<{ 194 | contact_persons: ContactPersonWithoutContact[]; 195 | }>({ 196 | path: ["contacts", contactId, "contactpersons"], 197 | params: { 198 | page, 199 | }, 200 | }); 201 | 202 | contactPersons.push(...res.contact_persons); 203 | if (!res.page_context) continue; 204 | hasMorePages = res.page_context?.has_more_page ?? false; 205 | page = res.page_context.page + 1 ?? 0 + 1; 206 | 207 | /** 208 | * Sleep to not get blocked by Zoho 209 | */ 210 | if (hasMorePages) await sleep(1000); 211 | } 212 | 213 | return contactPersons; 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/service/contactperson.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | dotenv.config({ path: "./.env" }); 5 | 6 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 7 | const clientId = process.env.ZOHO_CLIENT_ID as string; 8 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 9 | 10 | let zoho :Zoho 11 | 12 | describe("ContactPerson Tests", () => { 13 | 14 | beforeAll(async () => { 15 | const client = await ZohoApiClient.fromOAuth({ 16 | orgId, 17 | client: { 18 | id: clientId, 19 | secret: clientSecret, 20 | }, 21 | }); 22 | zoho = new Zoho(client); 23 | 24 | }) 25 | 26 | 27 | const contactIds: string[] = []; 28 | let contactPersonId: string 29 | 30 | test("It should work to create a contact and add a contact person", async () => { 31 | const contactCreate = await zoho.contact.create({ 32 | contact_persons: [{ 33 | first_name: "Test User", 34 | last_name: "Lastname", 35 | is_primary_contact: true, 36 | }], 37 | contact_name: "Test User Lastname", 38 | customer_sub_type: "individual", 39 | }); 40 | contactIds.push(contactCreate.contact_id); 41 | 42 | expect(contactCreate.first_name).toBe("Test User"); 43 | expect(contactCreate.contact_name).toBe("Test User Lastname"); 44 | 45 | const contactPersonCreate = await zoho.contactperson.create({ 46 | contact_id: contactCreate.contact_id, 47 | first_name: "", 48 | last_name: "Contactpersontest" 49 | }) 50 | expect(contactPersonCreate.last_name).toBe("Contactpersontest") 51 | contactPersonId = contactPersonCreate.contact_person_id; 52 | }); 53 | 54 | test("It should work to list all contact persons", async () => { 55 | const contactPersons = await zoho.contactperson.list(); 56 | 57 | expect(contactPersons.length).toBeGreaterThan(0); 58 | expect(contactPersons[0].contact_id).toBeDefined; 59 | }, 20000) 60 | 61 | test("It should work to delete a contactPerson", async () => { 62 | await zoho.contactperson.delete(contactPersonId) 63 | await zoho.contact.delete(contactIds) 64 | }) 65 | }); 66 | -------------------------------------------------------------------------------- /src/service/contactperson.ts: -------------------------------------------------------------------------------- 1 | import { ZohoApiClient } from "../client/client"; 2 | import { ContactPerson } from "../types"; 3 | import { CreateContactPerson } from "../types/contactPerson"; 4 | import { sleep } from "../util/retry"; 5 | 6 | /** 7 | * Handling all methods related to the Zoho ContactPerson Entity 8 | */ 9 | export class ContactPersonHandler { 10 | private client: ZohoApiClient; 11 | 12 | constructor(client: ZohoApiClient) { 13 | this.client = client; 14 | } 15 | 16 | /** 17 | * Add a contact person to a contact 18 | * @param contactPerson 19 | * @returns 20 | */ 21 | public async create( 22 | contactPerson: CreateContactPerson, 23 | ): Promise { 24 | const res = await this.client.post<{ contact_person: ContactPerson }>({ 25 | path: ["contacts", "contactpersons"], 26 | body: contactPerson, 27 | }); 28 | 29 | return res.contact_person; 30 | } 31 | 32 | /** 33 | * Get a specific contact person 34 | * @param contactId 35 | * @param contactPersonId 36 | * @returns 37 | */ 38 | public async get( 39 | contactId: string, 40 | contactPersonId: string, 41 | ): Promise { 42 | const res = await this.client.get<{ contact_person?: ContactPerson }>({ 43 | path: ["contacts", contactId, "contactpersons", contactPersonId], 44 | }); 45 | return res.contact_person ?? null; 46 | } 47 | 48 | /** 49 | * Delete a contact person 50 | * @param contactId 51 | * @param contactPersonId 52 | * @returns 53 | */ 54 | public async delete(contactPersonId: string): Promise { 55 | await this.client.delete({ 56 | path: ["contacts", "contactpersons", contactPersonId], 57 | }); 58 | return; 59 | } 60 | 61 | /** 62 | * List all contact persons 63 | * @returns 64 | */ 65 | public async list(): Promise { 66 | let hasMorePages = true; 67 | let page = 1; 68 | const contactPersons: ContactPerson[] = []; 69 | 70 | while (hasMorePages) { 71 | const res = await this.client.get<{ 72 | contact_persons: ContactPerson[]; 73 | }>({ 74 | path: ["contacts", "contactpersons"], 75 | params: { 76 | page, 77 | }, 78 | }); 79 | 80 | contactPersons.push(...res.contact_persons); 81 | if (!res.page_context) continue; 82 | hasMorePages = res.page_context?.has_more_page ?? false; 83 | page = res.page_context.page + 1 ?? 0 + 1; 84 | 85 | /** 86 | * Sleep to not get blocked by Zoho 87 | */ 88 | await sleep(1000); 89 | } 90 | 91 | return contactPersons; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/service/index.ts: -------------------------------------------------------------------------------- 1 | import { ZohoApiClient } from "../client/client"; 2 | import { SalesOrderHandler } from "./salesOrder"; 3 | import { ItemHandler } from "./item"; 4 | import { ContactHandler } from "./contact"; 5 | import { PackageHandler } from "./package"; 6 | import { InvoiceHandler } from "./invoice"; 7 | import { WarehouseHandler } from "./warehouse"; 8 | import { PaymentHandler } from "./payment"; 9 | import { Utils } from "./util"; 10 | import { TaxHandler } from "./tax"; 11 | import { ContactPersonHandler } from "./contactperson"; 12 | import { OrganizationHandler } from "./organizations"; 13 | import { BankAccountHandler } from "./bankaccount"; 14 | export class Zoho { 15 | public readonly salesOrder: SalesOrderHandler; 16 | 17 | public readonly item: ItemHandler; 18 | 19 | public readonly contact: ContactHandler; 20 | 21 | public readonly package: PackageHandler; 22 | 23 | public readonly invoice: InvoiceHandler; 24 | 25 | public readonly warehouse: WarehouseHandler; 26 | 27 | public readonly payment: PaymentHandler; 28 | 29 | public readonly util: Utils; 30 | 31 | public readonly tax: TaxHandler; 32 | 33 | public readonly contactperson: ContactPersonHandler; 34 | 35 | public readonly organization: OrganizationHandler; 36 | 37 | public readonly bankaccount: BankAccountHandler; 38 | 39 | constructor(client: ZohoApiClient) { 40 | this.salesOrder = new SalesOrderHandler(client); 41 | this.item = new ItemHandler(client); 42 | this.package = new PackageHandler(client); 43 | this.contact = new ContactHandler(client); 44 | this.invoice = new InvoiceHandler(client); 45 | this.warehouse = new WarehouseHandler(client); 46 | this.payment = new PaymentHandler(client); 47 | this.util = new Utils(); 48 | this.tax = new TaxHandler(client); 49 | this.contactperson = new ContactPersonHandler(client); 50 | this.organization = new OrganizationHandler(client); 51 | this.bankaccount = new BankAccountHandler(client); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/service/invoice.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | 5 | dotenv.config({ path: "./.env" }); 6 | 7 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 8 | const clientId = process.env.ZOHO_CLIENT_ID as string; 9 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 10 | 11 | let zoho: Zoho; 12 | let testUserId: string; 13 | let testUserContactPerson: string; 14 | let testSalesOrderId: string; 15 | let testSalesOrderTotal: number; 16 | 17 | describe("invoice Tests", () => { 18 | beforeAll(async () => { 19 | const client = await ZohoApiClient.fromOAuth({ 20 | orgId, 21 | client: { 22 | id: clientId, 23 | secret: clientSecret, 24 | }, 25 | }); 26 | zoho = new Zoho(client); 27 | }); 28 | 29 | const invoiceIds: string[] = []; 30 | 31 | test("It should work to create a invoice", async () => { 32 | const testUser = await zoho.contact.create({ 33 | contact_name: "Test Run User Zoho TS", 34 | customer_sub_type: "individual", 35 | contact_persons: [ 36 | { 37 | email: "testuser@trieb.work", 38 | first_name: "Jest", 39 | last_name: "Runner", 40 | }, 41 | ], 42 | }); 43 | testUserId = testUser.contact_id; 44 | testUserContactPerson = testUser.contact_persons[0].contact_person_id; 45 | 46 | const invoice = await zoho.invoice.create({ 47 | customer_id: testUser.contact_id, 48 | line_items: [ 49 | { 50 | item_id: "116240000000203041", 51 | quantity: 5, 52 | }, 53 | ], 54 | }); 55 | invoiceIds.push(invoice.invoice_id); 56 | expect(invoice.customer_id).toBe(testUser.contact_id); 57 | }); 58 | 59 | test("it should work to create an invoice from a salesorder", async () => { 60 | const salesOrderCreate = await zoho.salesOrder.create({ 61 | customer_id: testUserId, 62 | contact_persons: [testUserContactPerson], 63 | discount_type: "entity_level", 64 | salesorder_number: "TEST-34003594", 65 | line_items: [ 66 | { 67 | item_id: "116240000000203041", 68 | quantity: 5, 69 | discount: 10, 70 | }, 71 | ], 72 | }); 73 | testSalesOrderId = salesOrderCreate.salesorder_id; 74 | testSalesOrderTotal = salesOrderCreate.total; 75 | 76 | const invoice = await zoho.invoice.createFromSalesOrder( 77 | salesOrderCreate.salesorder_id, 78 | ); 79 | invoiceIds.push(invoice.invoice_id); 80 | expect(invoice.invoice_id).toBeDefined(); 81 | expect(invoice.contact_persons_details.length).toBe(1); 82 | expect(invoice.reference_number).toBe("TEST-34003594"); 83 | expect(invoice.total).toBe(testSalesOrderTotal); 84 | }); 85 | 86 | test("It should work to list invoice sorted by last_update_date", async () => { 87 | const res = await zoho.invoice.list({ 88 | sortColumn: "last_modified_time", 89 | createdDateStart: "2022-01-01", 90 | }); 91 | expect(res.length).toBeGreaterThan(0); 92 | }); 93 | 94 | test("It should work to mark invoices as sent", async () => { 95 | await zoho.invoice.sent(invoiceIds); 96 | const allInvoices = await zoho.invoice.list({}); 97 | for(const invoiceId of invoiceIds){ 98 | const invoice = allInvoices.find((inv) => inv.invoice_id === invoiceId); 99 | if(invoice?.status !== "sent") { 100 | throw new Error(`Invoice with id ${invoiceId} was marked as status sent but did not have status sent in status check.`); 101 | } 102 | } 103 | }); 104 | 105 | test("It should work to delete invoices", async () => { 106 | await zoho.invoice.delete(invoiceIds); 107 | const allInvoices = await zoho.invoice.list({}); 108 | for(const invoiceId of invoiceIds){ 109 | const invoice = allInvoices.find((inv) => inv.invoice_id === invoiceId); 110 | if(invoice) { 111 | throw new Error(`Invoice with id ${invoiceId} was deleted by test but was still returned by the search.`); 112 | } 113 | } 114 | }); 115 | 116 | afterAll(async () => { 117 | await zoho.salesOrder.delete([testSalesOrderId]); 118 | await zoho.contact.delete([testUserId]); 119 | }); 120 | }); 121 | -------------------------------------------------------------------------------- /src/service/invoice.ts: -------------------------------------------------------------------------------- 1 | import { sleep } from "../util/retry"; 2 | import { ZohoApiClient } from "../client/client"; 3 | import { Invoice, CreateInvoice, ListInvoice } from "../types/invoice"; 4 | import { lastModifiedDateFormat } from "../util/format"; 5 | 6 | /** 7 | * The Handler class for all functionality concerning Zoho 8 | * Invoices 9 | */ 10 | export class InvoiceHandler { 11 | private client: ZohoApiClient; 12 | 13 | constructor(client: ZohoApiClient) { 14 | this.client = client; 15 | } 16 | 17 | public async create(invoice: CreateInvoice): Promise { 18 | const res = await this.client.post<{ invoice: Invoice }>({ 19 | path: ["invoices"], 20 | body: invoice, 21 | params: { 22 | ignore_auto_number_generation: invoice.invoice_number 23 | ? true 24 | : false, 25 | }, 26 | }); 27 | 28 | return res.invoice; 29 | } 30 | 31 | /** 32 | * List invoice using different filters and sort Orders. Default Limit is 200, resulting in 1 API calls - using pagination automatically. 33 | * Limit the total result using the fields "createdDateStart" (GTE) or "createdDateEnd" (LTE) 34 | * @param opts 35 | * @returns 36 | */ 37 | public async list( 38 | opts: 39 | | { 40 | sortColumn?: 41 | | "date" 42 | | "created_time" 43 | | "last_modified_time" 44 | | "total"; 45 | sortOrder?: "ascending" | "descending"; 46 | /** 47 | * Filter for salesorders last modified after this date. 48 | */ 49 | lastModifiedTime?: Date; 50 | /** 51 | * yyyy-mm-dd 52 | */ 53 | createdDateStart?: string; 54 | /** 55 | * yyyy-mm-dd 56 | */ 57 | createdDateEnd?: string; 58 | /** 59 | * Filter Invoices by a specific Custom View ID 60 | */ 61 | customViewId?: string; 62 | } 63 | | undefined, 64 | ): Promise { 65 | const invoices: ListInvoice[] = []; 66 | let hasMorePages = true; 67 | let page = 1; 68 | 69 | while (hasMorePages) { 70 | const res = await this.client.get<{ invoices: ListInvoice[] }>({ 71 | path: ["invoices"], 72 | params: { 73 | sort_column: opts?.sortColumn ?? "date", 74 | sort_order: opts?.sortOrder === "ascending" ? "A" : "D", 75 | per_page: "200", 76 | page, 77 | created_date_start: opts?.createdDateStart || "", 78 | created_date_end: opts?.createdDateEnd || "", 79 | customview_id: opts?.customViewId || "", 80 | last_modified_time: opts?.lastModifiedTime 81 | ? lastModifiedDateFormat(opts.lastModifiedTime) 82 | : "", 83 | }, 84 | }); 85 | 86 | invoices.push(...res.invoices); 87 | if (!res.page_context) continue; 88 | hasMorePages = res.page_context?.has_more_page ?? false; 89 | page = res.page_context.page + 1 ?? 0 + 1; 90 | /** 91 | * Sleep to not get blocked by Zoho 92 | */ 93 | await sleep(1000); 94 | } 95 | 96 | return invoices; 97 | } 98 | 99 | /** 100 | * Get a single invoice by ID 101 | * @param id 102 | * @returns 103 | */ 104 | public async get(id: string): Promise { 105 | const res = await this.client.get<{ invoice: Invoice }>({ 106 | path: ["invoices", id], 107 | }); 108 | 109 | return res.invoice; 110 | } 111 | 112 | /** 113 | * Delete one or several invoices at once. Can be used for 114 | * unlimited amount of invoices. Creates chunks of 25 115 | * @param ids 116 | * @returns 117 | */ 118 | public async delete(ids: string[]): Promise { 119 | if (ids.length === 0) { 120 | return; 121 | } 122 | 123 | if (ids.length === 1) { 124 | await this.client.delete({ 125 | path: ["invoices", ids[0]], 126 | }); 127 | return; 128 | } 129 | 130 | const chunkSize = 25; 131 | const chunks: string[][] = []; 132 | for (let i = 0; i < ids.length; i += chunkSize) { 133 | chunks.push(ids.slice(i, i + chunkSize)); 134 | } 135 | for (const chunk of chunks) { 136 | await this.client.delete({ 137 | path: ["invoices"], 138 | params: { 139 | invoice_ids: chunk.join(","), 140 | }, 141 | }); 142 | } 143 | } 144 | 145 | /** 146 | * Generate an invoice from a salesorder. 147 | * @param id SalesorderID 148 | * @returns 149 | */ 150 | public async createFromSalesOrder(id: string): Promise { 151 | const res = await this.client.post<{ invoice: Invoice }>({ 152 | path: ["invoices", "fromsalesorder"], 153 | params: { 154 | salesorder_id: id, 155 | }, 156 | }); 157 | return res.invoice; 158 | } 159 | 160 | /** 161 | * Sent (similar to confirm) one ore many invoices at once. Can be used for unlimited amount of Invoices. Creates chunks of 25. 162 | * @param ids 163 | */ 164 | public async sent(ids: string[]): Promise { 165 | const chunkSize = 25; 166 | const chunks: string[][] = []; 167 | for (let i = 0; i < ids.length; i += chunkSize) { 168 | chunks.push(ids.slice(i, i + chunkSize)); 169 | } 170 | 171 | for (const chunk of chunks) { 172 | await this.client.post<{ invoice: Invoice }>({ 173 | path: ["invoices", "status", "sent"], 174 | headers: { 175 | "Content-Type": 176 | "application/x-www-form-urlencoded; charset=UTF-8", 177 | }, 178 | body: `invoice_ids=${encodeURIComponent(chunk.join(","))}`, 179 | }); 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/service/item.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | 5 | dotenv.config({ path: "./.env" }); 6 | 7 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 8 | const clientId = process.env.ZOHO_CLIENT_ID as string; 9 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 10 | const testCompositeItemId = "116240000001686001" 11 | const testItemsArray :string[] = []; 12 | 13 | let zoho :Zoho 14 | // let testUserId: string; 15 | 16 | describe("Item Tests", () => { 17 | beforeAll(async () => { 18 | 19 | const client = await ZohoApiClient.fromOAuth({ 20 | orgId, 21 | client: { 22 | id: clientId, 23 | secret: clientSecret, 24 | }, 25 | }); 26 | zoho = new Zoho(client); 27 | 28 | }) 29 | 30 | 31 | 32 | // const itemIds: string[] = []; 33 | 34 | // test ("It should work to create an article", async () => { 35 | // const testUser = await zoho.contact.create({ contact_name: "Test Run User Zoho TS" }) 36 | // testUserId = testUser.contact_id; 37 | 38 | // const item = await zoho.item.create({ 39 | // customer_id: testUser.contact_id, 40 | // line_items: [ 41 | // { 42 | // item_id: "116240000000203041", 43 | // quantity: 5, 44 | // }, 45 | // ], 46 | // }); 47 | // itemIds.push(item.Item_id) 48 | // expect(item.customer_id).toBe(testUser.contact_id); 49 | 50 | // }) 51 | 52 | let itemGroupId: string 53 | test("It should work to create an Item Group with two Items", async () => { 54 | const itemGroup = await zoho.item.createGroup({ 55 | group_name: "Test Item Group Lebkuchen", 56 | unit: "Stück", 57 | items: [{ 58 | sku: "test-123", 59 | name: "Test Item 1", 60 | rate: 1, 61 | purchase_rate: 0.5, 62 | }, { 63 | sku: "test-124", 64 | name: "Test Item 2", 65 | rate: 5, 66 | purchase_rate: 2, 67 | }] 68 | }) 69 | 70 | expect(itemGroup.group_id).toBeDefined(); 71 | itemGroupId = itemGroup.group_id; 72 | 73 | } ) 74 | 75 | test("It should work to delete the item group again", async () => { 76 | await zoho.item.deleteGroup(itemGroupId); 77 | }) 78 | 79 | test("It should work to list Item sorted by last_update_date", async () => { 80 | const res = await zoho.item.list({ sortColumn: "last_modified_time" }) 81 | expect(res.length).toBeGreaterThan(0); 82 | res.map((r) => testItemsArray.push(r.item_id)) 83 | }) 84 | 85 | test("It should work to pull many items with GetMany",async () => { 86 | console.log(`Pulling ${testItemsArray.length} items with getMany`) 87 | const res = await zoho.item.getMany(testItemsArray) 88 | expect(res.find((i) => i.item_id === testItemsArray[0])).toBeDefined(); 89 | }) 90 | 91 | test("It should work to list only inactive items", async () => { 92 | const res = await zoho.item.list({ filterBy: "inactive" }) 93 | expect(res.length).toBeGreaterThan(0); 94 | expect(res[0].status === "inactive") 95 | }) 96 | 97 | test("It should work to get a composite item", async () => { 98 | const res = await zoho.item.getComposite(testCompositeItemId) 99 | 100 | expect(res.mapped_items.length).toBe(2) 101 | }) 102 | 103 | // test("It should work to delete a item", async () => { 104 | // await zoho.item.delete(itemIds); 105 | 106 | // }); 107 | 108 | // afterAll(async () => { 109 | // await zoho.contact.delete([testUserId]); 110 | 111 | // }) 112 | 113 | 114 | }); -------------------------------------------------------------------------------- /src/service/item.ts: -------------------------------------------------------------------------------- 1 | import { ZohoApiClient } from "../client/client"; 2 | import { 3 | CreateItem, 4 | CreateItemGroup, 5 | ItemGroup, 6 | Item, 7 | GetItem, 8 | FullCompositeItem, 9 | ListItem, 10 | } from "../types/item"; 11 | import { lastModifiedDateFormat } from "../util/format"; 12 | 13 | export class ItemHandler { 14 | private client: ZohoApiClient; 15 | 16 | constructor(client: ZohoApiClient) { 17 | this.client = client; 18 | } 19 | 20 | /** 21 | * Get many items at once - needs just 1 API call for 100 item details. 22 | * @param ids 23 | * @returns 24 | */ 25 | public async getMany(ids: string[]): Promise { 26 | const chunkSize = 100; 27 | const chunks: string[][] = []; 28 | for (let i = 0; i < ids.length; i += chunkSize) { 29 | chunks.push(ids.slice(i, i + chunkSize)); 30 | } 31 | const responseArray: GetItem[] = []; 32 | for (const chunk of chunks) { 33 | const result = await this.client.get<{ items: GetItem[] }>({ 34 | path: ["itemdetails"], 35 | params: { 36 | item_ids: chunk.join(","), 37 | }, 38 | }); 39 | result.items.map((i) => responseArray.push(i)); 40 | } 41 | return responseArray; 42 | } 43 | 44 | /** 45 | * Gets just one item. Better use getMany 46 | * @param id 47 | * @returns 48 | */ 49 | public async get(id: string): Promise { 50 | const res = await this.client.get<{ item: GetItem }>({ 51 | path: ["items", id], 52 | }); 53 | 54 | if (!res.item) { 55 | throw new Error(`Item with id: ${id} was not found`); 56 | } 57 | return res.item; 58 | } 59 | 60 | /** 61 | * Item ID and composite Item IDs are the same - this route just returns the exact mapped items 62 | * of a composite item 63 | * @param id 64 | * @returns 65 | */ 66 | public async getComposite(id: string): Promise { 67 | const res = await this.client.get<{ 68 | composite_item: FullCompositeItem; 69 | }>({ 70 | path: ["compositeitems", id], 71 | }); 72 | 73 | if (!res.composite_item) { 74 | throw new Error(`CompositeItem with id: ${id} was not found`); 75 | } 76 | return res.composite_item; 77 | } 78 | 79 | /** 80 | * List items using different filters and sort Orders. Default Limit is 200, resulting in 1 API calls - using pagination automatically. 81 | * Limit the total result using the fields "createdDateStart" (GTE) or "createdDateEnd" (LTE) 82 | * @param opts 83 | * @returns 84 | */ 85 | public async list(opts: { 86 | sortColumn?: "created_time" | "last_modified_time"; 87 | sortOrder?: "ascending" | "descending"; 88 | /** 89 | * Filter by only active products 90 | */ 91 | filterBy?: "active" | "inactive"; 92 | /** 93 | * Filter for items last modified after this date. 94 | */ 95 | lastModifiedTime?: Date; 96 | }): Promise { 97 | const items: ListItem[] = []; 98 | let hasMorePages = true; 99 | let page = 1; 100 | 101 | while (hasMorePages) { 102 | const res = await this.client.get<{ items: ListItem[] }>({ 103 | path: ["items"], 104 | params: { 105 | sort_column: opts.sortColumn ?? "created_time", 106 | sort_order: opts.sortOrder === "ascending" ? "A" : "D", 107 | per_page: "200", 108 | page, 109 | status: opts.filterBy || "", 110 | last_modified_time: opts.lastModifiedTime 111 | ? lastModifiedDateFormat(opts.lastModifiedTime) 112 | : "", 113 | }, 114 | }); 115 | 116 | items.push(...res.items); 117 | if (!res.page_context) continue; 118 | hasMorePages = res.page_context?.has_more_page ?? false; 119 | page = res.page_context.page + 1 ?? 0 + 1; 120 | } 121 | 122 | return items; 123 | } 124 | 125 | /** 126 | * Create a new item. 127 | * @param item 128 | * @returns 129 | */ 130 | public async create(item: CreateItem): Promise { 131 | const res = await this.client.post<{ item: Item }>({ 132 | path: ["items"], 133 | body: item, 134 | }); 135 | 136 | return res.item; 137 | } 138 | 139 | /** 140 | * Create a new Itemgroup with Items 141 | * @param itemgroup 142 | * @returns 143 | */ 144 | public async createGroup(itemgroup: CreateItemGroup): Promise { 145 | const res = await this.client.post<{ item_group: ItemGroup }>({ 146 | path: ["itemgroups"], 147 | body: itemgroup, 148 | }); 149 | 150 | return res.item_group; 151 | } 152 | 153 | /** 154 | * Delete an item_group and all items of it 155 | * @param id 156 | */ 157 | public async deleteGroup(id: string): Promise { 158 | await this.client.delete({ 159 | path: ["itemgroups", id], 160 | }); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/service/organizations.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | 5 | dotenv.config({ path: "./.env" }); 6 | 7 | const orgIdUS = process.env.ZOHO_ORGANIZATION_ID_US as string; 8 | const clientIdUS = process.env.ZOHO_CLIENT_ID_US as string; 9 | const clientSecretUS = process.env.ZOHO_CLIENT_SECRET_US as string; 10 | 11 | let zoho: Zoho; 12 | // let testUserId: string; 13 | 14 | describe("Organization Tests", () => { 15 | beforeAll(async () => { 16 | const client = await ZohoApiClient.fromOAuth({ 17 | orgId: orgIdUS, 18 | client: { 19 | id: clientIdUS, 20 | secret: clientSecretUS, 21 | }, 22 | dc: ".com" 23 | }); 24 | zoho = new Zoho(client); 25 | }); 26 | 27 | test("It should work to pull an org from the US datacenter", async () => { 28 | const res = await zoho.organization.list(); 29 | 30 | expect(res[0].organization_id).toBe(orgIdUS) 31 | 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /src/service/organizations.ts: -------------------------------------------------------------------------------- 1 | import { ZohoApiClient } from "src/client/client"; 2 | import { Organization } from "src/types/organizations"; 3 | 4 | export class OrganizationHandler { 5 | private client: ZohoApiClient; 6 | 7 | constructor(client: ZohoApiClient) { 8 | this.client = client; 9 | } 10 | 11 | public async list() { 12 | const res = await this.client.get<{ organizations: Organization[] }>({ 13 | path: ["organizations"], 14 | }); 15 | 16 | return res.organizations; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/service/package.test.ts: -------------------------------------------------------------------------------- 1 | import { randomInt } from "crypto"; 2 | import { format } from "date-fns"; 3 | import dotenv from "dotenv"; 4 | import { Zoho } from "."; 5 | import { ZohoApiClient, ZohoApiError } from "../client/client"; 6 | import { SalesOrder } from "../types"; 7 | import { QuickCreateInput } from "../types/package"; 8 | dotenv.config({ path: "./.env" }); 9 | 10 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 11 | const clientId = process.env.ZOHO_CLIENT_ID as string; 12 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 13 | 14 | let zoho :Zoho 15 | 16 | describe("package Tests", () => { 17 | 18 | const packageIds: string[] = []; 19 | let testUserId: string; 20 | let testSalesOrderId: string; 21 | let testSalesOrders: SalesOrder[] = []; 22 | let testShipmentOrderIds: string[] = []; 23 | 24 | beforeAll(async () => { 25 | const client = await ZohoApiClient.fromOAuth({ 26 | orgId, 27 | client: { 28 | id: clientId, 29 | secret: clientSecret, 30 | }, 31 | }); 32 | zoho = new Zoho(client); 33 | 34 | // create a salesorder for which we create the package 35 | const testUser = await zoho.contact.create({ contact_name: "Test Run User Zoho TS", customer_sub_type: "individual" }) 36 | testUserId = testUser.contact_id; 37 | 38 | }) 39 | 40 | 41 | 42 | 43 | test("It should work to create a package", async () => { 44 | 45 | 46 | const salesOrder = await zoho.salesOrder.create({ 47 | salesorder_number: ["TEST", randomInt(90000)].join("-"), 48 | customer_id: testUserId, 49 | line_items: [ 50 | { 51 | item_id: "116240000000203041", 52 | quantity: 5, 53 | }, 54 | ], 55 | }); 56 | testSalesOrderId = salesOrder.salesorder_id; 57 | testSalesOrders.push(salesOrder); 58 | 59 | const packageCreate = await zoho.package.create({ 60 | date: format(new Date(), "yyyy-MM-dd"), 61 | line_items: [{ 62 | so_line_item_id: salesOrder.line_items[0].line_item_id, 63 | quantity: 3 64 | }] 65 | }, testSalesOrderId); 66 | packageIds.push(packageCreate.package_id); 67 | 68 | }); 69 | 70 | test("It should work to create a package with a manual set package number", async () => { 71 | const packageCreate = await zoho.package.create({ 72 | package_number: "LF-33567434", 73 | date: format(new Date(), "yyyy-MM-dd"), 74 | line_items: [{ 75 | so_line_item_id: testSalesOrders[0].line_items[0].line_item_id, 76 | quantity: 2 77 | }] 78 | }, testSalesOrderId); 79 | packageIds.push(packageCreate.package_id); 80 | expect(packageCreate.package_number).toBe("LF-33567434") 81 | 82 | }) 83 | 84 | test("It should work to create a shipmentorder for a package", async () => { 85 | const shipmentCreate = await zoho.package.createShipment({ 86 | date: format(new Date(), "yyyy-MM-dd"), 87 | delivery_method: "DHL Germany", 88 | tracking_number: "92358gfw8reg5", 89 | aftership_carrier_code: "dhl", 90 | }, testSalesOrderId, packageIds[0], true) 91 | 92 | expect(shipmentCreate.tracking_number).toBe("92358gfw8reg5") 93 | testShipmentOrderIds.push(shipmentCreate.shipment_id); 94 | 95 | }); 96 | 97 | 98 | test("It should work to list all packages", async () => { 99 | const packages = await zoho.package.list({}) 100 | 101 | expect(packages.length).toBeGreaterThan(0); 102 | expect(packages[0].package_id).toBeDefined; 103 | expect(packages.filter((p) => p.package_id === packageIds[0])).toBeDefined() 104 | 105 | }) 106 | 107 | test ("It should work to mark a package as delivered",async () => { 108 | await expect(zoho.package.markDelivered(testShipmentOrderIds[0], new Date())).resolves.not.toThrow() 109 | const testpackage = await zoho.package.get(packageIds[0]) 110 | 111 | expect(testpackage?.status).toBe("delivered") 112 | }) 113 | 114 | test ("It should fail correctly when marking a package a second time as delivered", async () => { 115 | 116 | await expect(zoho.package.markDelivered(testShipmentOrderIds[0], new Date())).rejects.toBeInstanceOf(ZohoApiError) 117 | }) 118 | 119 | test("It should work to create 3 packages for 3 salesorders with one API call", async () => { 120 | let x = 0 121 | const quickShipmentSalesOrderIds :string[] = [] 122 | while (x < 3) { 123 | const salesOrder = await zoho.salesOrder.create({ 124 | salesorder_number: ["TEST", randomInt(90000)].join("-"), 125 | customer_id: testUserId, 126 | line_items: [ 127 | { 128 | item_id: "116240000000203041", 129 | quantity: 5, 130 | }, 131 | ], 132 | }); 133 | quickShipmentSalesOrderIds.push(salesOrder.salesorder_id) 134 | testSalesOrders.push(salesOrder) 135 | x += 1 136 | } 137 | const inputArray :QuickCreateInput = quickShipmentSalesOrderIds.map((s, index) => { 138 | return { 139 | salesorder_id: s, 140 | tracking_number: `903952${index}`, 141 | carrier: "DPD" 142 | } 143 | }) 144 | 145 | await zoho.package.bulkCreateQuickShipment(inputArray); 146 | 147 | for (const s of quickShipmentSalesOrderIds) { 148 | const salesorder = await zoho.salesOrder.get(s) 149 | 150 | expect(salesorder.packages[0].tracking_number).toMatch(/903952/) 151 | 152 | testShipmentOrderIds.push(salesorder.packages[0].shipment_id) 153 | packageIds.push(salesorder.packages[0].package_id) 154 | 155 | } 156 | 157 | 158 | }, 10000) 159 | 160 | test("It should work to delete a shipmentorder", async () => { 161 | await zoho.package.deleteShipmentOrder(testShipmentOrderIds) 162 | }) 163 | test("It should work to delete a package", async () => { 164 | await zoho.package.delete(packageIds) 165 | }) 166 | afterAll(async () => { 167 | await zoho.salesOrder.delete(testSalesOrders.map((x) => x.salesorder_id)) 168 | await zoho.contact.delete([testUserId]); 169 | }) 170 | }); 171 | -------------------------------------------------------------------------------- /src/service/package.ts: -------------------------------------------------------------------------------- 1 | import { format } from "date-fns"; 2 | import { sleep } from "../util/retry"; 3 | import { ZohoApiClient } from "../client/client"; 4 | import { 5 | CreatePackage, 6 | CreatePackageRes, 7 | CreateShipment, 8 | CreateShipmentRes, 9 | Package, 10 | QuickCreateInput, 11 | } from "../types/package"; 12 | 13 | export class PackageHandler { 14 | private client: ZohoApiClient; 15 | 16 | constructor(client: ZohoApiClient) { 17 | this.client = client; 18 | } 19 | 20 | public async get(id: string): Promise { 21 | const res = await this.client.get<{ package: Package }>({ 22 | path: ["packages", id], 23 | }); 24 | 25 | return res.package; 26 | } 27 | 28 | /** 29 | * List package using different filters and sort Orders. Default Limit is 200, resulting in 1 API calls - using pagination automatically. 30 | * Limit the total result using the fields "createdDateStart" (GTE) or "createdDateEnd" (LTE) 31 | * @param opts 32 | * @returns 33 | */ 34 | public async list(opts: { 35 | sortColumn?: "date" | "created_time" | "last_modified_time" | "total"; 36 | sortOrder?: "ascending" | "descending"; 37 | limit?: number; 38 | 39 | /** 40 | * yyyy-mm-dd 41 | */ 42 | createdDateStart?: string; 43 | /** 44 | * yyyy-mm-dd 45 | */ 46 | createdDateEnd?: string; 47 | /** 48 | * Filter package by a specific Custom View ID 49 | */ 50 | customViewId?: string; 51 | }): Promise { 52 | const packages: Package[] = []; 53 | let hasMorePages = true; 54 | let page = 1; 55 | 56 | while (hasMorePages) { 57 | const res = await this.client.get<{ packages: Package[] }>({ 58 | path: ["packages"], 59 | params: { 60 | sort_column: opts.sortColumn ?? "date", 61 | sort_order: opts.sortOrder === "ascending" ? "A" : "D", 62 | per_page: opts.limit ?? "200", 63 | page, 64 | date_start: opts.createdDateStart || "", 65 | date_end: opts.createdDateEnd || "", 66 | customview_id: opts.customViewId || "", 67 | }, 68 | }); 69 | 70 | packages.push(...res.packages); 71 | if (!res.page_context) continue; 72 | hasMorePages = res.page_context?.has_more_page ?? false; 73 | if (opts.limit && packages.length >= opts.limit) hasMorePages = false; 74 | page = res.page_context.page + 1 ?? 0 + 1; 75 | } 76 | 77 | return packages; 78 | } 79 | 80 | /** 81 | * Creates a package for a specific salesorder. The shipment for it needs to be created afterwards with "createShipment" 82 | * @param createPackage 83 | * @param salesOrderId 84 | * @returns 85 | */ 86 | public async create( 87 | createPackage: CreatePackage, 88 | salesOrderId: string, 89 | ): Promise { 90 | const res = await this.client.post<{ package: CreatePackageRes }>({ 91 | path: ["packages"], 92 | params: { 93 | salesorder_id: salesOrderId, 94 | ignore_auto_number_generation: createPackage.package_number 95 | ? true 96 | : false, 97 | }, 98 | body: createPackage, 99 | }); 100 | 101 | return res.package; 102 | } 103 | 104 | /** 105 | * Create up to 25 packages with just one API call. This works only for fully shipped salesorders. Partial shipment is not working. 106 | * Takes an array of objects as input: { salesorder_id: string; tracking_number: string; carrier: string; }[]. Package and shipment Ids 107 | * are auto-created. We are sending chunks of 25 to Zoho. Unfortunately, we don't get the package or shipment ids back 108 | * @param input 109 | */ 110 | public async bulkCreateQuickShipment( 111 | input: QuickCreateInput, 112 | ): Promise { 113 | const chunkSize = 25; 114 | const chunks: QuickCreateInput[] = []; 115 | for (let i = 0; i < input.length; i += chunkSize) { 116 | chunks.push(input.slice(i, i + chunkSize)); 117 | } 118 | 119 | for (const chunk of chunks) { 120 | await this.client.post<{ data: [] }>({ 121 | path: ["salesorders", "quickcreate", "shipment"], 122 | body: { 123 | salesorders: chunk, 124 | }, 125 | }); 126 | 127 | await sleep(500); 128 | } 129 | } 130 | 131 | /** 132 | * Create a shipment for a package - ships out a package and adds information like the carrier and tracking number 133 | * @param createShipment 134 | * @param salesOrderId 135 | * @param packageId 136 | * @param liveTrackingEnabled 137 | * @returns 138 | */ 139 | public async createShipment( 140 | createShipment: CreateShipment, 141 | salesOrderId: string, 142 | packageId: string, 143 | liveTrackingEnabled?: boolean, 144 | ): Promise { 145 | const res = await this.client.post<{ 146 | shipmentorder: CreateShipmentRes; 147 | }>({ 148 | path: ["shipmentorders"], 149 | params: { 150 | salesorder_id: salesOrderId, 151 | package_ids: packageId, 152 | send_notification: false, 153 | is_tracking_required: liveTrackingEnabled || false, 154 | }, 155 | body: createShipment, 156 | }); 157 | 158 | return res.shipmentorder; 159 | } 160 | 161 | /** 162 | * Mark a package as delivered. If it is already delivered, you receive code 37135 163 | * @param shipmentOrderId 164 | * @param time 165 | * @returns 166 | */ 167 | public async markDelivered(shipmentOrderId: string, time: Date) { 168 | const res = await this.client.post<{ 169 | data: { 170 | statusupdate_error_list: []; 171 | }; 172 | }>({ 173 | path: ["shipmentorders", shipmentOrderId, "status", "delivered"], 174 | body: { 175 | delivered_date: format(time, "yyyy-MM-dd HH:mm"), 176 | }, 177 | }); 178 | 179 | if (res.data.statusupdate_error_list?.length === 0) return; 180 | 181 | throw new Error( 182 | res?.data?.statusupdate_error_list 183 | ? JSON.stringify(res.data.statusupdate_error_list) 184 | : `Error marking package as delivered! Undefined error: ${JSON.stringify( 185 | res, 186 | )}`, 187 | ); 188 | } 189 | 190 | /** 191 | * Delete one or several packages at once. Can be used for 192 | * unlimited amount of packages. Creates chunks of 25. You always need 193 | * to delete a corresponding shipment before the package can be deleted 194 | * @param ids 195 | * @returns 196 | */ 197 | public async delete(ids: string[]): Promise { 198 | if (ids.length === 0) { 199 | return; 200 | } 201 | 202 | if (ids.length === 1) { 203 | await this.client.delete({ 204 | path: ["packages", ids[0]], 205 | }); 206 | return; 207 | } 208 | 209 | const chunkSize = 25; 210 | const chunks: string[][] = []; 211 | for (let i = 0; i < ids.length; i += chunkSize) { 212 | chunks.push(ids.slice(i, i + chunkSize)); 213 | } 214 | for (const chunk of chunks) { 215 | await this.client.delete({ 216 | path: ["packages"], 217 | params: { 218 | package_ids: chunk.join(","), 219 | }, 220 | }); 221 | } 222 | } 223 | 224 | public async deleteShipmentOrder(ids: string[]): Promise { 225 | if (ids.length === 0) { 226 | return; 227 | } 228 | 229 | if (ids.length === 1) { 230 | await this.client.delete({ 231 | path: ["shipmentorders", ids[0]], 232 | }); 233 | return; 234 | } 235 | 236 | const chunkSize = 25; 237 | const chunks: string[][] = []; 238 | for (let i = 0; i < ids.length; i += chunkSize) { 239 | chunks.push(ids.slice(i, i + chunkSize)); 240 | } 241 | for (const chunk of chunks) { 242 | await this.client.delete({ 243 | path: ["shipmentorders"], 244 | params: { 245 | shipment_ids: chunk.join(","), 246 | }, 247 | }); 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/service/payment.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | import { format, subHours } from "date-fns"; 5 | dotenv.config({ path: "./.env" }); 6 | 7 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 8 | const clientId = process.env.ZOHO_CLIENT_ID as string; 9 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 10 | 11 | let zoho :Zoho 12 | 13 | describe("payment Tests", () => { 14 | 15 | beforeAll(async () => { 16 | const client = await ZohoApiClient.fromOAuth({ 17 | orgId, 18 | client: { 19 | id: clientId, 20 | secret: clientSecret, 21 | }, 22 | }); 23 | zoho = new Zoho(client); 24 | 25 | }) 26 | 27 | 28 | const paymentIds: string[] = []; 29 | let testUserId: string; 30 | let testInvoiceId: string; 31 | 32 | test("It should work to create a payment", async () => { 33 | const testUser = await zoho.contact.create({ contact_name: "Test Run User Zoho TS", customer_sub_type: "individual" }) 34 | testUserId = testUser.contact_id; 35 | const testInvoice = await zoho.invoice.create({ 36 | customer_id: testUserId, 37 | line_items: [ 38 | { 39 | item_id: "116240000000203041", 40 | quantity: 5, 41 | }, 42 | ], 43 | }) 44 | testInvoiceId = testInvoice.invoice_id; 45 | 46 | 47 | const paymentCreate = await zoho.payment.create({ 48 | amount: 1, 49 | customer_id: testUserId, 50 | payment_mode: "Banküberweisung", 51 | invoices: [{ invoice_id: testInvoice.invoice_id, amount_applied: 1}], 52 | date: format(new Date(), "yyyy-MM-dd") 53 | }); 54 | paymentIds.push(paymentCreate.payment_id); 55 | 56 | }); 57 | 58 | test("It should work to list all payments", async () => { 59 | const payments = await zoho.payment.list({ 60 | lastModifiedTime: subHours(new Date(), 1), 61 | }) 62 | 63 | expect(payments.length).toBeGreaterThan(0); 64 | expect(payments[0].payment_id).toBeDefined; 65 | expect(payments[0].invoice_numbers_array).toBeDefined 66 | }) 67 | 68 | test("It should work to delete a payment", async () => { 69 | await zoho.payment.delete(paymentIds) 70 | }) 71 | afterAll(async () => { 72 | await zoho.invoice.delete([testInvoiceId]) 73 | await zoho.contact.delete([testUserId]); 74 | 75 | }) 76 | }); 77 | -------------------------------------------------------------------------------- /src/service/payment.ts: -------------------------------------------------------------------------------- 1 | import { ZohoApiClient } from "../client/client"; 2 | import { sleep } from "../util/retry"; 3 | import { 4 | CreatePayment, 5 | CreatePaymentRes, 6 | ListPayment, 7 | Payment, 8 | } from "../types/payment"; 9 | import { lastModifiedDateFormat } from "../util/format"; 10 | export class PaymentHandler { 11 | private client: ZohoApiClient; 12 | 13 | constructor(client: ZohoApiClient) { 14 | this.client = client; 15 | } 16 | 17 | public async get(id: string): Promise { 18 | const res = await this.client.get<{ payment: Payment }>({ 19 | path: ["customerpayments", id], 20 | }); 21 | 22 | return res.payment; 23 | } 24 | 25 | /** 26 | * List payment using different filters and sort Orders. Default Limit is 200, resulting in 1 API calls - using pagination automatically. 27 | * @param opts 28 | * @returns 29 | */ 30 | public async list(opts: { 31 | sortColumn?: "date" | "created_time" | "last_modified_time" | "total"; 32 | sortOrder?: "ascending" | "descending"; 33 | /** 34 | * Filter for payments last modified after this date. 35 | */ 36 | lastModifiedTime?: Date; 37 | /** 38 | * yyyy-mm-dd - the date of the payment. Not the date it was created! 39 | */ 40 | dateStart?: string; 41 | /** 42 | * yyyy-mm-dd - the date of the payment. Not the date it was created! 43 | */ 44 | dateEnd?: string; 45 | }): Promise { 46 | const payments: ListPayment[] = []; 47 | let hasMorePages = true; 48 | let page = 1; 49 | 50 | while (hasMorePages) { 51 | const res = await this.client.get<{ 52 | customerpayments: ListPayment[]; 53 | }>({ 54 | path: ["customerpayments"], 55 | params: { 56 | sort_column: opts.sortColumn ?? "date", 57 | sort_order: opts.sortOrder === "ascending" ? "A" : "D", 58 | per_page: "200", 59 | page, 60 | date_start: opts.dateStart || "", 61 | date_end: opts.dateEnd || "", 62 | last_modified_time: opts.lastModifiedTime 63 | ? lastModifiedDateFormat(opts.lastModifiedTime) 64 | : "", 65 | }, 66 | }); 67 | 68 | payments.push(...res.customerpayments); 69 | if (!res.page_context) continue; 70 | hasMorePages = res.page_context?.has_more_page ?? false; 71 | page = res.page_context.page + 1 ?? 0 + 1; 72 | 73 | /** 74 | * Sleep to not get blocked by Zoho 75 | */ 76 | await sleep(1000); 77 | } 78 | 79 | const returnPayments = payments.map((payment) => { 80 | // Invoice Numbers Array is a helper array - we generate it here 81 | payment.invoice_numbers_array = payment.invoice_numbers.split(", "); 82 | return payment; 83 | }); 84 | 85 | return returnPayments; 86 | } 87 | 88 | public async create(payment: CreatePayment): Promise { 89 | const res = await this.client.post<{ payment: CreatePaymentRes }>({ 90 | path: ["customerpayments"], 91 | body: payment, 92 | }); 93 | 94 | return res.payment; 95 | } 96 | 97 | /** 98 | * Delete one or several customerpayments at once. Can be used for 99 | * unlimited amount of customerpayments. Creates chunks of 25 100 | * @param ids 101 | * @returns 102 | */ 103 | public async delete(ids: string[]): Promise { 104 | if (ids.length === 0) { 105 | return; 106 | } 107 | 108 | if (ids.length === 1) { 109 | await this.client.delete({ 110 | path: ["customerpayments", ids[0]], 111 | }); 112 | return; 113 | } 114 | 115 | const chunkSize = 25; 116 | const chunks: string[][] = []; 117 | for (let i = 0; i < ids.length; i += chunkSize) { 118 | chunks.push(ids.slice(i, i + chunkSize)); 119 | } 120 | for (const chunk of chunks) { 121 | await this.client.delete({ 122 | path: ["customerpayments"], 123 | params: { 124 | salesorder_ids: chunk.join(","), 125 | }, 126 | }); 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/service/salesOrder.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | import { randomInt } from "crypto"; 5 | 6 | dotenv.config({ path: "./.env" }); 7 | 8 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 9 | const clientId = process.env.ZOHO_CLIENT_ID as string; 10 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 11 | 12 | let zoho :Zoho 13 | let testUserId: string; 14 | 15 | describe("SalesOrder Tests", () => { 16 | beforeAll(async () => { 17 | 18 | const client = await ZohoApiClient.fromOAuth({ 19 | orgId, 20 | client: { 21 | id: clientId, 22 | secret: clientSecret, 23 | }, 24 | }); 25 | zoho = new Zoho(client); 26 | 27 | }) 28 | 29 | 30 | 31 | const salesOrderIds: string[] = []; 32 | 33 | test ("It should work to create a salesOrder", async () => { 34 | const testUser = await zoho.contact.create({ contact_name: "Test Run User Zoho TS", customer_sub_type: "individual" }) 35 | testUserId = testUser.contact_id; 36 | 37 | const salesOrder = await zoho.salesOrder.create({ 38 | salesorder_number: ["TEST", randomInt(90000)].join("-"), 39 | customer_id: testUser.contact_id, 40 | line_items: [ 41 | { 42 | item_id: "116240000000203041", 43 | quantity: 5, 44 | }, 45 | ], 46 | }); 47 | salesOrderIds.push(salesOrder.salesorder_id) 48 | expect(salesOrder.customer_id).toBe(testUser.contact_id); 49 | 50 | }) 51 | 52 | test("It should work to list all salesOrders", async () => { 53 | const list = await zoho.salesOrder.list({}); 54 | 55 | expect(list.length).toBeGreaterThan(0) 56 | 57 | }) 58 | 59 | test("It should work to set a custom Field Value", async () => { 60 | 61 | await zoho.salesOrder.setCustomFieldValue({ 62 | customFieldName: "cf_orderhash", 63 | salesOrderIds: [salesOrderIds[0]], 64 | value: "bcc", 65 | }); 66 | const result = await zoho.salesOrder.get(salesOrderIds[0]) 67 | expect(result.custom_fields.find((x) => x.api_name === "cf_orderhash")?.value).toBe("bcc"); 68 | expect(result.line_items[0].item_total_inclusive_of_tax).toBeGreaterThan(0); 69 | 70 | 71 | }) 72 | 73 | test("It should work to list salesorder sorted by last_update_date", async () => { 74 | const res = await zoho.salesOrder.list({ sortColumn: "last_modified_time", createdDateStart: "2022-01-01"}) 75 | expect(res.length).toBeGreaterThan(0); 76 | 77 | }) 78 | 79 | test("IT should work to delete a salesorder", async () => { 80 | await zoho.salesOrder.delete(salesOrderIds); 81 | 82 | }); 83 | 84 | afterAll(async () => { 85 | await zoho.contact.delete([testUserId]); 86 | 87 | }) 88 | 89 | 90 | }); -------------------------------------------------------------------------------- /src/service/salesOrder.ts: -------------------------------------------------------------------------------- 1 | import { sleep } from "../util/retry"; 2 | import { ZohoApiClient } from "../client/client"; 3 | import { 4 | SalesOrder, 5 | CreateSalesOrder, 6 | UpdateSalesOrder, 7 | ListSalesOrder, 8 | } from "../types/salesOrder"; 9 | import type { RequireOnlyOne } from "./util"; 10 | import { lastModifiedDateFormat } from "../util/format"; 11 | 12 | /** 13 | * The Handler class for all functionality concerning Zoho 14 | * SalesOrders 15 | */ 16 | export class SalesOrderHandler { 17 | private client: ZohoApiClient; 18 | 19 | constructor(client: ZohoApiClient) { 20 | this.client = client; 21 | } 22 | 23 | public async create(salesOrder: CreateSalesOrder): Promise { 24 | const res = await this.client.post<{ salesorder: SalesOrder }>({ 25 | path: ["salesorders"], 26 | body: salesOrder, 27 | params: { 28 | ignore_auto_number_generation: salesOrder.salesorder_number 29 | ? true 30 | : false, 31 | }, 32 | }); 33 | 34 | return res.salesorder; 35 | } 36 | 37 | /** 38 | * List SalesOrder using different filters and sort Orders. Default Limit is 200, resulting in 1 API calls - using pagination automatically. 39 | * Limit the total result using the fields "createdDateStart" (GTE) or "createdDateEnd" (LTE) 40 | * @param opts 41 | * @returns 42 | */ 43 | public async list(opts: { 44 | sortColumn?: "date" | "created_time" | "last_modified_time" | "total"; 45 | sortOrder?: "ascending" | "descending"; 46 | /** 47 | * Filter for salesorders last modified after this date. 48 | */ 49 | lastModifiedTime?: Date; 50 | limit?: number; 51 | /** 52 | * yyyy-mm-dd 53 | */ 54 | createdDateStart?: string; 55 | /** 56 | * yyyy-mm-dd 57 | */ 58 | createdDateEnd?: string; 59 | /** 60 | * Filter Salesorder by a specific Custom View ID 61 | */ 62 | customViewId?: string; 63 | }): Promise { 64 | const salesOrders: ListSalesOrder[] = []; 65 | let hasMorePages = true; 66 | let page = 1; 67 | 68 | while (hasMorePages) { 69 | const res = await this.client.get<{ 70 | salesorders: ListSalesOrder[]; 71 | }>({ 72 | path: ["salesorders"], 73 | params: { 74 | sort_column: opts.sortColumn ?? "date", 75 | sort_order: opts.sortOrder === "ascending" ? "A" : "D", 76 | per_page: "200", 77 | page, 78 | created_date_start: opts.createdDateStart || "", 79 | created_date_end: opts.createdDateEnd || "", 80 | customview_id: opts.customViewId || "", 81 | last_modified_time: opts.lastModifiedTime 82 | ? lastModifiedDateFormat(opts.lastModifiedTime) 83 | : "", 84 | }, 85 | }); 86 | 87 | salesOrders.push(...res.salesorders); 88 | if (!res.page_context) continue; 89 | hasMorePages = res.page_context?.has_more_page ?? false; 90 | page = res.page_context.page + 1 ?? 0 + 1; 91 | /** 92 | * Sleep to not get blocked by Zoho 93 | */ 94 | await sleep(1000); 95 | } 96 | 97 | return salesOrders; 98 | } 99 | 100 | public async update(salesOrder: UpdateSalesOrder): Promise { 101 | const res = await this.client.put<{ salesorder: SalesOrder }>({ 102 | path: ["salesorders", salesOrder.salesorder_id.toString()], 103 | body: salesOrder, 104 | }); 105 | 106 | return res.salesorder; 107 | } 108 | 109 | /** 110 | * Get a single salesorder by ID. 111 | * @param id 112 | * @returns 113 | */ 114 | public async get(id: string): Promise { 115 | const res = await this.client.get<{ salesorder: SalesOrder }>({ 116 | path: ["salesorders", id], 117 | headers: { 118 | "X-ZB-SOURCE": "zbclient", 119 | }, 120 | }); 121 | 122 | return res.salesorder; 123 | } 124 | 125 | /** 126 | * Delete one or several sales orders at once. Can be used for 127 | * unlimited amount of sales orders. Creates chunks of 25 128 | * @param ids 129 | * @returns 130 | */ 131 | public async delete(ids: string[]): Promise { 132 | if (ids.length === 0) { 133 | return; 134 | } 135 | 136 | if (ids.length === 1) { 137 | await this.client.delete({ 138 | path: ["salesorders", ids[0]], 139 | }); 140 | return; 141 | } 142 | 143 | const chunkSize = 25; 144 | const chunks: string[][] = []; 145 | for (let i = 0; i < ids.length; i += chunkSize) { 146 | chunks.push(ids.slice(i, i + chunkSize)); 147 | } 148 | for (const chunk of chunks) { 149 | await this.client.delete({ 150 | path: ["salesorders"], 151 | params: { 152 | salesorder_ids: chunk.join(","), 153 | }, 154 | }); 155 | } 156 | } 157 | 158 | /** 159 | * Confirm one ore many salesorders at once. Can be used for unlimited amount of SalesOrders. Creates chunks of 25. 160 | * @param ids 161 | */ 162 | public async confirm(ids: string[]): Promise { 163 | const chunkSize = 25; 164 | const chunks: string[][] = []; 165 | for (let i = 0; i < ids.length; i += chunkSize) { 166 | chunks.push(ids.slice(i, i + chunkSize)); 167 | } 168 | 169 | for (const chunk of chunks) { 170 | await this.client.post<{ salesorder: SalesOrder }>({ 171 | path: ["salesorders", "status", "confirmed"], 172 | headers: { 173 | "Content-Type": 174 | "application/x-www-form-urlencoded; charset=UTF-8", 175 | }, 176 | body: `salesorder_ids=${encodeURIComponent(chunk.join(","))}`, 177 | }); 178 | } 179 | } 180 | 181 | public async markVoid(ids: string[]): Promise { 182 | const chunkSize = 25; 183 | const chunks: string[][] = []; 184 | for (let i = 0; i < ids.length; i += chunkSize) { 185 | chunks.push(ids.slice(i, i + chunkSize)); 186 | } 187 | 188 | for (const chunk of chunks) { 189 | await this.client.post<{ salesorder: SalesOrder }>({ 190 | path: ["salesorders", "status", "void"], 191 | body: { 192 | salesorder_ids: chunk.join(","), 193 | }, 194 | }); 195 | } 196 | } 197 | 198 | /** 199 | * Set custom field values of one or many sales orders. Use the API_Name of the custom field in the Zoho settings 200 | * e.g. "cf_custom_field" 201 | * @param opts 202 | */ 203 | public async setCustomFieldValue( 204 | opts: RequireOnlyOne< 205 | { 206 | customFieldId?: never; 207 | customFieldName?: string; 208 | 209 | salesOrderIds: string[]; 210 | value: number | string | boolean; 211 | }, 212 | "customFieldId" | "customFieldName" 213 | >, 214 | ): Promise { 215 | await this.client.put<{ salesorder: SalesOrder }>({ 216 | path: ["salesorders"], 217 | headers: { 218 | "Content-Type": 219 | "application/x-www-form-urlencoded; charset=UTF-8", 220 | }, 221 | body: `bulk_update=true&JSONString=${JSON.stringify({ 222 | custom_fields: [ 223 | { 224 | [opts.customFieldId ? "customfield_id" : "api_name"]: 225 | opts.customFieldId ?? opts.customFieldName, 226 | value: opts.value, 227 | }, 228 | ], 229 | salesorder_id: opts.salesOrderIds.join(","), 230 | })}`, 231 | }); 232 | } 233 | 234 | /** 235 | * Search for a salesOrder number containing the search fragment 236 | * @param fragment 237 | * @returns 238 | */ 239 | public async search(fragment: string): Promise { 240 | const salesOrders: SalesOrder[] = []; 241 | let hasMorePages = true; 242 | let page = 1; 243 | 244 | while (hasMorePages) { 245 | const res = await this.client.get<{ salesorders: SalesOrder[] }>({ 246 | path: ["salesorders"], 247 | params: { 248 | salesorder_number_contains: fragment, 249 | page, 250 | }, 251 | }); 252 | 253 | salesOrders.push(...res.salesorders); 254 | hasMorePages = res.page_context?.has_more_page ?? false; 255 | page = res.page_context?.page ?? 0 + 1; 256 | } 257 | return salesOrders; 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /src/service/tax.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | 5 | dotenv.config({ path: "./.env" }); 6 | 7 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 8 | const clientId = process.env.ZOHO_CLIENT_ID as string; 9 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 10 | 11 | let zoho :Zoho 12 | 13 | 14 | beforeAll(async () => { 15 | 16 | const client = await ZohoApiClient.fromOAuth({ 17 | orgId, 18 | client: { 19 | id: clientId, 20 | secret: clientSecret, 21 | }, 22 | }); 23 | zoho = new Zoho(client); 24 | 25 | }) 26 | 27 | test("It should work to list all Taxes", async () => { 28 | const res = await zoho.tax.list(); 29 | 30 | expect(res.length).toBeGreaterThan(0); 31 | expect(res[0].tax_id).toBeDefined(); 32 | 33 | }); -------------------------------------------------------------------------------- /src/service/tax.ts: -------------------------------------------------------------------------------- 1 | import { ZohoApiClient } from "../client/client"; 2 | import { Tax } from "../types/tax"; 3 | 4 | export class TaxHandler { 5 | private client: ZohoApiClient; 6 | 7 | constructor(client: ZohoApiClient) { 8 | this.client = client; 9 | } 10 | 11 | /** 12 | * List all current active taxes 13 | * @returns 14 | */ 15 | public async list(): Promise { 16 | const res = await this.client.get<{ taxes: Tax[] }>({ 17 | path: ["settings", "taxes"], 18 | }); 19 | 20 | return res.taxes; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/service/util.test.ts: -------------------------------------------------------------------------------- 1 | import { Zoho } from "." 2 | import { ZohoApiClient } from "../client/client" 3 | 4 | test("String replace should work", () => { 5 | 6 | const client = undefined as unknown as ZohoApiClient 7 | const zoho = new Zoho(client) 8 | 9 | expect(zoho.util.getUnprefixedNumber("STORE-224")).toBe("224") 10 | expect(zoho.util.getUnprefixedNumber("BULK-224-55")).toBe("224-55") 11 | 12 | }) -------------------------------------------------------------------------------- /src/service/util.ts: -------------------------------------------------------------------------------- 1 | export type RequireOnlyOne = Pick< 2 | T, 3 | Exclude 4 | > & 5 | { 6 | [K in Keys]-?: Required> & 7 | Partial, undefined>>; 8 | }[Keys]; 9 | 10 | /** 11 | * A util class for comfort features like "un-prefixing" order / invoice etc. 12 | * numbers 13 | */ 14 | export class Utils { 15 | /** 16 | * Takes a prefixed number like INV-24945 or STORE-234355 and 17 | * returnes the unprefixed number 18 | * @param incomingNumer 19 | * @returns 20 | */ 21 | public getUnprefixedNumber(incomingNumer: string) { 22 | return incomingNumer.replace(/^([A-Za-z])+-/, ""); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/service/warehouse.test.ts: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | import { Zoho } from "."; 3 | import { ZohoApiClient } from "../client/client"; 4 | 5 | dotenv.config({ path: "./.env" }); 6 | 7 | const orgId = process.env.ZOHO_ORGANIZATION_ID as string; 8 | const clientId = process.env.ZOHO_CLIENT_ID as string; 9 | const clientSecret = process.env.ZOHO_CLIENT_SECRET as string; 10 | 11 | let zoho :Zoho 12 | let warehouseId: string; 13 | 14 | 15 | beforeAll(async () => { 16 | 17 | const client = await ZohoApiClient.fromOAuth({ 18 | orgId, 19 | client: { 20 | id: clientId, 21 | secret: clientSecret, 22 | }, 23 | }); 24 | zoho = new Zoho(client); 25 | 26 | }) 27 | 28 | test("It should work to list all Warehouses", async () => { 29 | const res = await zoho.warehouse.list(); 30 | 31 | expect(res.length).toBeGreaterThan(0); 32 | warehouseId = res[0].warehouse_id 33 | 34 | }); 35 | 36 | test("It should work to get one warehouse", async () => { 37 | const res = await zoho.warehouse.get(warehouseId) 38 | expect(res.warehouse_id).toBeDefined; 39 | }) -------------------------------------------------------------------------------- /src/service/warehouse.ts: -------------------------------------------------------------------------------- 1 | import { Warehouse } from "../types/warehouse"; 2 | import { ZohoApiClient } from "../client/client"; 3 | 4 | export class WarehouseHandler { 5 | private client: ZohoApiClient; 6 | 7 | constructor(client: ZohoApiClient) { 8 | this.client = client; 9 | } 10 | 11 | public async get(id: string): Promise { 12 | const res = await this.client.get<{ warehouse: Warehouse }>({ 13 | path: ["settings", "warehouses", id], 14 | }); 15 | 16 | if (!res.warehouse) { 17 | throw new Error(`warehouse with id: ${id} was not found`); 18 | } 19 | return res.warehouse; 20 | } 21 | 22 | public async list(): Promise { 23 | const res = await this.client.get<{ warehouses: Warehouse[] }>({ 24 | path: ["settings", "warehouses"], 25 | }); 26 | 27 | return res.warehouses; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/types/address.ts: -------------------------------------------------------------------------------- 1 | export type Address = { 2 | /** 3 | * Unique id for this address 4 | */ 5 | address_id: string; 6 | 7 | /** 8 | * Intended recipient at given address 9 | */ 10 | attention: string; 11 | 12 | /** 13 | * Name of the street of the customer’s shipping address. 14 | */ 15 | address: string; 16 | 17 | /** 18 | * Name of the city of the customer’s shipping address. 19 | */ 20 | city: string; 21 | 22 | /** 23 | * Name of the state of the customer's shipping address. 24 | */ 25 | state: string; 26 | 27 | /** 28 | * Zip code of the customer’s shipping address. 29 | */ 30 | zip: string; 31 | 32 | /** 33 | * Name of the country of the customer’s address. 34 | * Is the translated country name - for example "Deutschland". 35 | * We can't use the country_code for address create unfortunately 36 | */ 37 | country: string; 38 | 39 | /** 40 | * The ISO country code in capital letters: DE, EN, etc.. 41 | * Is not always returned 42 | */ 43 | country_code: string; 44 | 45 | state_code: string; 46 | 47 | /** 48 | * Fax number of the customer’s shipping address. 49 | */ 50 | fax: string; 51 | 52 | phone: string; 53 | 54 | /** 55 | * Additional Street address of the contact. Maximum length allowed [255] 56 | */ 57 | street2: string; 58 | }; 59 | 60 | export type CreateAddress = Partial< 61 | Omit 62 | > & { 63 | update_existing_transactions_address?: boolean; 64 | }; 65 | export type AddressWithoutAddressId = Omit; 66 | -------------------------------------------------------------------------------- /src/types/bankaccount.ts: -------------------------------------------------------------------------------- 1 | export type Bankaccount = { 2 | account_id: string; 3 | account_name: string; 4 | account_code: string; 5 | currency_id: string; 6 | currency_code: string; 7 | account_type: string; 8 | account_number: string; 9 | uncategorized_transactions: 0; 10 | total_unprinted_checks: 0; 11 | is_active: true; 12 | balance: number; 13 | bank_balance: number; 14 | bcy_balance: number; 15 | bank_name: string; 16 | routing_number: string; 17 | is_primary_account: false; 18 | is_paypal_account: false; 19 | feeds_last_refresh_date: string; 20 | is_direct_paypal: false; 21 | partner_bank_source_formatted: string; 22 | partner_bank_source: string; 23 | is_beta_feed: false; 24 | consent_info: { 25 | consent_remaining_days: string; 26 | is_consent_expired: string; 27 | }; 28 | feed_status: string; 29 | }; 30 | 31 | export type ListBankaccount = Pick< 32 | Bankaccount, 33 | | "account_code" 34 | | "account_id" 35 | | "account_name" 36 | | "account_type" 37 | | "balance" 38 | | "bank_name" 39 | | "bcy_balance" 40 | | "currency_code" 41 | | "feed_status" 42 | | "is_active" 43 | | "uncategorized_transactions" 44 | >; 45 | -------------------------------------------------------------------------------- /src/types/contact.ts: -------------------------------------------------------------------------------- 1 | import { Address, CustomField } from "."; 2 | import { CreateAddress } from "./address"; 3 | import { ContactPersonFromContactGet } from "./contactPerson"; 4 | 5 | export type Contact = { 6 | /** 7 | * Unique id for this contact. 8 | */ 9 | contact_id: string; 10 | 11 | /** 12 | * Name of the contact. This can be the name of an organisation or the name of an individual. Maximum length [200] 13 | */ 14 | contact_name: string; 15 | 16 | /** 17 | * Name of the conact's company. Maximum length [200] 18 | */ 19 | company_name: string; 20 | 21 | /** 22 | * First name of the contact. Maximum length [100] 23 | */ 24 | first_name: string; 25 | 26 | /** 27 | * Last name of the contact. Maximum length [100] 28 | */ 29 | last_name: string; 30 | 31 | /** 32 | * Search contacts by email id of the contact person. Variants: address_startswith and address_contains 33 | */ 34 | email: string; 35 | 36 | /** 37 | * Contact persons related to this contact. Use this to update the first and last name of the "main" contact person of a contact 38 | */ 39 | contact_persons: Partial<{ 40 | salutation: string; 41 | first_name: string; 42 | last_name: string; 43 | email: string; 44 | is_primary_contact: boolean; 45 | }>[]; 46 | 47 | /** 48 | * Search contacts by phone number of the contact person. Variants: phone_startswith and phone_contains 49 | */ 50 | phone: string; 51 | 52 | /** 53 | * Facebook profile account of the contact. Maximum length [100] 54 | */ 55 | facebook: string; 56 | 57 | /** 58 | * Twitter account of the contact. MAximum length [100] 59 | */ 60 | twitter: string; 61 | 62 | /** 63 | * language of a contact 64 | */ 65 | language_code: 66 | | "de" 67 | | "en" 68 | | "es" 69 | | "fr" 70 | | "it" 71 | | "ja" 72 | | "nl" 73 | | "pt" 74 | | "sv" 75 | | "zh"; 76 | 77 | /** 78 | * Billing address of the contact. 79 | */ 80 | billing_address: Address; 81 | 82 | /** 83 | * Customer's shipping address to which the goods must be delivered. 84 | */ 85 | shipping_address: Address; 86 | 87 | /** 88 | * Location of the contact. (This node identifies the place of supply 89 | * and source of supply when invoices/bills are raised for the 90 | * customer/vendor respectively. This is not applicable for Overseas contacts) 91 | * India Edition only. 92 | */ 93 | place_of_contact: string; 94 | 95 | /** 96 | * Name of the Tax Authority 97 | */ 98 | tax_authority_name: string; 99 | 100 | /** 101 | * Enter tax exemption code 102 | * US, Canada, Australia and India editions only 103 | */ 104 | tax_exemption_code: string; 105 | 106 | /** 107 | * Addresses related to this contact. Not the main billing and shipping address - 108 | * get thos with billing_address and shipping_address 109 | */ 110 | addresses: Address[] | []; 111 | 112 | /** 113 | * Customer or vendor / this is Zoho specific, as contacts can be vendors or customer 114 | */ 115 | contact_type: "customer" | "vendor"; 116 | 117 | /** 118 | * Is this contact a business or an individual person 119 | */ 120 | customer_sub_type: "business" | "individual"; 121 | 122 | /** 123 | * Contact can be disabled, for example when merged with 124 | * a different contact 125 | */ 126 | status: "active" | "inactive"; 127 | 128 | last_modified_time: string; 129 | 130 | created_time: string; 131 | }; 132 | 133 | export type CreateContact = 134 | /** 135 | * Required fields 136 | */ 137 | Omit< 138 | Pick & 139 | /** 140 | * Optional fields 141 | */ 142 | Partial< 143 | Omit< 144 | Contact, 145 | | "created_time" 146 | | "last_modified_time" 147 | | "billing_address" 148 | | "shipping_address" 149 | > 150 | >, 151 | | "first_name" 152 | | "last_name" 153 | | "email" 154 | | "billing_address" 155 | | "shipping_address" 156 | > & { 157 | billing_address?: CreateAddress; 158 | shipping_address?: CreateAddress; 159 | custom_fields?: CustomField[]; 160 | }; 161 | 162 | export type UpdateContact = 163 | /** 164 | * Required fields 165 | */ 166 | Pick & 167 | /** 168 | * Optional fields 169 | */ 170 | Partial> & { 171 | custom_fields?: CustomField[]; 172 | }; 173 | 174 | export interface GetContact extends Contact { 175 | contact_persons: ContactPersonFromContactGet[]; 176 | } 177 | -------------------------------------------------------------------------------- /src/types/contactPerson.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * List of contact persons details. 3 | */ 4 | export type ContactPerson = { 5 | /** 6 | * Unique ID generated by the server for the contact person 7 | */ 8 | contact_person_id: string; 9 | 10 | contact_id: string; 11 | salutation: string; 12 | first_name: string; 13 | last_name: string; 14 | email: string; 15 | phone: string; 16 | mobile: string; 17 | is_primary_contact: boolean; 18 | skype: string; 19 | designation: string; 20 | department: string; 21 | is_added_in_portal: boolean; 22 | enable_portal: boolean; 23 | created_time: string; 24 | updated_time: string; 25 | }; 26 | 27 | export type ContactPersonWithoutContact = Omit; 28 | export type ContactPersonFromContactGet = Omit< 29 | ContactPerson, 30 | "contact_id" | "created_time" | "updated_time" 31 | >; 32 | 33 | export type ContactPersonShortList = Pick< 34 | ContactPerson, 35 | | "phone" 36 | | "mobile" 37 | | "last_name" 38 | | "first_name" 39 | | "email" 40 | | "contact_person_id" 41 | >; 42 | 43 | export type CreateContactPerson = 44 | /** 45 | * Required fields 46 | */ 47 | Omit< 48 | Pick & 49 | /** 50 | * Optional fields 51 | */ 52 | Partial< 53 | Omit< 54 | ContactPerson, 55 | "contact_person_id" | "created_time" | "updated_time" 56 | > 57 | >, 58 | "is_added_in_portal" 59 | >; 60 | -------------------------------------------------------------------------------- /src/types/customField.ts: -------------------------------------------------------------------------------- 1 | export type CustomField = { 2 | customfield_id?: string; 3 | 4 | /** 5 | * Seems to be always the same than customfield_id 6 | */ 7 | field_id?: string; 8 | 9 | /** 10 | * Index of the custom field 11 | */ 12 | index?: unknown; //TODO: Figure out type 13 | 14 | /** 15 | * Label of the Custom Field 16 | */ 17 | label?: string; 18 | 19 | /** 20 | * Value of the Custom Field 21 | */ 22 | value?: string | number | boolean; 23 | 24 | /** 25 | * Optionally reference this field by its api name 26 | * The API name can be found in the Zoho settings page when creating 27 | * a new custom field. It is way more comfortable using this field 28 | */ 29 | api_name?: string; 30 | 31 | show_in_portal?: boolean; 32 | 33 | /** 34 | * Additional fields that Zoho adds from time to time 35 | */ 36 | [key: string]: unknown; 37 | }; 38 | -------------------------------------------------------------------------------- /src/types/document.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Sales order can have files attached to them 3 | */ 4 | export type Document = { 5 | /** 6 | * Checks whether the sales order can be sent as a mail or not. 7 | */ 8 | can_send_in_mail: boolean; 9 | 10 | /** 11 | * This indicates the name of the file. 12 | */ 13 | file_name: string; 14 | 15 | /** 16 | * This indicates the type of the file. 17 | */ 18 | file_type: string; 19 | 20 | /** 21 | * This indicates the size of the formatted file. 22 | */ 23 | file_size_formatted: string; 24 | 25 | /** 26 | * This indicates the chronological number of the attachment. 27 | */ 28 | attachment_order: number; 29 | 30 | /** 31 | * Unique ID generated by the server for the document. This is used as an identifier. 32 | */ 33 | document_id: string; 34 | 35 | /** 36 | * this indicates the size of the attached file. 37 | */ 38 | file_size: number; 39 | }; 40 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | export type { Address, AddressWithoutAddressId } from "./address"; 2 | export type { 3 | ContactPerson, 4 | ContactPersonShortList, 5 | ContactPersonFromContactGet, 6 | } from "./contactPerson"; 7 | export type { Document } from "./document"; 8 | export type { LineItem } from "./lineItem"; 9 | export type { Package } from "./package"; 10 | export type { Invoice } from "./invoice"; 11 | export type { Tax } from "./tax"; 12 | export type { 13 | SalesOrder, 14 | CreateSalesOrder, 15 | UpdateSalesOrder, 16 | } from "./salesOrder"; 17 | export type { CustomField } from "./customField"; 18 | export type { Contact, CreateContact, UpdateContact } from "./contact"; 19 | export type { Item, FullCompositeItem } from "./item"; 20 | export type { Payment, CreatePayment } from "./payment"; 21 | export type { ListBankaccount } from "./bankaccount"; 22 | -------------------------------------------------------------------------------- /src/types/invoice.ts: -------------------------------------------------------------------------------- 1 | import { AddressWithoutAddressId } from "./address"; 2 | import { ContactPerson } from "./contactPerson"; 3 | import { CustomField } from "./customField"; 4 | import { LineItem } from "./lineItem"; 5 | 6 | export type CreateInvoice = 7 | /** 8 | * Required fields 9 | */ 10 | Pick & 11 | /** 12 | * Optional fields 13 | */ 14 | Partial< 15 | Pick< 16 | Invoice, 17 | | "contact_persons" 18 | | "date" 19 | | "discount_type" 20 | | "discount" 21 | | "is_discount_before_tax" 22 | | "notes" 23 | | "pricebook_id" 24 | | "reference_number" 25 | | "salesperson_name" 26 | | "shipping_charge_tax_id" 27 | | "shipping_charge" 28 | > 29 | > & /** 30 | * Additional fields 31 | */ { 32 | line_items: (Pick & 33 | Partial)[]; 34 | /** 35 | * Unique ID generated for the customer. This is used as an identifier. 36 | */ 37 | customer_id: string; 38 | 39 | custom_fields?: CustomField[]; 40 | 41 | /** 42 | * The invoice number will be auto-generated in most cases (e.g. INV-00494569) 43 | */ 44 | invoice_number?: string; 45 | 46 | /** 47 | * Reference number of the Invoice. The sales order number should be used as the reference_number if you want Zoho to "connect" 48 | * invoices with Sales Orders 49 | */ 50 | reference_number?: string; 51 | 52 | /** 53 | * Used to specify whether the line item rates are inclusive or exclusive of 54 | * tax. 55 | */ 56 | is_inclusive_tax?: boolean; 57 | 58 | /** 59 | * Exchange rate of the currency, with respect to the base currency. 60 | */ 61 | exchange_rate?: number; 62 | 63 | /** 64 | * Unique Id generated by the server for address in contacts page. To add a 65 | * billing address to invoice, send the address_id using this node. 66 | * Else, the default billing address for that contact is used 67 | */ 68 | billing_address_id?: string; 69 | 70 | /** 71 | * Unique Id generated by the server for address in contacts page. To add a 72 | * shipping address to invoice, send the address_id using this node. Else, 73 | * the default shipping address for that contact is used 74 | */ 75 | shipping_address_id?: string; 76 | }; 77 | 78 | /** 79 | * Invoices created 80 | */ 81 | export type Invoice = { 82 | /** 83 | * Unique ID generated by the server for the invoice. This is used as an identifier. 84 | */ 85 | invoice_id: string; 86 | 87 | /** 88 | * The number of the Invoice. 89 | */ 90 | invoice_number: string; 91 | 92 | /** 93 | * Used to specify whether the line item rates are inclusive or exclusive of 94 | * tax. 95 | */ 96 | is_inclusive_tax: boolean; 97 | 98 | /** 99 | * The current status of the Invoice. 100 | */ 101 | status: string; 102 | 103 | /** 104 | * The date for the Invoice. 105 | * ISO 8601 format - YYYY-MM-DDThh:mm:ssTZD 106 | */ 107 | date: string; 108 | 109 | /** 110 | * Due date for the Invoice. 111 | * ISO 8601 format - YYYY-MM-DDThh:mm:ssTZD 112 | */ 113 | due_date: string; 114 | 115 | /** 116 | * Reference number of the Invoice. The sales order number should be used as the reference_number if you want Zoho to "connect" 117 | * invoices with Sales Orders 118 | */ 119 | reference_number: string; 120 | 121 | /** 122 | * Total amount of the Invoice. 123 | */ 124 | total: number; 125 | 126 | /** 127 | * Unique ID generated for the customer. This is used as an identifier. 128 | */ 129 | customer_id: string; 130 | 131 | /** 132 | * Unique ID generated by the server for the sales person. This is used as an identifier. 133 | */ 134 | salesperson_id: number; 135 | 136 | /** 137 | * Name of the Sales Person. 138 | */ 139 | salesperson_name: string; 140 | 141 | contact_persons: string[] | []; 142 | 143 | /** 144 | * List of contact persons details. 145 | */ 146 | contact_persons_details: ContactPerson[]; 147 | 148 | /** 149 | * Only visible in Invoice List 150 | */ 151 | customer_name: string; 152 | 153 | /** 154 | * The related company name. Only visible in Invoice List 155 | */ 156 | company_name: string; 157 | 158 | /** 159 | * The email address of the related main contact. Only visible in invoice list 160 | */ 161 | email?: string; 162 | 163 | /** 164 | * For example EUR 165 | */ 166 | currency_code: string; 167 | 168 | billing_address?: AddressWithoutAddressId; 169 | shipping_address?: AddressWithoutAddressId; 170 | 171 | country?: string; 172 | 173 | /** 174 | * Balance due for the invoice. 175 | */ 176 | balance: number; 177 | 178 | /** 179 | * Discount to be applied on the Sales Order. 180 | */ 181 | discount_amount: number; 182 | 183 | /** 184 | * The percentage of Discount applied. 185 | */ 186 | discount: string; 187 | 188 | /** 189 | * Used to check whether the discount is applied before tax or after tax. 190 | */ 191 | is_discount_before_tax: boolean; 192 | 193 | /** 194 | * Type of discount. Allowed values are entity_level,item_level. For 195 | * entity_level type, discount is applied at entity level and the node 196 | * discount resides outside the line_items node.For item_level type, 197 | * discount is applied at item level and the node discount resides inside 198 | * each line_item under the line_items node 199 | */ 200 | discount_type: "entity_level" | "item_level"; 201 | 202 | /** 203 | * Notes for the Sales Order. 204 | */ 205 | notes: string; 206 | 207 | /** 208 | * Unique ID generated by the server for the Pricebook. This is used as an identifier. 209 | */ 210 | pricebook_id: number; 211 | 212 | /** 213 | * Id of the shipping tax 214 | * 215 | * Not documented 216 | */ 217 | shipping_charge_tax_id: string; 218 | 219 | /** 220 | * Shipping charge tax rate in percent. 221 | * 222 | * Not officially documented 223 | */ 224 | shipping_charge_tax_percentage: number; 225 | 226 | /** 227 | * Shipping charges that can be applied to the invoice. 228 | */ 229 | shipping_charge: number; 230 | 231 | /** 232 | * Time at which the Sales Order was created. 233 | */ 234 | created_time: string; 235 | 236 | /** 237 | * Time at which the sales order details were last modified. 238 | */ 239 | last_modified_time: string; 240 | }; 241 | 242 | /** 243 | * Custom fields that always start with "cf_" 244 | */ 245 | type CustomFieldsDirectAPIResponse = { [key: string]: unknown }; 246 | 247 | export type ListInvoice = Pick< 248 | Invoice, 249 | | "invoice_id" 250 | | "customer_name" 251 | | "customer_id" 252 | | "company_name" 253 | | "status" 254 | | "invoice_number" 255 | | "reference_number" 256 | | "date" 257 | | "due_date" 258 | | "email" 259 | | "currency_code" 260 | | "billing_address" 261 | | "shipping_address" 262 | | "country" 263 | | "created_time" 264 | | "last_modified_time" 265 | | "total" 266 | > & 267 | CustomFieldsDirectAPIResponse; 268 | -------------------------------------------------------------------------------- /src/types/item.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Zoho gives us warehouse stock information for an item 3 | */ 4 | export type WarehouseStock = { 5 | warehouse_id: string; 6 | warehouse_name: string; 7 | status: "active" | "inactive"; 8 | is_primary: boolean; 9 | warehouse_stock_on_hand: number; 10 | initial_stock: number; 11 | initial_stock_rate: number; 12 | warehouse_available_stock: number; 13 | warehouse_actual_available_stock: number; 14 | warehouse_committed_stock: number; 15 | warehouse_actual_committed_stock: number; 16 | warehouse_available_for_sale_stock: number; 17 | warehouse_actual_available_for_sale_stock: number; 18 | batches: []; 19 | is_fba_warehouse: false; 20 | sales_channels: []; 21 | }; 22 | 23 | type PackageDetails = { 24 | dimension_unit: "cm"; 25 | height: string; 26 | length: string; 27 | weight: number; 28 | weight_unit: "kg" | "g" | "lb" | "oz"; 29 | width: string; 30 | }; 31 | 32 | export type Item = { 33 | /** 34 | * Unique ID generated by the server for the group to which the item belongs, if any. This is used as an identifier. 35 | */ 36 | group_id?: string; 37 | 38 | /** 39 | * Name of product group -> Group Name is the actual "product name". name is the variant name 40 | */ 41 | group_name?: string; 42 | 43 | /** 44 | * Unit of measurement for the item. For example "Stück" 45 | */ 46 | unit: string; 47 | 48 | /** 49 | * Item type can be inventory, sales, purchases or sales_and_purchases. If item is associated with a group, then type should be inventory. 50 | */ 51 | item_type: string; 52 | /** 53 | * Type of the product. It can be goods or service 54 | */ 55 | product_type: string; 56 | 57 | /** 58 | * Boolean to track the taxability of the item. 59 | */ 60 | is_taxable: boolean; 61 | 62 | /** 63 | * Unique ID generated by the server for the tax associated with the item. This is used a unique identifier. 64 | */ 65 | tax_id: string; 66 | 67 | /** 68 | * Description of the Item. 69 | */ 70 | description: string; 71 | 72 | is_combo_product: boolean; 73 | 74 | /** 75 | * Name of the tax applied on the Item Group. 76 | */ 77 | tax_name: string; 78 | 79 | /** 80 | * Percentage of the Tax 81 | */ 82 | tax_percentage: number; 83 | 84 | brand: string; 85 | 86 | manufacturer: string; 87 | 88 | /** 89 | * Type of the Tax. 90 | */ 91 | tax_type: string; 92 | 93 | /*+ 94 | * Unique ID generated by the server for the Purchase account. 95 | */ 96 | purchase_account_id: number; 97 | 98 | /** 99 | * Name of the Purchase Account 100 | */ 101 | purchase_account_name: string; 102 | 103 | /** 104 | * Unique ID generated by the server for the Sales account. 105 | */ 106 | account_id: number; 107 | 108 | /** 109 | * Name of the Sales Account. 110 | */ 111 | account_name: string; 112 | 113 | /** 114 | * Unique ID generated by the server for the Inventory account. 115 | */ 116 | inventory_account_id: number; 117 | 118 | /** 119 | * Unique ID generated by the server for the Inventory account. 120 | */ 121 | attribute_id1: number; 122 | 123 | /** 124 | * Name of the attribute present in the Item Group. 125 | */ 126 | attribute_name1: string; 127 | 128 | /** 129 | * Status of the Item Group. 130 | */ 131 | status: "active" | "inactive"; 132 | 133 | /** 134 | * The source of the Item Group. 135 | */ 136 | source: string; 137 | 138 | /** 139 | * Unique ID generated by the server for the Item. This is used as an identifier. 140 | */ 141 | item_id: string; 142 | 143 | item_name: string; 144 | 145 | /** 146 | * Name of the Item. 147 | */ 148 | name: string; 149 | 150 | /** 151 | * Sales price of the Item. 152 | */ 153 | rate: number; 154 | 155 | /** 156 | * Pricelist rate applied on the item. 157 | */ 158 | pricebook_rate: number; 159 | 160 | /** 161 | * Purchase price of the Item. 162 | */ 163 | purchase_rate: number; 164 | 165 | /** 166 | * Reorder level of the item. 167 | */ 168 | reorder_level: number; 169 | 170 | /** 171 | * The opening stock of the item. 172 | */ 173 | initial_stock: number; 174 | 175 | /** 176 | * The opening stock value of the item. 177 | */ 178 | initial_stock_rate: number; 179 | 180 | /** 181 | * Stock based on Shipments and Receives 182 | */ 183 | available_stock: number; 184 | 185 | /** 186 | * Stock based on Shipments and Receives minus ordered stock 187 | */ 188 | actual_available_stock: number; 189 | 190 | /** 191 | * Unique ID generated by the server for the Vendor. This is used as an identifier. 192 | */ 193 | vendor_id: number; 194 | 195 | /** 196 | * Name of the preferred Vendor for purchasing this item. 197 | */ 198 | vendor_name: string; 199 | 200 | /** 201 | * Stock available for a particular item. Is undefined for services and 202 | * not inventory tracked products 203 | */ 204 | stock_on_hand?: number; 205 | 206 | /** 207 | * The Stock Keeeping Unit (SKU) of an item. This is unique for every item in the Inventory. 208 | */ 209 | sku: string; 210 | 211 | /** 212 | * The 12 digit Unique Product Code (UPC) of the item. 213 | */ 214 | upc: number; 215 | 216 | /** 217 | * Unique EAN value for the Item. 218 | */ 219 | ean: number; 220 | 221 | /** 222 | * Unique ISBN value for the Item. 223 | * */ 224 | isbn: string; 225 | /** 226 | * Part Number of the Item. 227 | */ 228 | part_number: string; 229 | 230 | /** 231 | * Unique ID generated by the server for the attribute's options. This is used as an identifier. 232 | */ 233 | attribute_option_id1: number; 234 | 235 | /** 236 | * Name of the attribute's option. 237 | */ 238 | attribute_option_name1: number; 239 | 240 | /** 241 | * Unique ID generated by the server for the item image. This is used as an identifier. 242 | */ 243 | image_id: number; 244 | 245 | /** 246 | * Image name of the Item. 247 | */ 248 | image_name: string; 249 | /** 250 | * The description for the purchase information. This will be displayed to the vendor in your purchase order. 251 | */ 252 | purchase_description: string; 253 | 254 | package_details: PackageDetails; 255 | 256 | /** 257 | * Type of the image i.e., its file format. 258 | */ 259 | image_type: string; 260 | 261 | created_time: string; 262 | 263 | last_modified_time: string; 264 | 265 | is_returnable: boolean; 266 | 267 | warehouses?: WarehouseStock[]; 268 | }; 269 | 270 | /** 271 | * Custom fields that always start with "cf_" 272 | */ 273 | type CustomFieldsDirectAPIResponse = { [key: string]: unknown }; 274 | 275 | type MappedProduct = { 276 | mapped_item_id: string; 277 | item_id: string; 278 | /** 279 | * Every mapped item can have a specific order 280 | */ 281 | item_order: number; 282 | name: string; 283 | rate: number; 284 | rate_formatted: "€0,00"; 285 | purchase_rate: 0.42; 286 | purchase_rate_formatted: "€0,42"; 287 | sku: string; 288 | status: 1; 289 | image_name: ""; 290 | image_document_id: ""; 291 | purchase_description: string; 292 | image_type: ""; 293 | unit: string; 294 | product_type: "goods"; 295 | is_combo_product: false; 296 | description: ""; 297 | quantity: number; 298 | stock_on_hand: number; 299 | stock_on_hand_formatted: "0,00"; 300 | available_stock: number; 301 | available_stock_formatted: "0,00"; 302 | actual_available_stock: number; 303 | actual_available_stock_formatted: "0,00"; 304 | }; 305 | 306 | export type GetItem = Item; 307 | 308 | export type CreateItem = Pick & Item; 309 | 310 | export type ListItem = Pick< 311 | Item, 312 | | "account_id" 313 | | "actual_available_stock" 314 | | "available_stock" 315 | | "brand" 316 | | "ean" 317 | | "is_combo_product" 318 | | "is_returnable" 319 | | "isbn" 320 | | "item_id" 321 | | "item_name" 322 | | "item_type" 323 | | "last_modified_time" 324 | | "created_time" 325 | | "name" 326 | | "manufacturer" 327 | | "name" 328 | | "product_type" 329 | | "purchase_account_id" 330 | | "purchase_rate" 331 | | "rate" 332 | | "sku" 333 | | "stock_on_hand" 334 | | "tax_id" 335 | | "tax_percentage" 336 | | "unit" 337 | | "status" 338 | > & 339 | Partial> & 340 | PackageDetails & 341 | CustomFieldsDirectAPIResponse; 342 | 343 | /** 344 | * Zoho's ItemGroup system is actually just a different name for Product (ItemGroup) and Product Variant (Item) 345 | * Products in an item group share similar features. You can create multiple product variants (items) at once, using 346 | * the ItemGroup create 347 | */ 348 | export type ItemGroup = { 349 | group_id: string; 350 | 351 | /** 352 | * Name of the Item Group. 353 | */ 354 | group_name: string; 355 | 356 | brand: string; 357 | 358 | manufacturer: string; 359 | 360 | /** 361 | * Unit of measurement of the Item Group. 362 | */ 363 | unit: "box" | "kg" | "Stück" | "pcs" | "Set" | "pauschal" | string; 364 | 365 | /** 366 | * Description of the Item Group. 367 | */ 368 | description: string; 369 | 370 | tax_id: string; 371 | 372 | items: Item[]; 373 | 374 | /** 375 | * The variant selection attribute 1 - e.g. "sort" or "color" 376 | */ 377 | attribute_name1: string; 378 | 379 | /** 380 | * The variant selection attribute 2 - e.g. "sort" or "color" 381 | */ 382 | attribute_name2: string; 383 | 384 | attribute_name3: string; 385 | }; 386 | 387 | export type FullCompositeItem = Omit< 388 | Item, 389 | "group_id" | "group_name" | "is_combo_product" | "item_id" 390 | > & { 391 | is_combo_product: true; 392 | mapped_items: MappedProduct[]; 393 | composite_component_items: MappedProduct[]; 394 | composite_service_items: MappedProduct[]; 395 | composite_item_id: string; 396 | }; 397 | 398 | /** 399 | * When creating items directly with the "CreateItemGroup" API call, we have to set different fields mandatory and optional 400 | */ 401 | type CreateItemGroupItem = Required< 402 | Pick 403 | > & 404 | Partial>; 405 | 406 | export type CreateItemGroup = Pick & 407 | Partial< 408 | Pick< 409 | ItemGroup, 410 | | "brand" 411 | | "manufacturer" 412 | | "description" 413 | | "tax_id" 414 | | "attribute_name1" 415 | | "attribute_name2" 416 | | "attribute_name3" 417 | > 418 | > & { 419 | items: CreateItemGroupItem[]; 420 | }; 421 | -------------------------------------------------------------------------------- /src/types/lineItem.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * A sales order can contain multiple line items 3 | */ 4 | export type LineItem = { 5 | line_item_id: string; 6 | 7 | /** 8 | * Unique ID generated by the server for the item. This is used as an identifier. 9 | */ 10 | item_id: string; 11 | 12 | variant_id: string; 13 | 14 | product_id: string; 15 | 16 | /** 17 | * Name of the line item. 18 | */ 19 | name: string; 20 | 21 | sku: string; 22 | 23 | /** 24 | * Description of the line item. 25 | */ 26 | description: string; 27 | 28 | /** 29 | * The order of the line items, starts from 0 by default. 30 | */ 31 | item_order: number; 32 | 33 | /** 34 | * Item rate in the organization's base currency. 35 | */ 36 | bcy_rate: number; 37 | 38 | /** 39 | * Rate / Selling Price of the line item. 40 | */ 41 | rate: number; 42 | 43 | /** 44 | * Quantity of the line item. 45 | */ 46 | quantity: number; 47 | 48 | /** 49 | * Quantity invoiced of the line item. 50 | */ 51 | quantity_invoiced: number; 52 | 53 | /** 54 | * Quantity packed of the line item. 55 | */ 56 | quantity_packed: number; 57 | 58 | /** 59 | * Quantity shipped of the line item. 60 | */ 61 | quantity_shipped: number; 62 | 63 | /** 64 | * Unit of line item. 65 | */ 66 | unit: string; 67 | 68 | /** 69 | * Unique ID generated by the server for the tax. This is used as an identifier. 70 | */ 71 | tax_id: string; 72 | 73 | /** 74 | * Name of the tax applied on the line item. 75 | */ 76 | tax_name: string; 77 | 78 | /** 79 | * Denotes the type of the tax. This can either be a single tax or a tax group. 80 | */ 81 | tax_type: string; 82 | 83 | /** 84 | * Percentage of the tax. 85 | */ 86 | tax_percentage: number; 87 | 88 | /** 89 | * Total of line item after discounts. 90 | * Always the net value 91 | */ 92 | item_total: number; 93 | 94 | /** 95 | * The line item sub-total before line item discounts 96 | */ 97 | item_sub_total: number; 98 | 99 | /** 100 | * This key does only exist when the salesorder/invoice etc is created "inclusive_tax" 101 | */ 102 | item_total_inclusive_of_tax?: number; 103 | 104 | /** 105 | * Checks whether the Sales Order has been invoiced or not. 106 | */ 107 | is_invoiced: boolean; 108 | 109 | /** 110 | * Unique ID generated by the server for the item image. This is used an identifier. 111 | */ 112 | image_id?: string; 113 | 114 | /** 115 | * Name of the image of the line item. 116 | */ 117 | image_name: string; 118 | 119 | /** 120 | * The type (file format) of the image. 121 | */ 122 | image_type: string; 123 | 124 | /** 125 | * Unique ID generated by the server for the warehouses 126 | * Does only exist for inventory tracked products 127 | */ 128 | warehouse_id?: string; 129 | 130 | /** 131 | * The discount value that is applied to the net price. 132 | * Can be a string like "100%" or "10€" 133 | */ 134 | discount: number | string; 135 | 136 | /** 137 | * The net discount amount. Key exist only when active line item discount or 138 | * when this org gives default discount on item level 139 | */ 140 | discount_amount?: number; 141 | 142 | track_batch_number?: boolean; 143 | is_returnable?: boolean; 144 | 145 | attribute_name1: string; 146 | attribute_name2: string; 147 | attribute_name3: string; 148 | 149 | attribute_option_name1: string; 150 | attribute_option_name2: string; 151 | attribute_option_name3: string; 152 | attribute_option_data1: string; 153 | attribute_option_data2: string; 154 | attribute_option_data3: string; 155 | 156 | /** 157 | * Add HSN/SAC code for your goods/services 158 | * 159 | * India Edition only 160 | */ 161 | hsn_or_sac?: number; 162 | 163 | /** 164 | * Additional fields that Zoho adds from time to time 165 | */ 166 | [key: string]: unknown; 167 | }; 168 | -------------------------------------------------------------------------------- /src/types/organizations.ts: -------------------------------------------------------------------------------- 1 | export type Organization = { 2 | organization_id: string; 3 | name: string; 4 | contact_name: string; 5 | email: string; 6 | is_default_org: false; 7 | plan_type: number; 8 | tax_group_enabled: true; 9 | zi_migration_status: 0; 10 | plan_name: string; 11 | plan_period: string; 12 | language_code: string; 13 | fiscal_year_start_month: 0; 14 | account_created_date: string; 15 | account_created_date_formatted: string; 16 | time_zone: string; 17 | is_org_active: true; 18 | currency_id: string; 19 | currency_code: string; 20 | currency_symbol: string; 21 | currency_format: string; 22 | price_precision: 2; 23 | }; 24 | -------------------------------------------------------------------------------- /src/types/package.ts: -------------------------------------------------------------------------------- 1 | import { CustomField } from "./customField"; 2 | 3 | export type ListPackage = Pick< 4 | Package, 5 | | "package_id" 6 | | "salesorder_id" 7 | | "shipment_id" 8 | | "customer_id" 9 | | "customer_name" 10 | | "status" 11 | | "package_number" 12 | | "tracking_number" 13 | | "is_tracking_enabled" 14 | | "shipment_type" 15 | | "date" 16 | | "quantity" 17 | | "salesorder_number" 18 | | "created_time" 19 | | "delivery_method" 20 | | "last_modified_time" 21 | | "shipment_date" 22 | | "is_carrier_shipment" 23 | >; 24 | 25 | export type QuickCreateInput = { 26 | salesorder_id: string; 27 | tracking_number: string; 28 | carrier: string; 29 | }[]; 30 | 31 | export type PackageLineItem = { 32 | line_item_id: string; 33 | so_line_item_id: string; 34 | item_id: string; 35 | picklist_item_id: string; 36 | picklist_number: string; 37 | sku: string; 38 | name: string; 39 | description: string; 40 | item_order: number; 41 | quantity: number; 42 | unit: string; 43 | image_name: string; 44 | image_type: string; 45 | image_document_id: string; 46 | is_invoiced: true; 47 | item_custom_fields: []; 48 | batches: []; 49 | track_batch_for_package: false; 50 | warehouse_id: string; 51 | warehouse_name: string; 52 | }; 53 | 54 | /** 55 | * The ShipmentOrder can be included in a already shipped package 56 | * This types defines the values, that the Zoho API returns us 57 | */ 58 | export type ShipmentOrder = { 59 | date: string; 60 | shipment_id: string; 61 | aftership_carrier_code: "dhl" | "dpd" | "ups" | "hermes"; 62 | shipment_number: string; 63 | shipment_date: string; 64 | shipment_date_with_time: string; 65 | tracking_number: string; 66 | /** 67 | * When you use live tracking, you can't set the trcking link by yourself 68 | */ 69 | tracking_link: string; 70 | delivery_date: string; 71 | delivery_date_with_time: string; 72 | delivery_method: string; 73 | shipment_type: string; 74 | associated_packages_count: number; 75 | carrier: string; 76 | service: string; 77 | delivery_days: string; 78 | delivery_guarantee: false; 79 | tracking_url: string; 80 | is_carrier_shipment: boolean; 81 | notes: string; 82 | 83 | created_time: string; 84 | last_modified_time: string; 85 | }; 86 | 87 | /** 88 | * These are the packages created for Sales Orders 89 | */ 90 | export type Package = { 91 | /** 92 | * Unique ID generated by the server for the package. This is used as an identifier. 93 | */ 94 | package_id: string; 95 | 96 | /** 97 | * Package number. 98 | */ 99 | package_number: string; 100 | 101 | customer_id: string; 102 | 103 | customer_name: string; 104 | 105 | /** 106 | * Sometime Zoho gives us the quantity in string, sometimes as number.. 107 | */ 108 | quantity: string | number; 109 | 110 | total_quantity: number; 111 | 112 | created_time: string; 113 | 114 | is_carrier_shipment: boolean; 115 | 116 | shipment_type: string; 117 | 118 | /** 119 | * The current status of the Package. 120 | */ 121 | status: "not_shipped" | "shipped" | "delivered"; 122 | 123 | /** 124 | * Detailed status. 125 | */ 126 | detailed_status: string; 127 | 128 | /** 129 | * Status message of package. 130 | */ 131 | status_message: string; 132 | 133 | /** 134 | * Unique ID generated by the server for the shipment. This is used as an identifier. 135 | */ 136 | shipment_id: string; 137 | 138 | /** 139 | * Shipment number of the package. 140 | */ 141 | shipment_number: string; 142 | 143 | /** 144 | * Shipment status of the package. 145 | */ 146 | shipment_status: string; 147 | 148 | /** 149 | * Name of the shipping carrier. 150 | */ 151 | carrier: string; 152 | 153 | /** 154 | * In most cases the same as carrier 155 | */ 156 | delivery_method: string; 157 | 158 | line_items: PackageLineItem[]; 159 | 160 | /** 161 | * Name of the service provided by the carrier. 162 | */ 163 | service: string; 164 | 165 | /** 166 | * Tracking number of shipment. 167 | */ 168 | tracking_number: string; 169 | 170 | is_tracking_enabled: boolean; 171 | 172 | /** 173 | * Date, that the package got created 174 | */ 175 | date: string; 176 | 177 | /** 178 | * Shipment date of the Sales Order. 179 | * ISO 8601 format - YYYY-MM-DDThh:mm:ssTZD 180 | */ 181 | shipment_date: string; 182 | 183 | shipment_order?: ShipmentOrder; 184 | 185 | /** 186 | * The expected days to be taken for the delivery. 187 | */ 188 | delivery_days: string; 189 | 190 | /** 191 | * Delivery guarantee of the shipment can be true or false. 192 | */ 193 | delivery_guarantee: boolean; 194 | 195 | last_modified_time: string; 196 | 197 | salesorder_id: string; 198 | 199 | salesorder_number: string; 200 | 201 | notes: string; 202 | 203 | custom_fields?: CustomField[]; 204 | }; 205 | 206 | export type PackageShortList = Pick< 207 | Package, 208 | | "package_id" 209 | | "package_number" 210 | | "date" 211 | | "status" 212 | | "detailed_status" 213 | | "status_message" 214 | | "shipment_id" 215 | | "shipment_number" 216 | | "shipment_status" 217 | | "carrier" 218 | | "service" 219 | | "tracking_number" 220 | | "shipment_date" 221 | | "delivery_days" 222 | | "delivery_guarantee" 223 | | "delivery_method" 224 | | "quantity" 225 | | "is_tracking_enabled" 226 | | "shipment_order" 227 | >; 228 | 229 | export type CreatePackageLineItems = Pick< 230 | PackageLineItem, 231 | "so_line_item_id" | "quantity" 232 | >[]; 233 | export type CreatePackage = Pick & 234 | Partial> & { 235 | line_items: CreatePackageLineItems; 236 | }; 237 | 238 | export type CreatePackageRes = Package; 239 | 240 | export type CreateShipment = Pick< 241 | ShipmentOrder, 242 | "date" | "delivery_method" | "tracking_number" 243 | > & 244 | Partial< 245 | Pick< 246 | ShipmentOrder, 247 | "tracking_link" | "notes" | "aftership_carrier_code" 248 | > 249 | >; 250 | 251 | export type CreateShipmentRes = ShipmentOrder; 252 | -------------------------------------------------------------------------------- /src/types/payment.ts: -------------------------------------------------------------------------------- 1 | export type Payment = { 2 | /** 3 | * Unique ID of the payment generated by the server. Maximum length allowed [2000] 4 | */ 5 | payment_id: string; 6 | 7 | /** 8 | * Mode through which payment is made. This can be check, cash, creditcard, banktransfer, bankremittance, 9 | * autotransaction or others. In german 10 | * Maximum length [100] 11 | * Get all methods by: https://inventory.zoho.eu/api/v1/meta/paymentmodes 12 | */ 13 | payment_mode: 14 | | "braintree" 15 | | "paypal" 16 | | "banktransfer" 17 | | "Banküberweisung" 18 | | "authorizeNet"; 19 | 20 | payment_number: string; 21 | 22 | /** 23 | * Amount paid in the respective payment. 24 | */ 25 | amount: number; 26 | 27 | /** 28 | * Denotes any additional bank charges. - Use this field for paypal etc. transaction costs. 29 | */ 30 | bank_charges: number; 31 | 32 | /** 33 | * Date on which payment is made. Date Format [yyyy-mm-dd] 34 | */ 35 | date: string; 36 | 37 | /** 38 | * Reference number generated for the payment. 39 | * A string of your choice can also be used as the reference number. Maximum length of the reference number [100] 40 | * Zoho uses this field to write the transaction Id of the gateway into it. 41 | */ 42 | reference_number: string; 43 | 44 | /** 45 | * Description about the payment. 46 | */ 47 | description: string; 48 | 49 | /** 50 | * Customer ID of the customer involved in the payment. 51 | */ 52 | customer_id: string; 53 | 54 | created_time: string; 55 | last_modified_time: string; 56 | 57 | /** 58 | * ID of the cash/ bank account the payment has to be deposited. 59 | * Use this field to write the payment to a specific bank or online payments account. 60 | * For example paypal, braintree or others. 61 | */ 62 | account_id: string; 63 | 64 | /** 65 | * List of invoices associated with the payment. Each invoice object contains invoice_id, 66 | * invoice_number, date, invoice_amount, amount_applied and balance_amount. 67 | */ 68 | invoices: { 69 | invoice_id: string; 70 | amount_applied: number; 71 | }[]; 72 | 73 | /** 74 | * Zoho returns this string with all the invoices, that this payment was applied to. 75 | * It looks like this: "INV-002847, INV-002859" 76 | */ 77 | invoice_numbers: string; 78 | }; 79 | 80 | /** 81 | * The list payment is special 82 | */ 83 | export type ListPayment = Pick< 84 | Payment, 85 | | "payment_id" 86 | | "payment_mode" 87 | | "invoice_numbers" 88 | | "payment_number" 89 | | "amount" 90 | | "account_id" 91 | | "description" 92 | | "reference_number" 93 | | "customer_id" 94 | | "created_time" 95 | | "last_modified_time" 96 | | "date" 97 | > & 98 | Partial> & { 99 | /** 100 | * Gives you an array of invoice numbers related 101 | * to this payment. Wwe added this, as "invoices" array 102 | * does not exist for payment list and payments with just one invoice attached 103 | */ 104 | invoice_numbers_array: string[]; 105 | /** 106 | * Custom field gateway transaction id - exist only, if you have created that field in 107 | * Zoho 108 | */ 109 | cf_gateway_transaction_id: string; 110 | }; 111 | 112 | export type CreatePayment = Pick< 113 | Payment, 114 | "customer_id" | "payment_mode" | "amount" | "invoices" | "date" 115 | > & 116 | Partial< 117 | Pick< 118 | Payment, 119 | "reference_number" | "bank_charges" | "account_id" | "description" 120 | > 121 | >; 122 | 123 | export type CreatePaymentRes = { 124 | /** 125 | * Unique ID of the payment generated by the server. Maximum length allowed [2000] 126 | */ 127 | payment_id: string; 128 | 129 | /** 130 | * Mode through which payment is made. This can be check, cash, creditcard, banktransfer, bankremittance, 131 | * autotransaction or others. In german 132 | * Maximum length [100] 133 | * Get all methods by: https://inventory.zoho.eu/api/v1/meta/paymentmodes 134 | */ 135 | payment_mode: "braintree" | "paypal" | "banktransfer" | "Banküberweisung"; 136 | card_type: string; 137 | 138 | payment_number: string; 139 | payment_number_prefix: string; 140 | payment_number_suffix: string; 141 | 142 | payment_link_id: string; 143 | 144 | /** 145 | * Amount paid in the respective payment. 146 | */ 147 | amount: number; 148 | unused_amount: number; 149 | 150 | /** 151 | * Denotes any additional bank charges. - Use this field for paypal etc. transaction costs. 152 | */ 153 | bank_charges: number; 154 | 155 | /** 156 | * Date on which payment is made. Date Format [yyyy-mm-dd] 157 | */ 158 | date: string; 159 | 160 | /** 161 | * Reference number generated for the payment. 162 | * A string of your choice can also be used as the reference number. Maximum length of the reference number [100] 163 | * Zoho uses this field to write the transaction Id of the gateway into it. 164 | */ 165 | reference_number: string; 166 | 167 | /** 168 | * Description about the payment. 169 | */ 170 | description: string; 171 | 172 | /** 173 | * Customer ID of the customer involved in the payment. 174 | */ 175 | customer_id: string; 176 | customer_name: string; 177 | 178 | created_time: string; 179 | updated_time: string; 180 | 181 | /** 182 | * ID of the cash/ bank account the payment has to be deposited. 183 | * Use this field to write the payment to a specific bank or online payments account. 184 | * For example paypal, braintree or others. 185 | */ 186 | account_id: string; 187 | account_name: string; 188 | account_type: string; 189 | 190 | currency_id: string; 191 | currency_symbol: string; 192 | currency_code: string; 193 | 194 | /** 195 | * List of invoices associated with the payment. Each invoice object contains invoice_id, 196 | * invoice_number, date, invoice_amount, amount_applied and balance_amount. 197 | */ 198 | invoices: { 199 | invoice_id: string; 200 | amount_applied: number; 201 | }[]; 202 | 203 | /** 204 | * Zoho returns this string with all the invoices, that this payment was applied to. 205 | * It looks like this: "INV-002847, INV-002859" 206 | */ 207 | invoice_numbers: string; 208 | }; 209 | -------------------------------------------------------------------------------- /src/types/salesOrder.ts: -------------------------------------------------------------------------------- 1 | import type { AddressWithoutAddressId } from "./address"; 2 | import type { Document } from "./document"; 3 | import type { LineItem } from "./lineItem"; 4 | import type { PackageShortList } from "./package"; 5 | import type { Invoice } from "./invoice"; 6 | import type { CustomField } from "./customField"; 7 | import { ContactPersonShortList } from "./contactPerson"; 8 | 9 | export type UpdateSalesOrder = Omit< 10 | CreateSalesOrder, 11 | "documents" | "template_id" 12 | > & 13 | Pick; 14 | 15 | export type PaymentOverview = { 16 | payment_id: string; 17 | payment_mode: string; 18 | payment_mode_id: string; 19 | amount: number; 20 | date: string; 21 | offline_created_date_with_time: string; 22 | description: string; 23 | reference_number: string; 24 | account_id: string; 25 | account_name: string; 26 | payment_type: string; 27 | }; 28 | 29 | export type CreateSalesOrder = 30 | /** 31 | * Required fields 32 | */ 33 | Pick & 34 | /** 35 | * Optional fields 36 | */ 37 | Partial< 38 | Pick< 39 | SalesOrder, 40 | | "adjustment_description" 41 | | "adjustment" 42 | | "contact_persons" 43 | | "date" 44 | | "delivery_method" 45 | | "discount_type" 46 | | "discount" 47 | | "documents" 48 | | "exchange_rate" 49 | | "gst_no" 50 | | "gst_treatment" 51 | | "is_discount_before_tax" 52 | | "notes" 53 | | "place_of_supply" 54 | | "pricebook_id" 55 | | "reference_number" 56 | | "salesorder_id" 57 | | "salesperson_name" 58 | | "shipment_date" 59 | | "shipping_charge_tax_id" 60 | | "shipping_charge" 61 | | "template_id" 62 | | "terms" 63 | > 64 | > & /** 65 | * Additional fields 66 | */ { 67 | line_items: (Pick & 68 | Partial)[]; 69 | 70 | custom_fields?: CustomField[]; 71 | 72 | /** 73 | * Used to specify whether the line item rates are inclusive or exclusive of 74 | * tax. 75 | */ 76 | is_inclusive_tax?: boolean; 77 | 78 | /** 79 | * Exchange rate of the currency, with respect to the base currency. 80 | */ 81 | exchange_rate?: number; 82 | 83 | /** 84 | * Unique Id generated by the server for address in contacts page. To add a 85 | * billing address to sales order, send the address_id using this node. 86 | * Else, the default billing address for that contact is used 87 | */ 88 | billing_address_id?: string; 89 | 90 | /** 91 | * Unique Id generated by the server for address in contacts page. To add a 92 | * shipping address to sales order, send the address_id using this node. Else, 93 | * the default shipping address for that contact is used 94 | */ 95 | shipping_address_id?: string; 96 | }; 97 | 98 | /** 99 | * Custom fields that always start with "cf_" 100 | */ 101 | type CustomFieldsDirectAPIResponse = { [key: string]: unknown }; 102 | 103 | export type SalesOrderStatus = 104 | | "draft" 105 | | "void" 106 | | "onhold" 107 | | "confirmed" 108 | | "closed"; 109 | export type SalesOrderShippedStatus = 110 | | "shipped" 111 | | "partially_shipped" 112 | | "fulfilled" 113 | | "pending" 114 | | ""; 115 | export type SalesOrderInvoicedStatus = 116 | | "invoiced" 117 | | "not_invoiced" 118 | | "partially_invoiced" 119 | | ""; 120 | export type SalesOrderPaidStatus = "paid" | "not_paid" | "partially_paid" | ""; 121 | 122 | /** 123 | * A sales order is a financial document that confirms an impending sale. It 124 | * details the exact quantity, price and delivery details of the products or 125 | * services being sold. Perform the simple operations mentioned below to create 126 | * and manage your Sales Orders 127 | */ 128 | export type SalesOrder = { 129 | /** 130 | * Unique ID generated by the server for the Sales Order. This is used as identifier. 131 | */ 132 | salesorder_id: string; 133 | 134 | payments: PaymentOverview[]; 135 | 136 | /** 137 | * Ignore auto sales order number generation for this sales order. This mandates the sales order number 138 | */ 139 | ignore_auto_number_generation?: boolean; 140 | 141 | /** 142 | * The Sales Order number. This is unique for each sales order. 143 | */ 144 | salesorder_number: string; 145 | 146 | /** 147 | * The date for the Sales Order. 148 | * ISO 8601 format - YYYY-MM-DDThh:mm:ssTZD 149 | */ 150 | date: string; 151 | 152 | /** 153 | * The current status of the Sales Order. 154 | */ 155 | status: string; 156 | 157 | /** 158 | * Shipment date of the Sales Order. 159 | * ISO 8601 format - YYYY-MM-DDThh:mm:ssTZD 160 | */ 161 | shipment_date: string; 162 | 163 | /** 164 | * Reference number of the Sales Order 165 | */ 166 | reference_number: string; 167 | 168 | /** 169 | * Unique ID generated for the customer. This is used as an identifier. 170 | */ 171 | customer_id: string; 172 | 173 | /** 174 | * Name of the customer. 175 | */ 176 | customer_name: string; 177 | 178 | /** 179 | * Company name (billing address) if set in contact 180 | */ 181 | company_name?: string; 182 | 183 | is_inclusive_tax: boolean; 184 | 185 | /** 186 | * The contact persons IDs, that are connected to this salesorder 187 | */ 188 | contact_persons: string[]; 189 | 190 | /** 191 | * The details of the contact associated to this salesorder 192 | */ 193 | contact_person_details: ContactPersonShortList[]; 194 | 195 | /** 196 | * Unique ID generated by the server for the currency. This is used as an identifier. 197 | */ 198 | currency_id: string; 199 | 200 | /** 201 | * Currency code. 202 | */ 203 | currency_code: string; 204 | 205 | /** 206 | * The symbol for the selected currency. 207 | */ 208 | currency_symbol: string; 209 | 210 | /** 211 | * Exchange rate of the currency, with respect to the base currency. 212 | */ 213 | exchange_rate: number; 214 | 215 | /** 216 | * Discount to be applied on the Sales Order. - Exist only when entity level discount is default 217 | * in this org 218 | */ 219 | discount_amount?: number; 220 | 221 | /** 222 | * The percentage of Discount applied. Is a number for discount 223 | * in € and string for discount in percentage ("15%") 224 | */ 225 | discount: string | number; 226 | 227 | /** 228 | * Used to check whether the discount is applied before tax or after tax. 229 | */ 230 | is_discount_before_tax: boolean; 231 | 232 | /** 233 | * Type of discount. Allowed values are entity_level,item_level. For 234 | * entity_level type, discount is applied at entity level and the node 235 | * discount resides outside the line_items node.For item_level type, 236 | * discount is applied at item level and the node discount resides inside 237 | * each line_item under the line_items node 238 | */ 239 | discount_type: "entity_level" | "item_level"; 240 | 241 | /** 242 | * Unique ID generated by the server from the Estimate created in Zoho Books. This is used as an identifier. 243 | */ 244 | estimate_id?: string; 245 | 246 | /** 247 | * Delivery method of the shipment. 248 | */ 249 | delivery_method?: string; 250 | 251 | /** 252 | * Unique ID generated by the server for the delivery method. This is used as an identifier. 253 | */ 254 | delivery_method_id?: string; 255 | 256 | /** 257 | * A sales order can contain multiple line items 258 | */ 259 | line_items: LineItem[]; 260 | 261 | /** 262 | * Shipping charges that can be applied to the Sales Order. 263 | */ 264 | shipping_charge: number; 265 | 266 | /** 267 | * Adjustment on the Sales Order's total. 268 | */ 269 | adjustment: number; 270 | 271 | /** 272 | * Description for the adjustment. 273 | */ 274 | adjustment_description: string; 275 | 276 | /** 277 | * Sub total of the Sales Order. 278 | */ 279 | sub_total: number; 280 | 281 | /** 282 | * Tax total of the Sales Order. 283 | */ 284 | tax_total: number; 285 | 286 | /** 287 | * Total amount of the Sales Order. 288 | */ 289 | total: number; 290 | 291 | /** 292 | * Number of taxes applied on sales order. 293 | */ 294 | taxes: { 295 | tax_amount: number; 296 | tax_name: string; 297 | }[]; 298 | 299 | /** 300 | * The precision level for the price's decimal point in a Sales Order. 301 | */ 302 | price_precision: number; 303 | 304 | /** 305 | * Unique ID generated by the server for the Pricebook. This is used as an identifier. 306 | */ 307 | pricebook_id?: number; 308 | 309 | /** 310 | * Checks whether the Sales Order has been emailed to the customer or not. 311 | */ 312 | is_emailed: boolean; 313 | 314 | /** 315 | * The shipping charges in one object 316 | */ 317 | shipping_charges?: { 318 | description: string; 319 | bcy_rate: number; 320 | /** 321 | * the gross rate shipping charges 322 | */ 323 | rate: number; 324 | tax_id: string; 325 | tax_name: string; 326 | tax_type: string; 327 | tax_percentage: 7; 328 | tax_total_fcy: number; 329 | /** 330 | * the net total shipping costs 331 | */ 332 | item_total: number; 333 | }; 334 | 335 | refund_status: "" | "refunded"; 336 | 337 | /** 338 | * These are the packages created for Sales Orders 339 | * The quantity is the total amount of items in this package 340 | * TODO: fix this type, dont use the whole package type 341 | */ 342 | packages: (PackageShortList & { quantity: number })[]; 343 | 344 | /** 345 | * Invoices created for the Sales Order. 346 | */ 347 | invoices: Pick< 348 | Invoice, 349 | | "invoice_id" 350 | | "invoice_number" 351 | | "reference_number" 352 | | "status" 353 | | "date" 354 | | "due_date" 355 | | "total" 356 | | "balance" 357 | >[]; 358 | 359 | /** 360 | * Customer's shipping address. 361 | */ 362 | shipping_address: AddressWithoutAddressId; 363 | 364 | /** 365 | * The internal Id. Sometimes, Zoho is not returning this value 366 | */ 367 | billing_address_id?: string; 368 | 369 | /** 370 | * The internal Id. Sometimes, Zoho is not returning this value 371 | */ 372 | shipping_address_id?: string; 373 | 374 | /** 375 | * Customer's billing address. 376 | */ 377 | billing_address: AddressWithoutAddressId; 378 | 379 | /** 380 | * Notes for the Sales Order. 381 | */ 382 | notes: string; 383 | 384 | /** 385 | * Terms for the Sales Order. 386 | */ 387 | terms: string; 388 | 389 | /** 390 | * Unique ID generated by the server for the Template. This is used as an identifier. 391 | */ 392 | template_id: string; 393 | 394 | /** 395 | * Name of the template used for the Sales Order. 396 | */ 397 | template_name: string; 398 | 399 | /** 400 | * Type of the template. 401 | */ 402 | template_type: string; 403 | 404 | /** 405 | * Time at which the Sales Order was created. 406 | */ 407 | created_time: string; 408 | 409 | /** 410 | * Time at which the sales order details were last modified. 411 | */ 412 | last_modified_time: string; 413 | 414 | /** 415 | * Name of attached file with Sales Order. 416 | */ 417 | attachment_name: string; 418 | 419 | /** 420 | * Checks whether the sales order can be sent as a mail or not. 421 | */ 422 | can_send_in_mail: boolean; 423 | 424 | /** 425 | * Unique ID generated by the server for the sales person. This is used as an identifier. 426 | */ 427 | salesperson_id: string; 428 | 429 | /** 430 | * Name of the Sales Person. 431 | */ 432 | salesperson_name: string; 433 | 434 | /** 435 | * Sales order can have files attached to them. 436 | */ 437 | documents: Document[]; 438 | 439 | /** 440 | * Applicable for transactions that fall before july 1, 2017 441 | * 442 | * India Edition only 443 | */ 444 | is_pre_gst?: boolean; 445 | 446 | /** 447 | * 15 digit GST identification number of the customer. 448 | * 449 | * India Edition only 450 | */ 451 | gst_no?: string; 452 | 453 | /** 454 | * Choose whether the contact is GST registered/unregistered/consumer/overseas. 455 | * 456 | * India Edition only 457 | */ 458 | gst_treatment?: "business_gst" | "business_none" | "overseas" | "consumer"; 459 | 460 | /** 461 | * Place where the goods/services are supplied to. (If not given, `place of 462 | * contact` given for the contact will be taken) 463 | * 464 | * India Edition only 465 | */ 466 | place_of_supply?: string; 467 | 468 | /** 469 | * Id of the shipping tax 470 | * 471 | * Not documented 472 | */ 473 | shipping_charge_tax_id: string; 474 | 475 | /** 476 | * Shipping charge tax rate in percent. 477 | * 478 | * Not officially documented. Returns empty string when not set 479 | */ 480 | shipping_charge_tax_percentage: number | ""; 481 | 482 | invoiced_status: SalesOrderInvoicedStatus; 483 | 484 | paid_status: SalesOrderPaidStatus; 485 | 486 | shipped_status: SalesOrderShippedStatus; 487 | 488 | order_status: SalesOrderStatus; 489 | 490 | /** 491 | * Additional custom fields 492 | */ 493 | [key: string]: unknown; 494 | 495 | custom_fields: CustomField[]; 496 | }; 497 | 498 | export type ListSalesOrder = Pick< 499 | SalesOrder, 500 | | "salesorder_id" 501 | | "customer_name" 502 | | "customer_id" 503 | | "delivery_date" 504 | | "company_name" 505 | | "salesorder_number" 506 | | "reference_number" 507 | | "date" 508 | | "shipment_date" 509 | | "due_by_days" 510 | | "due_in_days" 511 | | "currency_code" 512 | | "total" 513 | | "total_invoiced_amount" 514 | | "created_time" 515 | | "last_modified_time" 516 | | "is_emailed" 517 | | "quantity" 518 | | "order_status" 519 | | "invoiced_status" 520 | | "paid_status" 521 | | "shipped_status" 522 | | "status" 523 | | "is_drop_shipment" 524 | | "salesperson_name" 525 | | "has_attachment" 526 | > & 527 | CustomFieldsDirectAPIResponse & { 528 | /** 529 | * The email address of the main contact person related to this salesorder 530 | */ 531 | email: string; 532 | }; 533 | -------------------------------------------------------------------------------- /src/types/tax.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Number of taxes applied on sales order 3 | */ 4 | export type Tax = { 5 | tax_type: "tax"; 6 | tax_specific_type: ""; 7 | output_tax_account_name: string; 8 | purchase_tax_account_name: string; 9 | tax_account_id: string; 10 | /** 11 | * Only visible if you have seperated 12 | * tax tracking active 13 | */ 14 | purchase_tax_account_id: string; 15 | is_value_added: true; 16 | is_default_tax: false; 17 | is_editable: true; 18 | 19 | tax_id: string; 20 | 21 | tax_percentage: number; 22 | 23 | /** 24 | * Name of the tax. 25 | */ 26 | tax_name: string; 27 | }; 28 | -------------------------------------------------------------------------------- /src/types/warehouse.ts: -------------------------------------------------------------------------------- 1 | export type Warehouse = { 2 | warehouse_id: string; 3 | 4 | warehouse_name: string; 5 | 6 | is_primary: boolean; 7 | }; 8 | -------------------------------------------------------------------------------- /src/util/format.ts: -------------------------------------------------------------------------------- 1 | import { format } from "date-fns"; 2 | 3 | /** 4 | * Formats a date object to the needed representation for Zoho 5 | * @param date 6 | * @returns 7 | */ 8 | const lastModifiedDateFormat = (date: Date) => { 9 | return format(date, "yyyy-MM-dd'T'HH:mm:ssxx"); 10 | }; 11 | 12 | export { lastModifiedDateFormat }; 13 | -------------------------------------------------------------------------------- /src/util/retry.ts: -------------------------------------------------------------------------------- 1 | export async function sleep(ms: number): Promise { 2 | return new Promise((res) => setTimeout(res, ms)); 3 | } 4 | 5 | /** 6 | * retry automatically retries to perform an asyncronous action. 7 | * @param fn - Must throw an error to indicate failure 8 | * @param maxAttempts 9 | * @param backoffAlgorithm - The algorithm used to calcualte the waiting time. Returns milliseconds 10 | */ 11 | export async function retry( 12 | fn: () => Promise, 13 | config: { 14 | maxAttempts: number; 15 | backoffAlgorithm?: (attempt: number) => number; 16 | }, 17 | ): Promise { 18 | for (let attempt = 1; attempt <= config.maxAttempts; attempt += 1) { 19 | const backoff = config.backoffAlgorithm 20 | ? config.backoffAlgorithm(attempt) 21 | : Math.random() ** Math.min(attempt, 6) * 1000; 22 | 23 | try { 24 | return await fn(); 25 | } catch { 26 | await sleep(backoff); 27 | } 28 | } 29 | throw new Error(`Unable to perform action: ran out of retries.`); 30 | } 31 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@trieb.work/tsconfig-base", 3 | "compilerOptions": { 4 | "baseUrl": ".", 5 | "outDir": "./dist", 6 | "rootDir": "./src", 7 | "declaration": true, 8 | "noEmit": false 9 | }, 10 | "include": ["src/**/*"], 11 | "exclude": ["node_modules", "dist", "src/**/*.test.*"] 12 | } 13 | --------------------------------------------------------------------------------