moneybirdjs 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/dist/client/Client.d.ts +8 -0
  4. package/dist/client/Client.js +17 -0
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +17 -0
  7. package/dist/index.mjs +4 -0
  8. package/dist/rest/RESTManager.d.ts +54 -0
  9. package/dist/rest/RESTManager.js +306 -0
  10. package/dist/rest/RequestHandler.d.ts +9 -0
  11. package/dist/rest/RequestHandler.js +135 -0
  12. package/dist/struct/Administration.d.ts +85 -0
  13. package/dist/struct/Administration.js +252 -0
  14. package/dist/struct/Attachment.d.ts +22 -0
  15. package/dist/struct/Attachment.js +32 -0
  16. package/dist/struct/Contact.d.ts +66 -0
  17. package/dist/struct/Contact.js +160 -0
  18. package/dist/struct/ContactCustomField.d.ts +7 -0
  19. package/dist/struct/ContactCustomField.js +19 -0
  20. package/dist/struct/ContactPerson.d.ts +19 -0
  21. package/dist/struct/ContactPerson.js +39 -0
  22. package/dist/struct/CustomField.d.ts +10 -0
  23. package/dist/struct/CustomField.js +13 -0
  24. package/dist/struct/DocumentDetail.d.ts +23 -0
  25. package/dist/struct/DocumentDetail.js +27 -0
  26. package/dist/struct/DocumentStyle.d.ts +30 -0
  27. package/dist/struct/DocumentStyle.js +33 -0
  28. package/dist/struct/Event.d.ts +16 -0
  29. package/dist/struct/Event.js +17 -0
  30. package/dist/struct/ExternalSalesInvoice.d.ts +49 -0
  31. package/dist/struct/ExternalSalesInvoice.js +105 -0
  32. package/dist/struct/FinancialMutation.d.ts +33 -0
  33. package/dist/struct/FinancialMutation.js +43 -0
  34. package/dist/struct/GeneralDocument.d.ts +33 -0
  35. package/dist/struct/GeneralDocument.js +73 -0
  36. package/dist/struct/InvoiceCustomField.d.ts +7 -0
  37. package/dist/struct/InvoiceCustomField.js +19 -0
  38. package/dist/struct/JournalDocument.d.ts +28 -0
  39. package/dist/struct/JournalDocument.js +64 -0
  40. package/dist/struct/LedgerAccount.d.ts +22 -0
  41. package/dist/struct/LedgerAccount.js +43 -0
  42. package/dist/struct/Note.d.ts +21 -0
  43. package/dist/struct/Note.js +27 -0
  44. package/dist/struct/Payment.d.ts +23 -0
  45. package/dist/struct/Payment.js +27 -0
  46. package/dist/struct/PurchaseInvoice.d.ts +45 -0
  47. package/dist/struct/PurchaseInvoice.js +95 -0
  48. package/dist/struct/Receipt.d.ts +45 -0
  49. package/dist/struct/Receipt.js +95 -0
  50. package/dist/struct/SalesInvoice.d.ts +80 -0
  51. package/dist/struct/SalesInvoice.js +172 -0
  52. package/dist/struct/TaxRate.d.ts +15 -0
  53. package/dist/struct/TaxRate.js +19 -0
  54. package/dist/struct/TypelessDocument.d.ts +26 -0
  55. package/dist/struct/TypelessDocument.js +36 -0
  56. package/dist/struct/index.d.ts +21 -0
  57. package/dist/struct/index.js +37 -0
  58. package/dist/types/api.d.ts +717 -0
  59. package/dist/types/api.js +2 -0
  60. package/dist/types/index.d.ts +7 -0
  61. package/dist/types/index.js +23 -0
  62. package/dist/types/lib.d.ts +106 -0
  63. package/dist/types/lib.js +26 -0
  64. package/dist/types/lib_contact.d.ts +127 -0
  65. package/dist/types/lib_contact.js +2 -0
  66. package/dist/types/lib_documents.d.ts +21 -0
  67. package/dist/types/lib_documents.js +23 -0
  68. package/dist/types/lib_documents_general.d.ts +24 -0
  69. package/dist/types/lib_documents_general.js +2 -0
  70. package/dist/types/lib_documents_journal.d.ts +44 -0
  71. package/dist/types/lib_documents_journal.js +2 -0
  72. package/dist/types/lib_documents_purchaseInvoice.d.ts +64 -0
  73. package/dist/types/lib_documents_purchaseInvoice.js +2 -0
  74. package/dist/types/lib_documents_receipt.d.ts +64 -0
  75. package/dist/types/lib_documents_receipt.js +2 -0
  76. package/dist/types/lib_documents_typeless.d.ts +14 -0
  77. package/dist/types/lib_documents_typeless.js +2 -0
  78. package/dist/types/lib_externalSalesInvoice.d.ts +64 -0
  79. package/dist/types/lib_externalSalesInvoice.js +2 -0
  80. package/dist/types/lib_financialMutation.d.ts +17 -0
  81. package/dist/types/lib_financialMutation.js +2 -0
  82. package/dist/types/lib_salesInvoice.d.ts +112 -0
  83. package/dist/types/lib_salesInvoice.js +2 -0
  84. package/dist/util/Constants.d.ts +2 -0
  85. package/dist/util/Constants.js +6 -0
  86. package/dist/util/Util.d.ts +15 -0
  87. package/dist/util/Util.js +94 -0
  88. package/package.json +32 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 vanBrusselGames
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # moneybirdjs
2
+ A wrapper for the Moneybird API
@@ -0,0 +1,8 @@
1
+ import { Administration } from "../struct";
2
+ import { RESTManager } from "../rest/RESTManager";
3
+ /** */
4
+ export declare class Client {
5
+ rest: RESTManager;
6
+ constructor(apiToken: string);
7
+ getAdministrations(): Promise<Administration[]>;
8
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = void 0;
4
+ const struct_1 = require("../struct");
5
+ const RESTManager_1 = require("../rest/RESTManager");
6
+ // noinspection JSUnusedGlobalSymbols
7
+ /** */
8
+ class Client {
9
+ constructor(apiToken) {
10
+ this.rest = new RESTManager_1.RESTManager(apiToken);
11
+ }
12
+ async getAdministrations() {
13
+ const { data } = await this.rest.getAdministrations();
14
+ return data.map((entry) => new struct_1.Administration(this, entry));
15
+ }
16
+ }
17
+ exports.Client = Client;
@@ -0,0 +1 @@
1
+ export * from './client/Client';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client/Client"), exports);
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import mod from "./index.js";
2
+
3
+ export default mod;
4
+ export const Client = mod.Client;
@@ -0,0 +1,54 @@
1
+ /// <reference types="node" />
2
+ import { RequestHandler } from "./RequestHandler";
3
+ import { AddAttachmentOptions, AddContactOptions, AddLedgerAccountOptions, AddNoteOptions, APIAdministration, APIContact, APIContactPerson, APICustomField, APIDocument, APIDocumentStyle, APIFinancialMutation, APILedgerAccount, APINote, APISalesInvoice, APITaxRate, ContactPersonOptions, ContactSearchOptions, Document, DocumentAddOptions, DocumentEntityType, DocumentSearchOptions, DocumentUpdateOptions, EntityType, Filter, FinancialMutationLinkBookingOptions, FinancialMutationUnlinkBookingOptions, SendSalesInvoiceOptions, TaxRateSearchOptions, UpdateContactOptions, UpdateLedgerAccountOptions } from "../types";
4
+ import { Administration, Contact, ContactPerson, FinancialMutation, SalesInvoice } from "../struct";
5
+ import { LedgerAccount } from "../struct";
6
+ export declare class RESTManager {
7
+ requestHandler: RequestHandler;
8
+ constructor(apiToken: string);
9
+ getAdministrations(): Promise<import("../types").Response<APIAdministration[]>>;
10
+ addAttachment(doc: Document, options: AddAttachmentOptions): Promise<import("../types").Response<void>>;
11
+ deleteAttachment(doc: Document, attachmentId: string): Promise<import("../types").Response<void>>;
12
+ downloadAttachment(doc: Document, attachmentId: string): Promise<import("../types").Response<Buffer>>;
13
+ synchronize(administration: Administration, entityType: EntityType, filter?: Filter): Promise<import("../types").Response<{
14
+ id: string;
15
+ version: number;
16
+ }[]>>;
17
+ listContactsByIds(administration: Administration, ids: Array<string>): Promise<import("../types").Response<APIContact[]>>;
18
+ getContacts(administration: Administration, urlOptions: ContactSearchOptions): Promise<import("../types").Response<APIContact[]>>;
19
+ getContact(administration: Administration, id: string): Promise<import("../types").Response<APIContact>>;
20
+ getContactByCustomerId(administration: Administration, customerId: string): Promise<import("../types").Response<APIContact>>;
21
+ addContact(administration: Administration, options: AddContactOptions): Promise<import("../types").Response<APIContact>>;
22
+ updateContact(contact: Contact, options: UpdateContactOptions): Promise<import("../types").Response<APIContact>>;
23
+ deleteContact(administration: Administration, contactId: string): Promise<import("../types").Response<void>>;
24
+ getContactPerson(contact: Contact, contactPersonId: string): Promise<import("../types").Response<APIContactPerson>>;
25
+ addContactPerson(contact: Contact, options: ContactPersonOptions): Promise<import("../types").Response<APIContactPerson>>;
26
+ updateContactPerson(contactPerson: ContactPerson, options: ContactPersonOptions): Promise<import("../types").Response<APIContactPerson>>;
27
+ deleteContactPerson(contact: Contact, contactPersonId: string): Promise<import("../types").Response<void>>;
28
+ getCustomFields(administration: Administration): Promise<import("../types").Response<APICustomField[]>>;
29
+ getDocumentStyles(administration: Administration): Promise<import("../types").Response<APIDocumentStyle[]>>;
30
+ listDocumentsByIds<T extends APIDocument>(administration: Administration, documentType: DocumentEntityType, ids: Array<string>): Promise<import("../types").Response<T[]>>;
31
+ getDocuments<T extends APIDocument>(administration: Administration, documentType: DocumentEntityType, urlOptions: DocumentSearchOptions): Promise<import("../types").Response<T[]>>;
32
+ getDocument<T extends APIDocument>(administration: Administration, documentType: DocumentEntityType, id: string): Promise<import("../types").Response<T>>;
33
+ addDocument<T extends APIDocument>(administration: Administration, documentType: DocumentEntityType, options: DocumentAddOptions): Promise<import("../types").Response<T>>;
34
+ updateDocument<T extends APIDocument>(document: Document, options: DocumentUpdateOptions, query?: string): Promise<import("../types").Response<T>>;
35
+ deleteDocument(administration: Administration, documentType: DocumentEntityType, documentId: string, refresh_journal_entries?: boolean): Promise<import("../types").Response<void>>;
36
+ addNote(entity: Contact | Document, options: AddNoteOptions): Promise<import("../types").Response<APINote>>;
37
+ deleteNote(entity: Contact | Document, noteId: string): Promise<import("../types").Response<void>>;
38
+ getFinancialMutations(administration: Administration, filter: Filter): Promise<import("../types").Response<APIFinancialMutation[]>>;
39
+ listFinancialMutationsByIds(administration: Administration, ids: Array<string>): Promise<import("../types").Response<APIFinancialMutation[]>>;
40
+ getFinancialMutation(administration: Administration, id: string): Promise<import("../types").Response<APIFinancialMutation>>;
41
+ financialMutationLinkBooking(financialMutation: FinancialMutation, options: FinancialMutationLinkBookingOptions): Promise<import("../types").Response<void>>;
42
+ financialMutationUnlinkBooking(financialMutation: FinancialMutation, options: FinancialMutationUnlinkBookingOptions): Promise<import("../types").Response<void>>;
43
+ getTaxRates(administration: Administration, filter: TaxRateSearchOptions): Promise<import("../types").Response<APITaxRate[]>>;
44
+ getLedgerAccounts(administration: Administration): Promise<import("../types").Response<APILedgerAccount[]>>;
45
+ getLedgerAccount(administration: Administration, id: string): Promise<import("../types").Response<APILedgerAccount>>;
46
+ addLedgerAccount(administration: Administration, options: AddLedgerAccountOptions, rgs_code: string): Promise<import("../types").Response<APILedgerAccount>>;
47
+ updateLedgerAccount(ledgerAccount: LedgerAccount, options: UpdateLedgerAccountOptions, rgs_code: string): Promise<import("../types").Response<APILedgerAccount>>;
48
+ deleteLedgerAccount(administration: Administration, ledgerAccountId: string): Promise<import("../types").Response<void>>;
49
+ getSalesInvoiceByInvoiceId(administration: Administration, salesInvoiceId: string): Promise<import("../types").Response<APISalesInvoice>>;
50
+ getSalesInvoiceByReference(administration: Administration, salesInvoiceReference: string): Promise<import("../types").Response<APISalesInvoice>>;
51
+ sendInvoice(invoice: SalesInvoice, options: SendSalesInvoiceOptions): Promise<import("../types").Response<APISalesInvoice>>;
52
+ registerPaymentCreditInvoice(invoice: SalesInvoice): Promise<import("../types").Response<APISalesInvoice>>;
53
+ duplicateToCreditInvoice(invoice: SalesInvoice): Promise<import("../types").Response<APISalesInvoice>>;
54
+ }
@@ -0,0 +1,306 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RESTManager = void 0;
7
+ const RequestHandler_1 = require("./RequestHandler");
8
+ const Util_1 = require("../util/Util");
9
+ const form_data_1 = __importDefault(require("form-data"));
10
+ class RESTManager {
11
+ constructor(apiToken) {
12
+ this.requestHandler = new RequestHandler_1.RequestHandler(apiToken);
13
+ }
14
+ getAdministrations() {
15
+ return this.requestHandler.request('administrations', { method: "GET", body: "{}" });
16
+ }
17
+ addAttachment(doc, options) {
18
+ const form = new form_data_1.default();
19
+ form.append('file', options.attachmentBuffer, { filename: options.attachmentName ?? 'attachment' });
20
+ const docPath = Util_1.Util.entityRestUrl(Util_1.Util.entityToEntityType(doc));
21
+ const att = docPath === 'external_sales_invoices' ? 'attachment' : 'attachments';
22
+ return this.requestHandler.request(`${doc.administration_id}/${docPath}/${doc.id}/${att}`, {
23
+ method: "POST",
24
+ body: form.getBuffer(),
25
+ additionalHeaders: form.getHeaders()
26
+ });
27
+ }
28
+ deleteAttachment(doc, attachmentId) {
29
+ const docPath = Util_1.Util.entityRestUrl(Util_1.Util.entityToEntityType(doc));
30
+ return this.requestHandler.request(`${doc.administration_id}/${docPath}/${doc.id}/attachments/${attachmentId}`, {
31
+ method: "DELETE",
32
+ body: "{}"
33
+ });
34
+ }
35
+ downloadAttachment(doc, attachmentId) {
36
+ const docPath = Util_1.Util.entityRestUrl(Util_1.Util.entityToEntityType(doc));
37
+ return this.requestHandler.request(`${doc.administration_id}/${docPath}/${doc.id}/attachments/${attachmentId}/download`, {
38
+ method: "GET",
39
+ body: "{}"
40
+ });
41
+ }
42
+ synchronize(administration, entityType, filter) {
43
+ const entityPath = Util_1.Util.entityRestUrl(entityType);
44
+ const query = filter === undefined ? '' : Util_1.Util.queryString({ filter: filter });
45
+ return this.requestHandler.request(`${administration.id}/${entityPath}/synchronization${query}`, { method: "GET", body: "{}" });
46
+ }
47
+ listContactsByIds(administration, ids) {
48
+ return this.requestHandler.request(`${administration.id}/contacts/synchronization`, {
49
+ method: "POST",
50
+ body: JSON.stringify({ ids: ids })
51
+ });
52
+ }
53
+ getContacts(administration, urlOptions) {
54
+ const query = Util_1.Util.queryString(urlOptions);
55
+ return this.requestHandler.request(`${administration.id}/contacts${query}`, {
56
+ method: "GET",
57
+ body: "{}"
58
+ });
59
+ }
60
+ getContact(administration, id) {
61
+ return this.requestHandler.request(`${administration.id}/contacts/${id}`, {
62
+ method: "GET",
63
+ body: "{}"
64
+ });
65
+ }
66
+ getContactByCustomerId(administration, customerId) {
67
+ return this.requestHandler.request(`${administration.id}/contacts/customer_id/${customerId}`, {
68
+ method: "GET",
69
+ body: "{}"
70
+ });
71
+ }
72
+ addContact(administration, options) {
73
+ return this.requestHandler.request(`${administration.id}/contacts`, {
74
+ method: "POST",
75
+ body: JSON.stringify({ contact: options })
76
+ });
77
+ }
78
+ updateContact(contact, options) {
79
+ return this.requestHandler.request(`${contact.administration_id}/contacts/${contact.id}`, {
80
+ method: "PATCH",
81
+ body: JSON.stringify({ contact: options })
82
+ });
83
+ }
84
+ deleteContact(administration, contactId) {
85
+ return this.requestHandler.request(`${administration.id}/contacts/${contactId}`, {
86
+ method: "DELETE",
87
+ body: "{}"
88
+ });
89
+ }
90
+ getContactPerson(contact, contactPersonId) {
91
+ return this.requestHandler.request(`${contact.administration_id}/contacts/${contact.id}/contact_people/${contactPersonId}`, {
92
+ method: "GET",
93
+ body: "{}"
94
+ });
95
+ }
96
+ addContactPerson(contact, options) {
97
+ return this.requestHandler.request(`${contact.administration_id}/contacts/${contact.id}/contact_people`, {
98
+ method: "POST",
99
+ body: JSON.stringify({ contact_person: options })
100
+ });
101
+ }
102
+ updateContactPerson(contactPerson, options) {
103
+ return this.requestHandler.request(`${contactPerson.administration_id}/contacts/${contactPerson.contact.id}/contact_people/${contactPerson.id}`, {
104
+ method: "PATCH",
105
+ body: JSON.stringify({ contact_person: options })
106
+ });
107
+ }
108
+ deleteContactPerson(contact, contactPersonId) {
109
+ return this.requestHandler.request(`${contact.administration.id}/contacts/${contact.id}/contact_people/${contactPersonId}`, {
110
+ method: "DELETE",
111
+ body: "{}"
112
+ });
113
+ }
114
+ getCustomFields(administration) {
115
+ return this.requestHandler.request(`${administration.id}/custom_fields`, {
116
+ method: "GET",
117
+ body: "{}"
118
+ });
119
+ }
120
+ getDocumentStyles(administration) {
121
+ return this.requestHandler.request(`${administration.id}/document_styles`, {
122
+ method: "GET",
123
+ body: "{}"
124
+ });
125
+ }
126
+ //#region Document
127
+ listDocumentsByIds(administration, documentType, ids) {
128
+ const documentPath = Util_1.Util.entityRestUrl(documentType);
129
+ return this.requestHandler.request(`${administration.id}/${documentPath}/synchronization`, {
130
+ method: "POST",
131
+ body: JSON.stringify({ ids: ids })
132
+ });
133
+ }
134
+ getDocuments(administration, documentType, urlOptions) {
135
+ const documentPath = Util_1.Util.entityRestUrl(documentType);
136
+ const query = Util_1.Util.queryString(urlOptions);
137
+ return this.requestHandler.request(`${administration.id}/${documentPath}${query}`, {
138
+ method: "GET",
139
+ body: "{}"
140
+ });
141
+ }
142
+ getDocument(administration, documentType, id) {
143
+ const documentPath = Util_1.Util.entityRestUrl(documentType);
144
+ return this.requestHandler.request(`${administration.id}/${documentPath}/${id}`, {
145
+ method: "GET",
146
+ body: "{}"
147
+ });
148
+ }
149
+ addDocument(administration, documentType, options) {
150
+ const documentPath = Util_1.Util.entityRestUrl(documentType);
151
+ let body = Util_1.Util.entityRequestBody(documentType, options);
152
+ return this.requestHandler.request(`${administration.id}/${documentPath}`, {
153
+ method: "POST",
154
+ body: JSON.stringify(body)
155
+ });
156
+ }
157
+ updateDocument(document, options, query = "") {
158
+ const docType = Util_1.Util.entityToEntityType(document);
159
+ const documentPath = Util_1.Util.entityRestUrl(docType);
160
+ let body = Util_1.Util.entityRequestBody(docType, options);
161
+ return this.requestHandler.request(`${document.administration_id}/${documentPath}/${document.id}${query}`, {
162
+ method: "PATCH",
163
+ body: JSON.stringify(body)
164
+ });
165
+ }
166
+ deleteDocument(administration, documentType, documentId, refresh_journal_entries) {
167
+ const query = refresh_journal_entries ? `?refresh_journal_entries=true` : "";
168
+ const documentPath = Util_1.Util.entityRestUrl(documentType);
169
+ return this.requestHandler.request(`${administration.id}/${documentPath}/${documentId}${query}`, {
170
+ method: "DELETE",
171
+ body: "{}"
172
+ });
173
+ }
174
+ //#endregion Document
175
+ //todo: Payments
176
+ /*
177
+ public addPayment(entity: PurchaseInvoice | Receipt, options: AddPaymentOptions) {
178
+ const entityPath = Util.documentRestUrl(doc)
179
+ return this.requestHandler.request<APIPayment>(`${entity.administration_id}/${entityPath}/${entity.id}/payments`, {
180
+ method: "POST",
181
+ body: JSON.stringify({payment: options})
182
+ })
183
+ }
184
+
185
+ public deletePayment(entity: PurchaseInvoice | Receipt, paymentId: string) {
186
+ const entityPath = Util.documentRestUrl(doc)
187
+ return this.requestHandler.request<void>(`${entity.administration_id}/${entityPath}/${entity.id}/payments/${paymentId}`, {
188
+ method: "DELETE",
189
+ body: "{}"
190
+ })
191
+ }
192
+ */
193
+ addNote(entity, options) {
194
+ const entityPath = Util_1.Util.entityRestUrl(Util_1.Util.entityToEntityType(entity));
195
+ return this.requestHandler.request(`${entity.administration_id}/${entityPath}/${entity.id}/notes`, {
196
+ method: "POST",
197
+ body: JSON.stringify({ note: options })
198
+ });
199
+ }
200
+ deleteNote(entity, noteId) {
201
+ const entityPath = Util_1.Util.entityRestUrl(Util_1.Util.entityToEntityType(entity));
202
+ return this.requestHandler.request(`${entity.administration_id}/${entityPath}/${entity.id}/notes/${noteId}`, {
203
+ method: "DELETE",
204
+ body: "{}"
205
+ });
206
+ }
207
+ getFinancialMutations(administration, filter) {
208
+ const query = Util_1.Util.queryString({ filter: filter });
209
+ return this.requestHandler.request(`${administration.id}/financial_mutations${query}`, {
210
+ method: "GET",
211
+ body: "{}"
212
+ });
213
+ }
214
+ listFinancialMutationsByIds(administration, ids) {
215
+ return this.requestHandler.request(`${administration.id}/financial_mutations/synchronization`, {
216
+ method: "POST",
217
+ body: JSON.stringify({ ids: ids })
218
+ });
219
+ }
220
+ getFinancialMutation(administration, id) {
221
+ return this.requestHandler.request(`${administration.id}/financial_mutations/${id}`, {
222
+ method: "GET",
223
+ body: "{}"
224
+ });
225
+ }
226
+ financialMutationLinkBooking(financialMutation, options) {
227
+ return this.requestHandler.request(`${financialMutation.administration_id}/financial_mutations/${financialMutation.id}/link_booking`, {
228
+ method: "PATCH",
229
+ body: JSON.stringify(options)
230
+ });
231
+ }
232
+ financialMutationUnlinkBooking(financialMutation, options) {
233
+ return this.requestHandler.request(`${financialMutation.administration_id}/financial_mutations/${financialMutation.id}/unlink_booking`, {
234
+ method: "DELETE",
235
+ body: JSON.stringify(options)
236
+ });
237
+ }
238
+ getTaxRates(administration, filter) {
239
+ const query = Util_1.Util.queryString({ filter: filter });
240
+ return this.requestHandler.request(`${administration.id}/tax_rates${query}`, {
241
+ method: "GET",
242
+ body: "{}"
243
+ });
244
+ }
245
+ getLedgerAccounts(administration) {
246
+ return this.requestHandler.request(`${administration.id}/ledger_accounts`, {
247
+ method: "GET",
248
+ body: "{}"
249
+ });
250
+ }
251
+ getLedgerAccount(administration, id) {
252
+ return this.requestHandler.request(`${administration.id}/ledger_accounts/${id}`, {
253
+ method: "GET",
254
+ body: "{}"
255
+ });
256
+ }
257
+ addLedgerAccount(administration, options, rgs_code) {
258
+ return this.requestHandler.request(`${administration.id}/ledger_accounts`, {
259
+ method: "POST",
260
+ body: JSON.stringify({ ledger_account: options, rgs_code: rgs_code })
261
+ });
262
+ }
263
+ updateLedgerAccount(ledgerAccount, options, rgs_code) {
264
+ return this.requestHandler.request(`${ledgerAccount.administration_id}/ledger_accounts/${ledgerAccount.id}`, {
265
+ method: "PATCH",
266
+ body: JSON.stringify({ ledger_account: options, rgs_code: rgs_code })
267
+ });
268
+ }
269
+ deleteLedgerAccount(administration, ledgerAccountId) {
270
+ return this.requestHandler.request(`${administration.id}/ledger_accounts/${ledgerAccountId}`, {
271
+ method: "DELETE",
272
+ body: "{}"
273
+ });
274
+ }
275
+ getSalesInvoiceByInvoiceId(administration, salesInvoiceId) {
276
+ return this.requestHandler.request(`${administration.id}/sales_invoices/find_by_invoice_id/${salesInvoiceId}`, {
277
+ method: "GET",
278
+ body: "{}"
279
+ });
280
+ }
281
+ getSalesInvoiceByReference(administration, salesInvoiceReference) {
282
+ return this.requestHandler.request(`${administration.id}/sales_invoices/find_by_reference/${salesInvoiceReference}`, {
283
+ method: "GET",
284
+ body: "{}"
285
+ });
286
+ }
287
+ sendInvoice(invoice, options) {
288
+ return this.requestHandler.request(`${invoice.administration_id}/sales_invoices/${invoice.id}/send_invoice`, {
289
+ method: "PATCH",
290
+ body: JSON.stringify({ sales_invoice_sending: options })
291
+ });
292
+ }
293
+ registerPaymentCreditInvoice(invoice) {
294
+ return this.requestHandler.request(`${invoice.administration_id}/sales_invoices/${invoice.id}/register_payment_creditinvoice`, {
295
+ method: "PATCH",
296
+ body: "{}"
297
+ });
298
+ }
299
+ duplicateToCreditInvoice(invoice) {
300
+ return this.requestHandler.request(`${invoice.administration_id}/sales_invoices/${invoice.id}/duplicate_creditinvoice`, {
301
+ method: "PATCH",
302
+ body: "{}"
303
+ });
304
+ }
305
+ }
306
+ exports.RESTManager = RESTManager;
@@ -0,0 +1,9 @@
1
+ import { RequestOptions, Response } from "../types";
2
+ export declare class RequestHandler {
3
+ #private;
4
+ rejectIfNotValid: boolean;
5
+ rateLimit: number;
6
+ constructor(apiToken: string);
7
+ request<T>(path: string, options: RequestOptions): Promise<Response<T>>;
8
+ private exec;
9
+ }
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
26
+ if (kind === "m") throw new TypeError("Private method is not writable");
27
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
28
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
29
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
30
+ };
31
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
32
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
33
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
34
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
35
+ };
36
+ var _RequestHandler_apiToken;
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.RequestHandler = void 0;
39
+ const Constants = __importStar(require("../util/Constants"));
40
+ class RequestHandler {
41
+ constructor(apiToken) {
42
+ this.rejectIfNotValid = true;
43
+ this.rateLimit = 10;
44
+ _RequestHandler_apiToken.set(this, void 0);
45
+ __classPrivateFieldSet(this, _RequestHandler_apiToken, apiToken, "f");
46
+ }
47
+ async request(path, options) {
48
+ return this.exec(path, options);
49
+ }
50
+ async exec(path, options, retries = 0) {
51
+ try {
52
+ let contentType = 'application/json';
53
+ if (options.additionalHeaders?.["content-type"]) {
54
+ contentType = options.additionalHeaders["content-type"];
55
+ delete options.additionalHeaders["content-type"];
56
+ }
57
+ const headers = {
58
+ 'Authorization': `Bearer ${__classPrivateFieldGet(this, _RequestHandler_apiToken, "f")}`,
59
+ 'Content-Type': contentType,
60
+ ...options.additionalHeaders
61
+ };
62
+ const res = await fetch(`${Constants.APIBaseURL}${path}`, {
63
+ method: options.method, headers: headers,
64
+ body: options.method !== 'GET' ? options.body : undefined
65
+ });
66
+ if (res.status >= 500 && retries < this.rateLimit) {
67
+ return this.exec(path, options, ++retries);
68
+ }
69
+ if (res.status === 429) {
70
+ const retryAfter = parseInt(res.headers.get('Retry-After'));
71
+ const rateLimitRemaining = parseInt(res.headers.get('RateLimit-Remaining'));
72
+ //const rateLimitLimit = parseInt(res.headers.get('RateLimit-Limit')!)
73
+ const rateLimitReset = parseInt(res.headers.get('RateLimit-Reset'));
74
+ const timeoutMS = (1 + (rateLimitRemaining < 10 ? rateLimitReset : retryAfter)) * 1000 - Date.now();
75
+ await new Promise((resolve) => {
76
+ setTimeout(resolve, timeoutMS);
77
+ });
78
+ return this.exec(path, options, ++retries);
79
+ }
80
+ if (res.status === 204)
81
+ return {
82
+ data: {},
83
+ status: 204,
84
+ maxAge: 0,
85
+ path,
86
+ ok: true
87
+ };
88
+ let data = null;
89
+ if (res.body != null) {
90
+ data = res.body;
91
+ const chunks = [];
92
+ const reader = data.getReader();
93
+ while (true) {
94
+ const { value, done } = await reader.read();
95
+ if (value !== undefined)
96
+ chunks.push(value);
97
+ if (done)
98
+ break;
99
+ }
100
+ const buffer = Buffer.concat(chunks);
101
+ try {
102
+ data = JSON.parse(buffer.toString());
103
+ }
104
+ catch (e) {
105
+ const contentDisposition = res.headers?.get('content-disposition');
106
+ if (contentDisposition?.startsWith('attachment')) {
107
+ data = buffer;
108
+ }
109
+ }
110
+ }
111
+ const isOk = res.status === 200 || res.status === 201;
112
+ if (!isOk)
113
+ throw new Error(`non valid: ${res.status} ${JSON.stringify(res)}`);
114
+ return { data: data, status: res.status, maxAge: 0, path, ok: isOk };
115
+ //https://developer.moneybird.com/#responses
116
+ }
117
+ catch (e) {
118
+ // fetch error timeout and rate-limit not reached yet -> Try again
119
+ if (e instanceof Error && e.message === 'fetch failed' && retries < this.rateLimit) {
120
+ return this.exec(path, options, ++retries);
121
+ }
122
+ if (this.rejectIfNotValid)
123
+ throw e;
124
+ return {
125
+ data: { message: e.message },
126
+ maxAge: 0,
127
+ status: 500,
128
+ path,
129
+ ok: false
130
+ };
131
+ }
132
+ }
133
+ }
134
+ exports.RequestHandler = RequestHandler;
135
+ _RequestHandler_apiToken = new WeakMap();