@voyantjs/plugin-smartbill 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 PixelMakers Studio SRL
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly
28
+ display and redistribute the Software for any Permitted Purpose identified
29
+ below.
30
+
31
+ ### Permitted Purpose
32
+
33
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing
34
+ Use means making the Software available to others in a commercial product or
35
+ service that:
36
+
37
+ 1. substitutes for the Software;
38
+
39
+ 2. substitutes for any other product or service we offer using the Software
40
+ that exists as of the date we make the Software available; or
41
+
42
+ 3. offers the same or substantially similar functionality as the Software.
43
+
44
+ Permitted Purposes specifically include using the Software:
45
+
46
+ 1. for your internal use and access;
47
+
48
+ 2. for non-commercial education;
49
+
50
+ 3. for non-commercial research; and
51
+
52
+ 4. in connection with professional services that you provide to a licensee
53
+ using the Software in accordance with these Terms and Conditions.
54
+
55
+ ### Patents
56
+
57
+ To the extent your use for a Permitted Purpose would necessarily infringe
58
+ our patents, the license grant above includes a license under our patents.
59
+ If you make a claim against any party that the Software infringes or
60
+ contributes to the infringement of any patent, then your patent license to
61
+ the Software ends immediately.
62
+
63
+ ### Redistribution
64
+
65
+ The Terms and Conditions apply to all copies, modifications and derivatives
66
+ of the Software.
67
+
68
+ If you redistribute any copies, modifications or derivatives of the
69
+ Software, you must include a copy of or a link to these Terms and Conditions
70
+ and not remove any copyright notices provided in or with the Software.
71
+
72
+ ### Disclaimer
73
+
74
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS
75
+ OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A
76
+ PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
77
+
78
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO
79
+ THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
80
+ DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
81
+
82
+ ### Trademarks
83
+
84
+ Except for displaying the License Details and identifying us as the origin
85
+ of the Software, you have no right under these Terms and Conditions to use
86
+ our trademarks, trade names, service marks or product names.
87
+
88
+ ---
89
+
90
+ ## Grant of Future License
91
+
92
+ We hereby irrevocably grant you an additional license to use the Software
93
+ under the Apache License, Version 2.0 that is effective on the second
94
+ anniversary of the date we make the Software available. On or after that
95
+ date, you may use the Software under the Apache License, Version 2.0, in
96
+ which case the following will apply:
97
+
98
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
99
+ use this file except in compliance with the License.
100
+
101
+ You may obtain a copy of the License at
102
+
103
+ http://www.apache.org/licenses/LICENSE-2.0
104
+
105
+ Unless required by applicable law or agreed to in writing, software
106
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
107
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
108
+ License for the specific language governing permissions and limitations
109
+ under the License.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @voyantjs/plugin-smartbill
2
+
3
+ SmartBill e-invoicing plugin for Voyant. Subscribes to invoice events and creates/cancels/syncs invoices via the SmartBill REST API for Romanian tax compliance.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @voyantjs/plugin-smartbill
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { smartbillPlugin } from "@voyantjs/plugin-smartbill"
15
+ import { createApp } from "@voyantjs/hono"
16
+
17
+ const app = createApp({
18
+ plugins: [
19
+ smartbillPlugin({
20
+ username: env.SMARTBILL_USERNAME,
21
+ apiToken: env.SMARTBILL_API_TOKEN,
22
+ companyVatCode: "RO12345678",
23
+ seriesName: "A",
24
+ // optional: language, art311SpecialRegime, events, mapEvent, logger
25
+ }),
26
+ ],
27
+ })
28
+ ```
29
+
30
+ By default the plugin wires up 3 subscribers (`invoice.issued`, `invoice.voided`, `invoice.external.sync.requested`) that create, cancel, and check payment status on SmartBill. All error handling is fire-and-forget per the EventBus contract.
31
+
32
+ ## Exports
33
+
34
+ | Entry | Description |
35
+ | --- | --- |
36
+ | `.` | Barrel re-exports |
37
+ | `./plugin` | `smartbillPlugin(options)` |
38
+ | `./client` | `createSmartbillClient` — `createInvoice`, `cancelInvoice`, `viewPdf`, `getPaymentStatus`, etc. |
39
+ | `./types` | SmartBill invoice types |
40
+
41
+ ## License
42
+
43
+ FSL-1.1-Apache-2.0
@@ -0,0 +1,38 @@
1
+ import type { SmartbillFetch, SmartbillInvoiceBody, SmartbillInvoiceResponse, SmartbillPdfResponse, SmartbillStatusResponse } from "./types.js";
2
+ /**
3
+ * Options for {@link createSmartbillClient}.
4
+ */
5
+ export interface SmartbillClientOptions {
6
+ /** SmartBill account username (email). */
7
+ username: string;
8
+ /** SmartBill API token. */
9
+ apiToken: string;
10
+ /**
11
+ * SmartBill API base URL. Defaults to `"https://ws.smartbill.ro/SBORO/api"`.
12
+ */
13
+ apiUrl?: string;
14
+ /** Override `fetch` (e.g. in tests). Defaults to global `fetch`. */
15
+ fetch?: SmartbillFetch;
16
+ }
17
+ export interface SmartbillClientApi {
18
+ /** Create an invoice. Returns the series + number + URL. */
19
+ createInvoice(body: SmartbillInvoiceBody): Promise<SmartbillInvoiceResponse>;
20
+ /** Create a proforma invoice. */
21
+ createProforma(body: SmartbillInvoiceBody): Promise<SmartbillInvoiceResponse>;
22
+ /** Cancel an invoice by series + number. */
23
+ cancelInvoice(companyVatCode: string, seriesName: string, number: string): Promise<{
24
+ errorText?: string;
25
+ }>;
26
+ /** Delete an invoice by series + number. */
27
+ deleteInvoice(companyVatCode: string, seriesName: string, number: string): Promise<{
28
+ errorText?: string;
29
+ }>;
30
+ /** Reverse an invoice by series + number. */
31
+ reverseInvoice(companyVatCode: string, seriesName: string, number: string): Promise<SmartbillInvoiceResponse>;
32
+ /** Get PDF URL for an invoice. */
33
+ viewPdf(companyVatCode: string, seriesName: string, number: string): Promise<SmartbillPdfResponse>;
34
+ /** Get payment status for an invoice. */
35
+ getPaymentStatus(companyVatCode: string, seriesName: string, number: string): Promise<SmartbillStatusResponse>;
36
+ }
37
+ export declare function createSmartbillClient(options: SmartbillClientOptions): SmartbillClientApi;
38
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,wBAAwB,EACxB,oBAAoB,EACpB,uBAAuB,EACxB,MAAM,YAAY,CAAA;AAEnB;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAA;IAChB,2BAA2B;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,oEAAoE;IACpE,KAAK,CAAC,EAAE,cAAc,CAAA;CACvB;AAED,MAAM,WAAW,kBAAkB;IACjC,4DAA4D;IAC5D,aAAa,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAA;IAC5E,iCAAiC;IACjC,cAAc,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAA;IAC7E,4CAA4C;IAC5C,aAAa,CACX,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAClC,4CAA4C;IAC5C,aAAa,CACX,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAClC,6CAA6C;IAC7C,cAAc,CACZ,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,wBAAwB,CAAC,CAAA;IACpC,kCAAkC;IAClC,OAAO,CAAC,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAA;IAClG,yCAAyC;IACzC,gBAAgB,CACd,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,uBAAuB,CAAC,CAAA;CACpC;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,sBAAsB,GAAG,kBAAkB,CAyIzF"}
@@ -0,0 +1,105 @@
1
+ export function createSmartbillClient(options) {
2
+ const apiUrl = (options.apiUrl ?? "https://ws.smartbill.ro/SBORO/api").replace(/\/$/, "");
3
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4
+ function authHeader() {
5
+ return `Basic ${btoa(`${options.username}:${options.apiToken}`)}`;
6
+ }
7
+ function headers() {
8
+ return {
9
+ Authorization: authHeader(),
10
+ "Content-Type": "application/json",
11
+ Accept: "application/json",
12
+ };
13
+ }
14
+ async function request(method, path, body) {
15
+ if (!fetchImpl) {
16
+ throw new Error("SmartBill client requires a fetch implementation");
17
+ }
18
+ const init = {
19
+ method,
20
+ headers: headers(),
21
+ };
22
+ if (body !== undefined)
23
+ init.body = JSON.stringify(body);
24
+ const response = await fetchImpl(`${apiUrl}${path}`, init);
25
+ let text = "";
26
+ let json = null;
27
+ try {
28
+ text = await response.text();
29
+ json = text ? JSON.parse(text) : null;
30
+ }
31
+ catch {
32
+ // leave json as null, surface text
33
+ }
34
+ return { ok: response.ok, status: response.status, json, text };
35
+ }
36
+ async function createInvoice(body) {
37
+ const res = await request("POST", "/invoice", body);
38
+ if (!res.ok) {
39
+ throw new Error(`SmartBill createInvoice failed (${res.status}): ${res.text}`);
40
+ }
41
+ return (res.json ?? {});
42
+ }
43
+ async function createProforma(body) {
44
+ const res = await request("POST", "/estimate", body);
45
+ if (!res.ok) {
46
+ throw new Error(`SmartBill createProforma failed (${res.status}): ${res.text}`);
47
+ }
48
+ return (res.json ?? {});
49
+ }
50
+ async function cancelInvoice(companyVatCode, seriesName, number) {
51
+ const res = await request("PUT", "/invoice/cancel", {
52
+ companyVatCode,
53
+ seriesName,
54
+ number,
55
+ });
56
+ if (!res.ok) {
57
+ throw new Error(`SmartBill cancelInvoice failed (${res.status}): ${res.text}`);
58
+ }
59
+ return (res.json ?? {});
60
+ }
61
+ async function deleteInvoice(companyVatCode, seriesName, number) {
62
+ const query = `cif=${encodeURIComponent(companyVatCode)}&seriesname=${encodeURIComponent(seriesName)}&number=${encodeURIComponent(number)}`;
63
+ const res = await request("DELETE", `/invoice?${query}`);
64
+ if (!res.ok) {
65
+ throw new Error(`SmartBill deleteInvoice failed (${res.status}): ${res.text}`);
66
+ }
67
+ return (res.json ?? {});
68
+ }
69
+ async function reverseInvoice(companyVatCode, seriesName, number) {
70
+ const res = await request("PUT", "/invoice/reverse", {
71
+ companyVatCode,
72
+ seriesName,
73
+ number,
74
+ });
75
+ if (!res.ok) {
76
+ throw new Error(`SmartBill reverseInvoice failed (${res.status}): ${res.text}`);
77
+ }
78
+ return (res.json ?? {});
79
+ }
80
+ async function viewPdf(companyVatCode, seriesName, number) {
81
+ const query = `cif=${encodeURIComponent(companyVatCode)}&seriesname=${encodeURIComponent(seriesName)}&number=${encodeURIComponent(number)}`;
82
+ const res = await request("GET", `/invoice/pdf?${query}`);
83
+ if (!res.ok) {
84
+ throw new Error(`SmartBill viewPdf failed (${res.status}): ${res.text}`);
85
+ }
86
+ return (res.json ?? {});
87
+ }
88
+ async function getPaymentStatus(companyVatCode, seriesName, number) {
89
+ const query = `cif=${encodeURIComponent(companyVatCode)}&seriesname=${encodeURIComponent(seriesName)}&number=${encodeURIComponent(number)}`;
90
+ const res = await request("GET", `/invoice/paymentstatus?${query}`);
91
+ if (!res.ok) {
92
+ throw new Error(`SmartBill getPaymentStatus failed (${res.status}): ${res.text}`);
93
+ }
94
+ return (res.json ?? {});
95
+ }
96
+ return {
97
+ createInvoice,
98
+ createProforma,
99
+ cancelInvoice,
100
+ deleteInvoice,
101
+ reverseInvoice,
102
+ viewPdf,
103
+ getPaymentStatus,
104
+ };
105
+ }
@@ -0,0 +1,8 @@
1
+ export type { SmartbillClientApi, SmartbillClientOptions } from "./client.js";
2
+ export { createSmartbillClient } from "./client.js";
3
+ export type { SmartbillMappingOptions } from "./mapping.js";
4
+ export { mapClient, mapLineItems, mapVoyantInvoiceToSmartbill } from "./mapping.js";
5
+ export type { SmartbillLogger, SmartbillMapFn, SmartbillPluginOptions, SmartbillSyncEventNames, } from "./plugin.js";
6
+ export { smartbillPlugin } from "./plugin.js";
7
+ export type { SmartbillClient, SmartbillFetch, SmartbillInvoiceBody, SmartbillInvoiceResponse, SmartbillPdfResponse, SmartbillProduct, SmartbillStatusResponse, VoyantInvoiceEvent, } from "./types.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAA;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AACnD,YAAY,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAC3D,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAA;AACnF,YAAY,EACV,eAAe,EACf,cAAc,EACd,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,YAAY,EACV,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,wBAAwB,EACxB,oBAAoB,EACpB,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,GACnB,MAAM,YAAY,CAAA"}
@@ -0,0 +1,3 @@
1
+ export { createSmartbillClient } from "./client.js";
2
+ export { mapClient, mapLineItems, mapVoyantInvoiceToSmartbill } from "./mapping.js";
3
+ export { smartbillPlugin } from "./plugin.js";
@@ -0,0 +1,32 @@
1
+ import type { SmartbillClient, SmartbillInvoiceBody, SmartbillProduct, VoyantInvoiceEvent } from "./types.js";
2
+ /**
3
+ * Options for the default invoice mapper.
4
+ */
5
+ export interface SmartbillMappingOptions {
6
+ /** Romanian company VAT code (e.g. `"RO12345678"`). */
7
+ companyVatCode: string;
8
+ /** SmartBill invoice series name (e.g. `"A"`). */
9
+ seriesName: string;
10
+ /** Invoice language. Defaults to `"RO"`. */
11
+ language?: string;
12
+ /** Whether VAT is included in line item prices. Defaults to `true`. */
13
+ isTaxIncluded?: boolean;
14
+ /** Whether to use Art. 311 special regime (margin scheme for travel). */
15
+ art311SpecialRegime?: boolean;
16
+ }
17
+ /**
18
+ * Extract the SmartBill client block from a Voyant invoice event.
19
+ * Falls back to empty strings for missing fields.
20
+ */
21
+ export declare function mapClient(event: VoyantInvoiceEvent): SmartbillClient;
22
+ /**
23
+ * Extract SmartBill product lines from a Voyant invoice event.
24
+ * Expects `event.lineItems` to be an array of objects with at minimum
25
+ * `description`/`name`, `quantity`, `unitPrice`, `currency`.
26
+ */
27
+ export declare function mapLineItems(event: VoyantInvoiceEvent, options: SmartbillMappingOptions): SmartbillProduct[];
28
+ /**
29
+ * Map a full Voyant invoice event to a SmartBill invoice body.
30
+ */
31
+ export declare function mapVoyantInvoiceToSmartbill(event: VoyantInvoiceEvent, options: SmartbillMappingOptions): SmartbillInvoiceBody;
32
+ //# sourceMappingURL=mapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapping.d.ts","sourceRoot":"","sources":["../../src/mapping.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,oBAAoB,EACpB,gBAAgB,EAChB,kBAAkB,EACnB,MAAM,YAAY,CAAA;AAEnB;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,uDAAuD;IACvD,cAAc,EAAE,MAAM,CAAA;IACtB,kDAAkD;IAClD,UAAU,EAAE,MAAM,CAAA;IAClB,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,uEAAuE;IACvE,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,yEAAyE;IACzE,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,kBAAkB,GAAG,eAAe,CAapE;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,kBAAkB,EACzB,OAAO,EAAE,uBAAuB,GAC/B,gBAAgB,EAAE,CAgBpB;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,kBAAkB,EACzB,OAAO,EAAE,uBAAuB,GAC/B,oBAAoB,CA2BtB"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Extract the SmartBill client block from a Voyant invoice event.
3
+ * Falls back to empty strings for missing fields.
4
+ */
5
+ export function mapClient(event) {
6
+ return {
7
+ name: asString(event.clientName ?? event.customerName, "Client"),
8
+ vatCode: asStringOrUndefined(event.clientVatCode ?? event.customerVatCode),
9
+ regCom: asStringOrUndefined(event.clientRegCom),
10
+ address: asStringOrUndefined(event.clientAddress ?? event.customerAddress),
11
+ city: asStringOrUndefined(event.clientCity ?? event.customerCity),
12
+ county: asStringOrUndefined(event.clientCounty ?? event.customerCounty),
13
+ country: asStringOrUndefined(event.clientCountry ?? event.customerCountry),
14
+ email: asStringOrUndefined(event.clientEmail ?? event.customerEmail),
15
+ phone: asStringOrUndefined(event.clientPhone ?? event.customerPhone),
16
+ saveToDb: false,
17
+ };
18
+ }
19
+ /**
20
+ * Extract SmartBill product lines from a Voyant invoice event.
21
+ * Expects `event.lineItems` to be an array of objects with at minimum
22
+ * `description`/`name`, `quantity`, `unitPrice`, `currency`.
23
+ */
24
+ export function mapLineItems(event, options) {
25
+ const items = event.lineItems;
26
+ if (!Array.isArray(items))
27
+ return [];
28
+ return items.map((item) => ({
29
+ name: asString(item.description ?? item.name, "Item"),
30
+ code: asStringOrUndefined(item.code ?? item.sku),
31
+ measureUnit: asString(item.measureUnit ?? item.unit, "buc"),
32
+ quantity: asNumber(item.quantity, 1),
33
+ price: asNumber(item.unitPrice ?? item.price, 0),
34
+ currency: asString(item.currency ?? event.currency, "RON"),
35
+ isTaxIncluded: options.isTaxIncluded ?? true,
36
+ taxPercentage: item.taxPercentage != null ? asNumber(item.taxPercentage, 0) : undefined,
37
+ isService: item.isService === true,
38
+ saveToDb: false,
39
+ }));
40
+ }
41
+ /**
42
+ * Map a full Voyant invoice event to a SmartBill invoice body.
43
+ */
44
+ export function mapVoyantInvoiceToSmartbill(event, options) {
45
+ const body = {
46
+ companyVatCode: options.companyVatCode,
47
+ client: mapClient(event),
48
+ seriesName: options.seriesName,
49
+ currency: asString(event.currency, "RON"),
50
+ language: options.language ?? "RO",
51
+ products: mapLineItems(event, options),
52
+ };
53
+ if (event.isDraft === true)
54
+ body.isDraft = true;
55
+ if (typeof event.dueDate === "string")
56
+ body.dueDate = event.dueDate;
57
+ if (typeof event.issueDate === "string")
58
+ body.issueDate = event.issueDate;
59
+ if (typeof event.deliveryDate === "string")
60
+ body.deliveryDate = event.deliveryDate;
61
+ if (typeof event.mentions === "string")
62
+ body.mentions = event.mentions;
63
+ if (typeof event.observations === "string")
64
+ body.observations = event.observations;
65
+ if (options.art311SpecialRegime) {
66
+ body.mentions = [
67
+ body.mentions,
68
+ "Regimul special de taxare - agentie de turism (Art. 311 Cod Fiscal)",
69
+ ]
70
+ .filter(Boolean)
71
+ .join("\n");
72
+ }
73
+ return body;
74
+ }
75
+ // --- helpers ---
76
+ function asString(value, fallback) {
77
+ if (typeof value === "string" && value.length > 0)
78
+ return value;
79
+ return fallback;
80
+ }
81
+ function asStringOrUndefined(value) {
82
+ if (typeof value === "string" && value.length > 0)
83
+ return value;
84
+ return undefined;
85
+ }
86
+ function asNumber(value, fallback) {
87
+ if (typeof value === "number" && !Number.isNaN(value))
88
+ return value;
89
+ return fallback;
90
+ }
@@ -0,0 +1,55 @@
1
+ import type { Plugin } from "@voyantjs/core";
2
+ import { type SmartbillClientOptions } from "./client.js";
3
+ import { mapVoyantInvoiceToSmartbill, type SmartbillMappingOptions } from "./mapping.js";
4
+ import type { VoyantInvoiceEvent } from "./types.js";
5
+ /**
6
+ * Event names the plugin subscribes to. Defaults match the
7
+ * `invoice.<action>` naming convention from the EventBus.
8
+ */
9
+ export interface SmartbillSyncEventNames {
10
+ issued?: string;
11
+ voided?: string;
12
+ syncRequested?: string;
13
+ }
14
+ /**
15
+ * Logger shape used to surface plugin errors without coupling to any specific
16
+ * runtime. Defaults to `console`.
17
+ */
18
+ export interface SmartbillLogger {
19
+ error: (message: string, meta?: unknown) => void;
20
+ info?: (message: string, meta?: unknown) => void;
21
+ }
22
+ /**
23
+ * Custom mapper from a Voyant invoice event to a SmartBill invoice body.
24
+ * When provided, replaces the default {@link mapVoyantInvoiceToSmartbill}.
25
+ */
26
+ export type SmartbillMapFn = (event: VoyantInvoiceEvent) => ReturnType<typeof mapVoyantInvoiceToSmartbill>;
27
+ export interface SmartbillPluginOptions extends SmartbillClientOptions, SmartbillMappingOptions {
28
+ /**
29
+ * Event names this plugin subscribes to.
30
+ * Defaults to `invoice.issued` / `invoice.voided` / `invoice.external.sync.requested`.
31
+ */
32
+ events?: SmartbillSyncEventNames;
33
+ /**
34
+ * Map a Voyant invoice event into a SmartBill invoice body.
35
+ * Defaults to the built-in {@link mapVoyantInvoiceToSmartbill}.
36
+ */
37
+ mapEvent?: SmartbillMapFn;
38
+ /** Override logger. Defaults to `console`. */
39
+ logger?: SmartbillLogger;
40
+ }
41
+ /**
42
+ * Build a Voyant {@link Plugin} that pushes invoice events to SmartBill
43
+ * for Romanian e-invoicing.
44
+ *
45
+ * The plugin subscribes to three events (configurable via
46
+ * {@link SmartbillPluginOptions.events}):
47
+ * - `invoice.issued` → create invoice in SmartBill
48
+ * - `invoice.voided` → cancel invoice in SmartBill
49
+ * - `invoice.external.sync.requested` → re-fetch payment status
50
+ *
51
+ * Errors are caught and logged — subscribers are fire-and-forget per the
52
+ * EventBus contract, so a SmartBill outage never blocks the emitter.
53
+ */
54
+ export declare function smartbillPlugin(options: SmartbillPluginOptions): Plugin;
55
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,gBAAgB,CAAA;AAExD,OAAO,EAAyB,KAAK,sBAAsB,EAAE,MAAM,aAAa,CAAA;AAChF,OAAO,EAAE,2BAA2B,EAAE,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAA;AACxF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAEpD;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;IAChD,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;CACjD;AAED;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,CAC3B,KAAK,EAAE,kBAAkB,KACtB,UAAU,CAAC,OAAO,2BAA2B,CAAC,CAAA;AAEnD,MAAM,WAAW,sBAAuB,SAAQ,sBAAsB,EAAE,uBAAuB;IAC7F;;;OAGG;IACH,MAAM,CAAC,EAAE,uBAAuB,CAAA;IAChC;;;OAGG;IACH,QAAQ,CAAC,EAAE,cAAc,CAAA;IACzB,8CAA8C;IAC9C,MAAM,CAAC,EAAE,eAAe,CAAA;CACzB;AASD;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,CA8GvE"}
@@ -0,0 +1,118 @@
1
+ import { createSmartbillClient } from "./client.js";
2
+ import { mapVoyantInvoiceToSmartbill } from "./mapping.js";
3
+ function coerceEvent(data) {
4
+ if (data == null || typeof data !== "object")
5
+ return null;
6
+ const maybe = data;
7
+ if (typeof maybe.id !== "string")
8
+ return null;
9
+ return maybe;
10
+ }
11
+ /**
12
+ * Build a Voyant {@link Plugin} that pushes invoice events to SmartBill
13
+ * for Romanian e-invoicing.
14
+ *
15
+ * The plugin subscribes to three events (configurable via
16
+ * {@link SmartbillPluginOptions.events}):
17
+ * - `invoice.issued` → create invoice in SmartBill
18
+ * - `invoice.voided` → cancel invoice in SmartBill
19
+ * - `invoice.external.sync.requested` → re-fetch payment status
20
+ *
21
+ * Errors are caught and logged — subscribers are fire-and-forget per the
22
+ * EventBus contract, so a SmartBill outage never blocks the emitter.
23
+ */
24
+ export function smartbillPlugin(options) {
25
+ const client = createSmartbillClient(options);
26
+ const logger = options.logger ?? console;
27
+ const mappingOptions = {
28
+ companyVatCode: options.companyVatCode,
29
+ seriesName: options.seriesName,
30
+ language: options.language,
31
+ isTaxIncluded: options.isTaxIncluded,
32
+ art311SpecialRegime: options.art311SpecialRegime,
33
+ };
34
+ const mapEvent = options.mapEvent ??
35
+ ((ev) => mapVoyantInvoiceToSmartbill(ev, mappingOptions));
36
+ const eventNames = {
37
+ issued: options.events?.issued ?? "invoice.issued",
38
+ voided: options.events?.voided ?? "invoice.voided",
39
+ syncRequested: options.events?.syncRequested ?? "invoice.external.sync.requested",
40
+ };
41
+ const subscribers = [
42
+ {
43
+ event: eventNames.issued,
44
+ handler: async (data) => {
45
+ const event = coerceEvent(data);
46
+ if (!event)
47
+ return;
48
+ try {
49
+ const body = mapEvent(event);
50
+ const result = await client.createInvoice(body);
51
+ logger.info?.(`[smartbill] invoice created: ${result.series}-${result.number} for ${event.id}`, result);
52
+ }
53
+ catch (err) {
54
+ logger.error(`[smartbill] createInvoice on "${eventNames.issued}" failed for ${event.id}`, err);
55
+ }
56
+ },
57
+ },
58
+ {
59
+ event: eventNames.voided,
60
+ handler: async (data) => {
61
+ const event = coerceEvent(data);
62
+ if (!event)
63
+ return;
64
+ try {
65
+ const seriesName = typeof event.externalSeriesName === "string"
66
+ ? event.externalSeriesName
67
+ : options.seriesName;
68
+ const number = typeof event.externalNumber === "string"
69
+ ? event.externalNumber
70
+ : typeof event.invoiceNumber === "string"
71
+ ? event.invoiceNumber
72
+ : undefined;
73
+ if (!number) {
74
+ logger.error(`[smartbill] cannot cancel invoice ${event.id}: missing external number`);
75
+ return;
76
+ }
77
+ await client.cancelInvoice(options.companyVatCode, seriesName, number);
78
+ logger.info?.(`[smartbill] invoice cancelled: ${seriesName}-${number} for ${event.id}`);
79
+ }
80
+ catch (err) {
81
+ logger.error(`[smartbill] cancelInvoice on "${eventNames.voided}" failed for ${event.id}`, err);
82
+ }
83
+ },
84
+ },
85
+ {
86
+ event: eventNames.syncRequested,
87
+ handler: async (data) => {
88
+ const event = coerceEvent(data);
89
+ if (!event)
90
+ return;
91
+ try {
92
+ const seriesName = typeof event.externalSeriesName === "string"
93
+ ? event.externalSeriesName
94
+ : options.seriesName;
95
+ const number = typeof event.externalNumber === "string"
96
+ ? event.externalNumber
97
+ : typeof event.invoiceNumber === "string"
98
+ ? event.invoiceNumber
99
+ : undefined;
100
+ if (!number) {
101
+ logger.error(`[smartbill] cannot sync invoice ${event.id}: missing external number`);
102
+ return;
103
+ }
104
+ const status = await client.getPaymentStatus(options.companyVatCode, seriesName, number);
105
+ logger.info?.(`[smartbill] payment status for ${seriesName}-${number}: ${status.status}`, status);
106
+ }
107
+ catch (err) {
108
+ logger.error(`[smartbill] getPaymentStatus on "${eventNames.syncRequested}" failed for ${event.id}`, err);
109
+ }
110
+ },
111
+ },
112
+ ];
113
+ return {
114
+ name: "smartbill",
115
+ version: "0.1.0",
116
+ subscribers,
117
+ };
118
+ }