kassza 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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -0
  3. package/agents/README.md +59 -0
  4. package/agents/api.md +206 -0
  5. package/agents/pitfalls.md +52 -0
  6. package/agents/recipes.md +217 -0
  7. package/agents/skills/kassza/SKILL.md +29 -0
  8. package/assets/logo-wordmark.svg +25 -0
  9. package/assets/logo.svg +19 -0
  10. package/dist/binary-B89HM03_.cjs +63 -0
  11. package/dist/binary-D0M9U2MD.js +34 -0
  12. package/dist/client-B9kbKKBf.d.cts +748 -0
  13. package/dist/client-zv4enyq7.d.ts +748 -0
  14. package/dist/cookie-stores/index.cjs +153 -0
  15. package/dist/cookie-stores/index.d.cts +63 -0
  16. package/dist/cookie-stores/index.d.ts +63 -0
  17. package/dist/cookie-stores/index.js +144 -0
  18. package/dist/create-BZd6CUO7.cjs +1160 -0
  19. package/dist/create-DDZaNlOz.js +939 -0
  20. package/dist/dates-D2XebOIg.js +34 -0
  21. package/dist/dates-DtHzwNU6.d.cts +7 -0
  22. package/dist/dates-DtHzwNU6.d.ts +7 -0
  23. package/dist/dates-PPxH0n5H.cjs +57 -0
  24. package/dist/errors-B0QJhUW1.cjs +302 -0
  25. package/dist/errors-DapdV5DK.js +273 -0
  26. package/dist/index-CYAGCdKJ.d.cts +56 -0
  27. package/dist/index-CYAGCdKJ.d.ts +56 -0
  28. package/dist/index.cjs +1406 -0
  29. package/dist/index.d.cts +8 -0
  30. package/dist/index.d.ts +8 -0
  31. package/dist/index.js +1394 -0
  32. package/dist/ipn/index.cjs +108 -0
  33. package/dist/ipn/index.d.cts +32 -0
  34. package/dist/ipn/index.d.ts +32 -0
  35. package/dist/ipn/index.js +101 -0
  36. package/dist/money/index.cjs +15 -0
  37. package/dist/money/index.d.cts +2 -0
  38. package/dist/money/index.d.ts +2 -0
  39. package/dist/money/index.js +2 -0
  40. package/dist/money-C9j7nBNP.js +258 -0
  41. package/dist/money-DkiGukAw.cjs +335 -0
  42. package/dist/session-CRGOuz-R.cjs +100 -0
  43. package/dist/session-Dm_45x8K.d.cts +11 -0
  44. package/dist/session-Dm_45x8K.d.ts +11 -0
  45. package/dist/session-OJMLGufT.js +77 -0
  46. package/dist/shared-CrxlxI8n.cjs +207 -0
  47. package/dist/shared-D6DLa4b7.js +100 -0
  48. package/dist/storage/fs.cjs +88 -0
  49. package/dist/storage/fs.d.cts +13 -0
  50. package/dist/storage/fs.d.ts +13 -0
  51. package/dist/storage/fs.js +87 -0
  52. package/dist/storage/index.cjs +643 -0
  53. package/dist/storage/index.d.cts +288 -0
  54. package/dist/storage/index.d.ts +288 -0
  55. package/dist/storage/index.js +619 -0
  56. package/dist/testing/index.cjs +409 -0
  57. package/dist/testing/index.d.cts +35 -0
  58. package/dist/testing/index.d.ts +35 -0
  59. package/dist/testing/index.js +407 -0
  60. package/dist/types-DVRgwcqg.d.cts +26 -0
  61. package/dist/types-DVRgwcqg.d.ts +26 -0
  62. package/dist/validators/index.cjs +296 -0
  63. package/dist/validators/index.d.cts +51 -0
  64. package/dist/validators/index.d.ts +51 -0
  65. package/dist/validators/index.js +278 -0
  66. package/llms.txt +16 -0
  67. package/package.json +151 -0
package/dist/index.js ADDED
@@ -0,0 +1,1394 @@
1
+ import { A as childBoolean, C as readHeader$1, D as throwIfTextError, E as throwIfHttpError, F as AGENT_ACTIONS, I as MAX_INVOICE_ATTACHMENTS, L as SZAMLAZZ_AGENT_URL, M as childText, N as findChild, O as throwIfXmlFailure, P as findChildren, S as readDocumentHeaders, T as throwIfHeaderError, _ as optionalEl, a as RECEIPT_XSD_BASE_URL, b as parseDoneText, c as requireReceiptNumber, d as presentText, f as resolveInvoice, g as el, h as buildXmlDocument, i as parseReceiptResponse, j as childNumber, k as unexpectedResponse, l as validateTemplate$1, m as TAXPAYER_TYPE_CODES, o as optionalText$1, p as INVOICE_TEMPLATES, r as createReceipt, s as receiptValidationError, u as optionalAgentDate$1, v as createAgentResponse, w as throwIfAnyError, x as parseResponseXml, y as looksLikeXml } from "./create-DDZaNlOz.js";
2
+ import { a as parseErrorCode, i as isSzamlazzError, n as SzamlazzError, r as createAgentError, t as AGENT_ERROR_CODES } from "./errors-DapdV5DK.js";
3
+ import { n as bytesToBase64, t as base64ToBytes } from "./binary-D0M9U2MD.js";
4
+ import { i as sessionKeyFor, n as memoryCookieStore, r as mergeSetCookies, t as SESSION_TTL_SECONDS } from "./session-OJMLGufT.js";
5
+ import { i as todayInBudapest, n as toAgentDate, r as toBudapestDate, t as addBudapestDays } from "./dates-D2XebOIg.js";
6
+ import { i as summarizeItems, s as formatVatRate } from "./money-C9j7nBNP.js";
7
+ const DEFAULT_SAFE_ATTEMPTS = 3;
8
+ const DEFAULT_RETRY_DELAY_MS = 1e3;
9
+ function readEnv(name) {
10
+ const value = (globalThis.process?.env)?.[name]?.trim();
11
+ return value ? value : void 0;
12
+ }
13
+ function configurationError(message) {
14
+ return new SzamlazzError(message, { category: "configuration" });
15
+ }
16
+ function resolveCredentials(options) {
17
+ const agentKey = options.agentKey?.trim() || (options.username ? void 0 : readEnv("SZAMLAZZ_AGENT_KEY"));
18
+ if (agentKey) {
19
+ if (agentKey !== agentKey.toLowerCase()) throw configurationError("Az Agent kulcs nagybetűt tartalmaz. A Számlázz.hu csak kisbetűs kulcsot fogad el, másold ki újra a kulcsot.");
20
+ return [el("szamlaagentkulcs", agentKey)];
21
+ }
22
+ if (options.username && options.password) return [el("felhasznalo", options.username), el("jelszo", options.password)];
23
+ throw configurationError("Hiányzik az Agent kulcs. Add meg az agentKey opciót, vagy állítsd be a SZAMLAZZ_AGENT_KEY környezeti változót.");
24
+ }
25
+ function toBlob(attachment) {
26
+ const type = attachment.contentType ?? "application/octet-stream";
27
+ if (attachment.content instanceof Blob) return attachment.content;
28
+ return new Blob([attachment.content], { type });
29
+ }
30
+ function buildFormData(request) {
31
+ const form = new FormData();
32
+ form.append(AGENT_ACTIONS[request.action], new Blob([request.xml], { type: "text/xml; charset=UTF-8" }), "request.xml");
33
+ request.attachments?.forEach((attachment, index) => {
34
+ form.append(`attachfile${index + 1}`, toBlob(attachment), attachment.filename);
35
+ });
36
+ return form;
37
+ }
38
+ function isAbortError(error) {
39
+ return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
40
+ }
41
+ function sleep(ms, signal) {
42
+ return new Promise((resolve, reject) => {
43
+ if (signal?.aborted) {
44
+ reject(signal.reason);
45
+ return;
46
+ }
47
+ const timer = setTimeout(() => {
48
+ signal?.removeEventListener("abort", onAbort);
49
+ resolve();
50
+ }, ms);
51
+ const onAbort = () => {
52
+ clearTimeout(timer);
53
+ reject(signal?.reason);
54
+ };
55
+ signal?.addEventListener("abort", onAbort, { once: true });
56
+ });
57
+ }
58
+ async function ignoreStoreFailure(operation) {
59
+ try {
60
+ return await operation();
61
+ } catch {
62
+ return;
63
+ }
64
+ }
65
+ function clampAttempts(value) {
66
+ if (value === void 0) return DEFAULT_SAFE_ATTEMPTS;
67
+ if (!Number.isInteger(value) || value < 1) throw configurationError(`A maxAttempts értéke legalább 1 egész szám legyen, kapott: ${value}`);
68
+ return Math.min(value, 5);
69
+ }
70
+ function createAgentContext(options = {}) {
71
+ const credentials = resolveCredentials(options);
72
+ const endpoint = options.endpoint ?? "https://www.szamlazz.hu/szamla/";
73
+ const fetchImpl = options.fetch ?? globalThis.fetch;
74
+ if (typeof fetchImpl !== "function") throw configurationError("Nem található fetch implementáció. Add meg a fetch opciót.");
75
+ const timeoutMs = options.timeoutMs ?? 6e4;
76
+ const safeAttempts = clampAttempts(options.maxAttempts);
77
+ const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
78
+ const cookieStore = options.cookieStore === false ? void 0 : options.cookieStore ?? memoryCookieStore();
79
+ const sessionKey = sessionKeyFor(credentials.map((node) => String(node.content)).join("|"));
80
+ const hooks = options.hooks ?? {};
81
+ async function send(request) {
82
+ const cookie = cookieStore ? await ignoreStoreFailure(() => cookieStore.get(sessionKey)) : void 0;
83
+ request.signal?.throwIfAborted();
84
+ const headers = new Headers({ Accept: "application/xml, application/pdf, text/plain, */*" });
85
+ if (cookie) headers.set("Cookie", cookie);
86
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
87
+ const signal = request.signal ? AbortSignal.any([request.signal, timeoutSignal]) : timeoutSignal;
88
+ let response;
89
+ try {
90
+ response = await fetchImpl(endpoint, {
91
+ method: "POST",
92
+ headers,
93
+ body: buildFormData(request),
94
+ signal
95
+ });
96
+ } catch (error) {
97
+ if (request.signal?.aborted) throw request.signal.reason;
98
+ if (timeoutSignal.aborted || isAbortError(error)) throw new SzamlazzError(`A Számlázz.hu nem válaszolt ${timeoutMs} ms alatt.`, {
99
+ category: "timeout",
100
+ action: request.action,
101
+ cause: error
102
+ });
103
+ throw new SzamlazzError("Hálózati hiba a Számlázz.hu elérésekor.", {
104
+ category: "network",
105
+ action: request.action,
106
+ cause: error
107
+ });
108
+ }
109
+ const body = new Uint8Array(await response.arrayBuffer());
110
+ if (cookieStore) {
111
+ const merged = mergeSetCookies(cookie, response.headers);
112
+ if (merged) await ignoreStoreFailure(() => cookieStore.set(sessionKey, merged, SESSION_TTL_SECONDS));
113
+ }
114
+ return createAgentResponse(request.action, response.status, response.headers, body);
115
+ }
116
+ async function resetSession() {
117
+ if (cookieStore) await ignoreStoreFailure(() => cookieStore.delete(sessionKey));
118
+ }
119
+ async function execute(request, parse) {
120
+ const maxAttempts = request.safeToRetry ? safeAttempts : 1;
121
+ for (let attempt = 1;; attempt++) {
122
+ const startedAt = Date.now();
123
+ hooks.onRequest?.({
124
+ action: request.action,
125
+ attempt
126
+ });
127
+ try {
128
+ const response = await send(request);
129
+ hooks.onResponse?.({
130
+ action: request.action,
131
+ attempt,
132
+ status: response.status,
133
+ durationMs: Date.now() - startedAt
134
+ });
135
+ return await parse(response);
136
+ } catch (error) {
137
+ if (!(error instanceof SzamlazzError)) throw error;
138
+ const willRetry = error.retryable && attempt < maxAttempts;
139
+ hooks.onError?.({
140
+ action: request.action,
141
+ attempt,
142
+ error,
143
+ willRetry
144
+ });
145
+ if (error.category === "auth") await resetSession();
146
+ if (!willRetry) throw error;
147
+ await sleep(retryDelayMs * 2 ** (attempt - 1), request.signal);
148
+ }
149
+ }
150
+ }
151
+ return {
152
+ credentials,
153
+ execute,
154
+ resetSession
155
+ };
156
+ }
157
+ //#endregion
158
+ //#region src/invoices/create-response.ts
159
+ function readRawResponse(response) {
160
+ throwIfAnyError(response);
161
+ const headers = readDocumentHeaders(response.headers);
162
+ const fromHeaders = {
163
+ number: headers.number,
164
+ netTotal: headers.netTotal,
165
+ grossTotal: headers.grossTotal,
166
+ outstanding: void 0,
167
+ buyerAccountUrl: headers.buyerAccountUrl,
168
+ pdf: void 0
169
+ };
170
+ if (response.isPdf) return {
171
+ ...fromHeaders,
172
+ pdf: response.body
173
+ };
174
+ if (looksLikeXml(response)) {
175
+ const root = parseResponseXml(response);
176
+ throwIfXmlFailure(root, response);
177
+ const pdfBase64 = childText(root, "pdf");
178
+ return {
179
+ number: childText(root, "szamlaszam") ?? headers.number,
180
+ netTotal: childNumber(root, "szamlanetto") ?? headers.netTotal,
181
+ grossTotal: childNumber(root, "szamlabrutto") ?? headers.grossTotal,
182
+ outstanding: childNumber(root, "kintlevoseg"),
183
+ buyerAccountUrl: childText(root, "vevoifiokurl") ?? headers.buyerAccountUrl,
184
+ pdf: pdfBase64 === void 0 ? void 0 : base64ToBytes(pdfBase64)
185
+ };
186
+ }
187
+ const done = parseDoneText(response.text());
188
+ if (done) return {
189
+ ...fromHeaders,
190
+ number: done.number ?? headers.number
191
+ };
192
+ if (headers.number !== void 0) return fromHeaders;
193
+ throw unexpectedResponse(response, "Számlaszámot vagy PDF-et vártunk.");
194
+ }
195
+ function totalsFor(raw, items) {
196
+ if (raw.netTotal !== void 0 && raw.grossTotal !== void 0) return {
197
+ netTotal: raw.netTotal,
198
+ grossTotal: raw.grossTotal
199
+ };
200
+ const computed = summarizeItems(items);
201
+ return {
202
+ netTotal: raw.netTotal ?? computed.netAmount,
203
+ grossTotal: raw.grossTotal ?? computed.grossAmount
204
+ };
205
+ }
206
+ function parseCreateInvoiceResponse(response, items = []) {
207
+ const raw = readRawResponse(response);
208
+ if (raw.number === void 0) throw unexpectedResponse(response, "A sikeres válaszból hiányzik a számlaszám.");
209
+ return {
210
+ number: raw.number,
211
+ ...totalsFor(raw, items),
212
+ outstanding: raw.outstanding,
213
+ buyerAccountUrl: raw.buyerAccountUrl,
214
+ pdf: raw.pdf,
215
+ items
216
+ };
217
+ }
218
+ function parseInvoicePreviewResponse(response, items = []) {
219
+ const raw = readRawResponse(response);
220
+ if (raw.pdf === void 0) throw unexpectedResponse(response, "Az előnézeti válaszból hiányzik a PDF.");
221
+ return {
222
+ pdf: raw.pdf,
223
+ ...totalsFor(raw, items),
224
+ items
225
+ };
226
+ }
227
+ //#endregion
228
+ //#region src/invoices/create-xml.ts
229
+ const INVOICE_XML_NAMESPACE = "http://www.szamlazz.hu/xmlszamla";
230
+ const INVOICE_XML_SCHEMA_LOCATION = "https://www.szamlazz.hu/szamla/docs/xsds/agent/xmlszamla.xsd";
231
+ const RESPONSE_VERSION_XML = 2;
232
+ function textEl(name, value) {
233
+ return optionalEl(name, presentText(value));
234
+ }
235
+ function settingsNode(credentials, invoice, preview) {
236
+ return el("beallitasok", [
237
+ ...credentials,
238
+ el("eszamla", invoice.eInvoice),
239
+ el("szamlaLetoltes", preview || invoice.downloadPdf),
240
+ el("valaszVerzio", RESPONSE_VERSION_XML),
241
+ textEl("aggregator", invoice.aggregator),
242
+ optionalEl("guardian", invoice.guardian),
243
+ optionalEl("cikkazoninvoice", invoice.articleIdentifierInvoice),
244
+ textEl("szamlaKulsoAzon", invoice.input.externalId)
245
+ ]);
246
+ }
247
+ function documentTypeNodes(invoice) {
248
+ const { input, type } = invoice;
249
+ return [
250
+ type === "advance" && el("elolegszamla", true),
251
+ type === "final" && el("vegszamla", true),
252
+ input.type === "final" && textEl("elolegSzamlaszam", input.advanceInvoiceNumber),
253
+ type === "corrective" && el("helyesbitoszamla", true),
254
+ input.type === "corrective" && textEl("helyesbitettSzamlaszam", input.correctedInvoiceNumber),
255
+ type === "proforma" && el("dijbekero", true),
256
+ type === "deliveryNote" && el("szallitolevel", true)
257
+ ];
258
+ }
259
+ function headerNode(invoice, preview) {
260
+ const { input } = invoice;
261
+ return el("fejlec", [
262
+ el("keltDatum", invoice.issueDate),
263
+ el("teljesitesDatum", invoice.fulfillmentDate),
264
+ el("fizetesiHataridoDatum", invoice.dueDate),
265
+ el("fizmod", invoice.paymentMethod),
266
+ el("penznem", invoice.currency),
267
+ el("szamlaNyelve", invoice.language),
268
+ textEl("megjegyzes", input.comment),
269
+ textEl("arfolyamBank", invoice.exchangeBank),
270
+ optionalEl("arfolyam", invoice.exchangeRate),
271
+ textEl("rendelesSzam", input.orderNumber),
272
+ textEl("dijbekeroSzamlaszam", input.proformaNumber),
273
+ ...documentTypeNodes(invoice),
274
+ textEl("logoExtra", invoice.logoExtra),
275
+ textEl("szamlaszamElotag", invoice.prefix),
276
+ optionalEl("fizetendoKorrekcio", input.paymentCorrection),
277
+ optionalEl("fizetve", input.paid),
278
+ optionalEl("arresAfa", input.marginVat),
279
+ optionalEl("eusAfa", invoice.euVat),
280
+ optionalEl("szamlaSablon", invoice.template),
281
+ preview && el("elonezetpdf", true),
282
+ optionalEl("simpleItems", invoice.simpleItems)
283
+ ]);
284
+ }
285
+ function sellerNode(seller) {
286
+ return el("elado", [
287
+ textEl("bank", seller.bank),
288
+ textEl("bankszamlaszam", seller.bankAccount),
289
+ textEl("emailReplyto", seller.emailReplyTo),
290
+ textEl("emailTargy", seller.emailSubject),
291
+ textEl("emailSzoveg", seller.emailText),
292
+ textEl("alairoNeve", seller.signatoryName)
293
+ ]);
294
+ }
295
+ function buyerLedgerNode(ledger) {
296
+ if (!ledger) return void 0;
297
+ return optionalEl("vevoFokonyv", [
298
+ optionalEl("konyvelesDatum", optionalAgentDate$1(ledger.bookingDate, "buyer.ledger.bookingDate")),
299
+ textEl("vevoAzonosito", ledger.buyerId),
300
+ textEl("vevoFokonyviSzam", ledger.ledgerAccount),
301
+ optionalEl("folyamatosTelj", ledger.continuousFulfillment),
302
+ optionalEl("elszDatumTol", optionalAgentDate$1(ledger.settlementPeriodStart, "buyer.ledger.settlementPeriodStart")),
303
+ optionalEl("elszDatumIg", optionalAgentDate$1(ledger.settlementPeriodEnd, "buyer.ledger.settlementPeriodEnd"))
304
+ ]);
305
+ }
306
+ function buyerNode(buyer, sendEmail) {
307
+ const taxpayerType = buyer.taxpayerType;
308
+ return el("vevo", [
309
+ el("nev", buyer.name),
310
+ textEl("orszag", buyer.country),
311
+ el("irsz", buyer.zip),
312
+ el("telepules", buyer.city),
313
+ el("cim", buyer.address),
314
+ textEl("email", buyer.email),
315
+ el("sendEmail", sendEmail),
316
+ optionalEl("adoalany", taxpayerType === void 0 ? void 0 : TAXPAYER_TYPE_CODES[taxpayerType]),
317
+ textEl("adoszam", buyer.taxNumber),
318
+ textEl("csoportazonosito", buyer.groupTaxNumber),
319
+ textEl("adoszamEU", buyer.euTaxNumber),
320
+ textEl("postazasiNev", buyer.postal?.name),
321
+ textEl("postazasiOrszag", buyer.postal?.country),
322
+ textEl("postazasiIrsz", buyer.postal?.zip),
323
+ textEl("postazasiTelepules", buyer.postal?.city),
324
+ textEl("postazasiCim", buyer.postal?.address),
325
+ buyerLedgerNode(buyer.ledger),
326
+ textEl("azonosito", buyer.identifier),
327
+ textEl("alairoNeve", buyer.signatoryName),
328
+ textEl("telefonszam", buyer.phone),
329
+ textEl("megjegyzes", buyer.comment)
330
+ ]);
331
+ }
332
+ function waybillNode(waybill) {
333
+ if (!waybill) return void 0;
334
+ const { transOFlex: tof, pickPackPoint: ppp, sprinter, mpl } = waybill;
335
+ return el("fuvarlevel", [
336
+ textEl("futarSzolgalat", waybill.courier),
337
+ textEl("vonalkod", waybill.barcode),
338
+ textEl("megjegyzes", waybill.comment),
339
+ tof && el("tof", [
340
+ textEl("azonosito", tof.id),
341
+ textEl("shipmentID", tof.shipmentId),
342
+ optionalEl("csomagszam", tof.packageCount),
343
+ textEl("countryCode", tof.countryCode),
344
+ textEl("zip", tof.zip),
345
+ textEl("service", tof.service)
346
+ ]),
347
+ ppp && el("ppp", [textEl("vonalkodPrefix", ppp.barcodePrefix), textEl("vonalkodPostfix", ppp.barcodePostfix)]),
348
+ sprinter && el("sprinter", [
349
+ textEl("azonosito", sprinter.id),
350
+ textEl("feladokod", sprinter.senderCode),
351
+ textEl("iranykod", sprinter.directionCode),
352
+ optionalEl("csomagszam", sprinter.packageCount),
353
+ textEl("vonalkodPostfix", sprinter.barcodePostfix),
354
+ textEl("szallitasiIdo", sprinter.deliveryTime)
355
+ ]),
356
+ mpl && el("mpl", [
357
+ el("vevokod", mpl.customerCode),
358
+ el("vonalkod", mpl.barcode),
359
+ el("tomeg", String(mpl.weight)),
360
+ textEl("kulonszolgaltatasok", mpl.services),
361
+ optionalEl("erteknyilvanitas", mpl.declaredValue)
362
+ ])
363
+ ]);
364
+ }
365
+ function itemLedgerNode(ledger, label) {
366
+ if (!ledger) return void 0;
367
+ return optionalEl("tetelFokonyv", [
368
+ textEl("gazdasagiEsem", ledger.economicEvent),
369
+ textEl("gazdasagiEsemAfa", ledger.vatEconomicEvent),
370
+ textEl("arbevetelFokonyviSzam", ledger.revenueLedgerAccount),
371
+ textEl("afaFokonyviSzam", ledger.vatLedgerAccount),
372
+ optionalEl("elszDatumTol", optionalAgentDate$1(ledger.settlementPeriodStart, `${label} settlementPeriodStart`)),
373
+ optionalEl("elszDatumIg", optionalAgentDate$1(ledger.settlementPeriodEnd, `${label} settlementPeriodEnd`))
374
+ ]);
375
+ }
376
+ function itemNode(item, index) {
377
+ const { input, amounts } = item;
378
+ return el("tetel", [
379
+ el("megnevezes", input.name),
380
+ textEl("azonosito", input.identifier),
381
+ el("mennyiseg", amounts.quantity),
382
+ el("mennyisegiEgyseg", item.unit),
383
+ el("nettoEgysegar", amounts.netUnitPrice),
384
+ el("afakulcs", formatVatRate(amounts.vat)),
385
+ optionalEl("arresAfaAlap", input.marginVatBase),
386
+ el("nettoErtek", amounts.netAmount),
387
+ el("afaErtek", amounts.vatAmount),
388
+ el("bruttoErtek", amounts.grossAmount),
389
+ textEl("megjegyzes", input.comment),
390
+ itemLedgerNode(input.ledger, `${index + 1}. tétel ledger`),
391
+ optionalEl("torloKod", input.dataDeletionCode)
392
+ ]);
393
+ }
394
+ function renderInvoiceXml(credentials, invoice, options = {}) {
395
+ const preview = options.preview === true;
396
+ return buildXmlDocument({
397
+ root: "xmlszamla",
398
+ namespace: INVOICE_XML_NAMESPACE,
399
+ schemaLocation: INVOICE_XML_SCHEMA_LOCATION,
400
+ children: [
401
+ settingsNode(credentials, invoice, preview),
402
+ headerNode(invoice, preview),
403
+ sellerNode(invoice.seller),
404
+ buyerNode(invoice.input.buyer, invoice.sendEmail),
405
+ waybillNode(invoice.input.waybill),
406
+ el("tetelek", invoice.items.map(itemNode))
407
+ ]
408
+ });
409
+ }
410
+ //#endregion
411
+ //#region src/invoices/create.ts
412
+ function buildRequest(ctx, invoice, preview, options) {
413
+ const xml = renderInvoiceXml(ctx.credentials, invoice, { preview });
414
+ const attachments = preview ? [] : invoice.attachments;
415
+ return {
416
+ action: "createInvoice",
417
+ xml,
418
+ signal: options.signal,
419
+ ...attachments.length > 0 ? { attachments } : {}
420
+ };
421
+ }
422
+ function itemsOf(invoice) {
423
+ return invoice.items.map((item) => item.amounts);
424
+ }
425
+ async function createInvoice(ctx, defaults, input, options = {}) {
426
+ const invoice = resolveInvoice(defaults, input, /* @__PURE__ */ new Date());
427
+ const items = itemsOf(invoice);
428
+ return ctx.execute(buildRequest(ctx, invoice, false, options), (response) => parseCreateInvoiceResponse(response, items));
429
+ }
430
+ async function previewInvoice(ctx, defaults, input, options = {}) {
431
+ const invoice = resolveInvoice(defaults, input, /* @__PURE__ */ new Date());
432
+ const items = itemsOf(invoice);
433
+ return ctx.execute(buildRequest(ctx, invoice, true, options), (response) => parseInvoicePreviewResponse(response, items));
434
+ }
435
+ //#endregion
436
+ //#region src/invoices/reference.ts
437
+ const AGENT_XSD_BASE_URL = "https://www.szamlazz.hu/szamla/docs/xsds/";
438
+ function validationError(message) {
439
+ return new SzamlazzError(message, { category: "validation" });
440
+ }
441
+ function requireText(value, message) {
442
+ const trimmed = typeof value === "string" ? value.trim() : "";
443
+ if (trimmed === "") throw validationError(message);
444
+ return trimmed;
445
+ }
446
+ function optionalText(value) {
447
+ const trimmed = value?.trim();
448
+ return trimmed ? trimmed : void 0;
449
+ }
450
+ function agentDate(input, field) {
451
+ try {
452
+ return toAgentDate(input);
453
+ } catch (error) {
454
+ const detail = error instanceof Error ? error.message : String(error);
455
+ throw new SzamlazzError(`Érvénytelen dátum (${field}): ${detail}`, {
456
+ category: "validation",
457
+ cause: error
458
+ });
459
+ }
460
+ }
461
+ function optionalAgentDate(input, field) {
462
+ return input === void 0 ? void 0 : agentDate(input, field);
463
+ }
464
+ const REFERENCE_KEYS = [
465
+ "invoiceNumber",
466
+ "orderNumber",
467
+ "externalId"
468
+ ];
469
+ const REFERENCE_HINT$1 = "Add meg a számlaszámot szövegként, vagy pontosan egyet ezek közül: { invoiceNumber }, { orderNumber }, { externalId }.";
470
+ function resolveInvoiceReference(reference) {
471
+ if (typeof reference === "string") return {
472
+ kind: "invoiceNumber",
473
+ value: requireText(reference, `Üres számlaszám. ${REFERENCE_HINT$1}`)
474
+ };
475
+ if (typeof reference !== "object" || reference === null) throw validationError(`Érvénytelen bizonylat-hivatkozás. ${REFERENCE_HINT$1}`);
476
+ const record = reference;
477
+ const present = REFERENCE_KEYS.filter((key) => record[key] !== void 0);
478
+ const [kind] = present;
479
+ if (kind === void 0 || present.length > 1) throw validationError(`Érvénytelen bizonylat-hivatkozás. ${REFERENCE_HINT$1}`);
480
+ return {
481
+ kind,
482
+ value: requireText(record[kind], `Üres ${kind} érték. ${REFERENCE_HINT$1}`)
483
+ };
484
+ }
485
+ function referenceValue(reference, kind) {
486
+ return reference.kind === kind ? reference.value : void 0;
487
+ }
488
+ function readNumericHeader(headers, name) {
489
+ const value = readHeader$1(headers, name);
490
+ if (value === void 0) return void 0;
491
+ const parsed = Number(value.replace(",", "."));
492
+ return Number.isFinite(parsed) ? parsed : void 0;
493
+ }
494
+ function headerSummary(response) {
495
+ const headers = readDocumentHeaders(response.headers);
496
+ return {
497
+ number: headers.number,
498
+ netTotal: headers.netTotal,
499
+ grossTotal: headers.grossTotal,
500
+ outstanding: readNumericHeader(response.headers, "szlahu_kintlevoseg"),
501
+ buyerAccountUrl: headers.buyerAccountUrl
502
+ };
503
+ }
504
+ function decodeResponsePdf(root, response) {
505
+ const encoded = childText(root, "pdf");
506
+ if (encoded === void 0) return void 0;
507
+ try {
508
+ return base64ToBytes(encoded);
509
+ } catch (error) {
510
+ throw new SzamlazzError("A válaszban kapott PDF nem érvényes base64.", {
511
+ category: "unexpected_response",
512
+ action: response.action,
513
+ httpStatus: response.status,
514
+ cause: error
515
+ });
516
+ }
517
+ }
518
+ function readInvoiceResultXml(root, response) {
519
+ const headers = headerSummary(response);
520
+ return {
521
+ number: childText(root, "szamlaszam") ?? headers.number,
522
+ netTotal: childNumber(root, "szamlanetto") ?? headers.netTotal,
523
+ grossTotal: childNumber(root, "szamlabrutto") ?? headers.grossTotal,
524
+ outstanding: childNumber(root, "kintlevoseg") ?? headers.outstanding,
525
+ buyerAccountUrl: childText(root, "vevoifiokurl") ?? headers.buyerAccountUrl,
526
+ pdf: decodeResponsePdf(root, response)
527
+ };
528
+ }
529
+ const INVOICE_RESULT_ROOT = "xmlszamlavalasz";
530
+ function parseInvoiceResult(response) {
531
+ throwIfHeaderError(response);
532
+ if (response.isPdf) return {
533
+ ...headerSummary(response),
534
+ pdf: response.body
535
+ };
536
+ throwIfTextError(response);
537
+ throwIfHttpError(response);
538
+ if (looksLikeXml(response)) {
539
+ const root = parseResponseXml(response);
540
+ throwIfXmlFailure(root, response);
541
+ if (root.name !== INVOICE_RESULT_ROOT || childText(root, "sikeres")?.toLowerCase() !== "true") throw unexpectedResponse(response, `${INVOICE_RESULT_ROOT} XML választ vártunk.`);
542
+ return readInvoiceResultXml(root, response);
543
+ }
544
+ const headers = headerSummary(response);
545
+ const done = parseDoneText(response.text());
546
+ if (done) return {
547
+ ...headers,
548
+ number: done.number ?? headers.number
549
+ };
550
+ if (headers.number !== void 0) return headers;
551
+ throw unexpectedResponse(response);
552
+ }
553
+ //#endregion
554
+ //#region src/invoices/get.ts
555
+ const INVOICE_DOCUMENT_TYPE_CODES = {
556
+ invoice: "SZ",
557
+ proforma: "D",
558
+ advance: "ES",
559
+ final: "VS",
560
+ corrective: "HS",
561
+ reversal: "SS",
562
+ deliveryNote: "SL"
563
+ };
564
+ function buildGetInvoiceXml(credentials, reference, query = {}) {
565
+ const resolved = resolveInvoiceReference(reference);
566
+ return buildXmlDocument({
567
+ root: "xmlszamlaxml",
568
+ namespace: "http://www.szamlazz.hu/xmlszamlaxml",
569
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentxml/xmlszamlaxml.xsd`,
570
+ children: [
571
+ ...credentials,
572
+ optionalEl("szamlaszam", referenceValue(resolved, "invoiceNumber")),
573
+ optionalEl("rendelesSzam", referenceValue(resolved, "orderNumber")),
574
+ optionalEl("pdf", query.includePdf),
575
+ optionalEl("szamlaKulsoAzon", referenceValue(resolved, "externalId"))
576
+ ]
577
+ });
578
+ }
579
+ var InvoiceReader = class {
580
+ response;
581
+ constructor(response) {
582
+ this.response = response;
583
+ }
584
+ missing(path) {
585
+ return unexpectedResponse(this.response, `Hiányzik a(z) <${path}> elem a számla XML-ből.`);
586
+ }
587
+ element(parent, name, path) {
588
+ const child = findChild(parent, name);
589
+ if (!child) throw this.missing(path);
590
+ return child;
591
+ }
592
+ text(parent, name, path) {
593
+ const value = childText(parent, name);
594
+ if (value === void 0) throw this.missing(`${path}/${name}`);
595
+ return value;
596
+ }
597
+ number(parent, name, path) {
598
+ const value = childNumber(parent, name);
599
+ if (value === void 0) throw this.missing(`${path}/${name}`);
600
+ return value;
601
+ }
602
+ };
603
+ function readAddress(element) {
604
+ if (!element) return void 0;
605
+ return {
606
+ name: childText(element, "nev"),
607
+ country: childText(element, "orszag"),
608
+ zip: childText(element, "irsz"),
609
+ city: childText(element, "telepules"),
610
+ address: childText(element, "cim")
611
+ };
612
+ }
613
+ function readSeller(root, reader) {
614
+ const seller = reader.element(root, "szallito", "szallito");
615
+ const bank = findChild(seller, "bank");
616
+ return {
617
+ id: childNumber(seller, "id"),
618
+ name: reader.text(seller, "nev", "szallito"),
619
+ address: readAddress(findChild(seller, "cim")),
620
+ postalAddress: readAddress(findChild(seller, "postacim")),
621
+ taxNumber: childText(seller, "adoszam"),
622
+ groupTaxNumber: childText(seller, "csoportazonosito"),
623
+ euTaxNumber: childText(seller, "adoszameu"),
624
+ bank: bank && {
625
+ name: childText(bank, "nev"),
626
+ accountNumber: childText(bank, "bankszamla")
627
+ }
628
+ };
629
+ }
630
+ const DOCUMENT_TYPES_BY_CODE = new Map(Object.entries(INVOICE_DOCUMENT_TYPE_CODES).map(([type, code]) => [code, type]));
631
+ const E_INVOICE_CODES = /* @__PURE__ */ new Set([2, 3]);
632
+ function readHeader(root, reader) {
633
+ const header = reader.element(root, "alap", "alap");
634
+ const typeCode = reader.text(header, "tipus", "alap");
635
+ const appearanceCode = childNumber(header, "eszamla");
636
+ return {
637
+ id: childNumber(header, "id"),
638
+ number: reader.text(header, "szamlaszam", "alap"),
639
+ economicEventId: childNumber(header, "gazdEsemAzon"),
640
+ sourceSystem: childNumber(header, "forras"),
641
+ registrationNumber: childText(header, "iktatoszam"),
642
+ type: DOCUMENT_TYPES_BY_CODE.get(typeCode) ?? "unknown",
643
+ typeCode,
644
+ eInvoice: appearanceCode !== void 0 && E_INVOICE_CODES.has(appearanceCode),
645
+ appearanceCode,
646
+ referencedInvoiceNumber: childText(header, "hivszamlaszam"),
647
+ referencedProformaNumber: childText(header, "hivdijbekszam"),
648
+ issueDate: reader.text(header, "kelt", "alap"),
649
+ fulfillmentDate: childText(header, "telj"),
650
+ dueDate: childText(header, "fizh"),
651
+ paymentMethod: childText(header, "fizmod"),
652
+ unifiedPaymentMethod: childText(header, "fizmodunified"),
653
+ cash: childBoolean(header, "keszpenz"),
654
+ orderNumber: childText(header, "rendelesszam"),
655
+ language: childText(header, "nyelv"),
656
+ currency: childText(header, "devizanem"),
657
+ exchangeBank: childText(header, "devizabank"),
658
+ exchangeRate: childNumber(header, "devizaarf"),
659
+ comment: childText(header, "megjegyzes"),
660
+ vatType: childText(header, "afatipus"),
661
+ cashAccounting: childBoolean(header, "penzforg"),
662
+ kata: childBoolean(header, "kata"),
663
+ kataLedger: childBoolean(header, "katafokonyv"),
664
+ email: childText(header, "email"),
665
+ test: childBoolean(header, "teszt"),
666
+ reversed: childBoolean(header, "sztornozott")
667
+ };
668
+ }
669
+ function readBuyerLedger(element) {
670
+ if (!element) return void 0;
671
+ return {
672
+ ledgerAccount: childText(element, "vevo"),
673
+ buyerId: childText(element, "vevoazon"),
674
+ bookingDate: childText(element, "datum"),
675
+ continuousFulfillment: childBoolean(element, "folyamatostelj"),
676
+ settlementPeriodStart: childText(element, "elszDatTol") ?? childText(element, "elszdattol"),
677
+ settlementPeriodEnd: childText(element, "elszDatIg") ?? childText(element, "elszdatig")
678
+ };
679
+ }
680
+ function readBuyer(root, reader) {
681
+ const buyer = reader.element(root, "vevo", "vevo");
682
+ return {
683
+ id: childNumber(buyer, "id"),
684
+ name: reader.text(buyer, "nev", "vevo"),
685
+ identifier: childText(buyer, "azonosito"),
686
+ address: readAddress(findChild(buyer, "cim")),
687
+ postalAddress: readAddress(findChild(buyer, "postacim")),
688
+ email: childText(buyer, "email"),
689
+ taxNumber: childText(buyer, "adoszam"),
690
+ groupTaxNumber: childText(buyer, "csoportazonosito"),
691
+ euTaxNumber: childText(buyer, "adoszameu"),
692
+ location: childNumber(buyer, "lokacio"),
693
+ privatePerson: childBoolean(buyer, "privatePersonIndicator"),
694
+ ledger: readBuyerLedger(findChild(buyer, "fokonyv"))
695
+ };
696
+ }
697
+ function readItemLedger(element) {
698
+ if (!element) return void 0;
699
+ return {
700
+ revenueLedgerAccount: childText(element, "arbevetel"),
701
+ vatLedgerAccount: childText(element, "afa"),
702
+ economicEvent: childText(element, "gazdasagiesemeny"),
703
+ vatEconomicEvent: childText(element, "gazdasagiesemenyafa"),
704
+ settlementPeriodStart: childText(element, "elszdattol"),
705
+ settlementPeriodEnd: childText(element, "elszdatig")
706
+ };
707
+ }
708
+ function readItem(item, reader) {
709
+ const path = "tetelek/tetel";
710
+ return {
711
+ name: reader.text(item, "nev", path),
712
+ identifier: childText(item, "azonosito"),
713
+ quantity: reader.number(item, "mennyiseg", path),
714
+ unit: childText(item, "mennyisegiegyseg"),
715
+ netUnitPrice: reader.number(item, "nettoegysegar", path),
716
+ vat: reader.number(item, "afakulcs", path),
717
+ vatCode: childText(item, "afatipus"),
718
+ netAmount: reader.number(item, "netto", path),
719
+ marginVatBase: childNumber(item, "arresafaalap"),
720
+ vatAmount: reader.number(item, "afa", path),
721
+ grossAmount: reader.number(item, "brutto", path),
722
+ comment: childText(item, "megjegyzes"),
723
+ position: childNumber(item, "sztetordering"),
724
+ ledger: readItemLedger(findChild(item, "fokonyv"))
725
+ };
726
+ }
727
+ function readLabels(element) {
728
+ return findChildren(element, "cimke").flatMap((label) => {
729
+ const value = label.text.trim();
730
+ return value === "" ? [] : [value];
731
+ });
732
+ }
733
+ function readFinancialItem(item, reader) {
734
+ const path = "qutetek/qutet";
735
+ return {
736
+ name: reader.text(item, "nev", path),
737
+ vat: reader.number(item, "afakulcs", path),
738
+ vatCode: childText(item, "afatipus"),
739
+ netAmount: reader.number(item, "netto", path),
740
+ vatAmount: reader.number(item, "afa", path),
741
+ grossAmount: reader.number(item, "brutto", path),
742
+ settlementPeriodStart: childText(item, "elszdattol"),
743
+ settlementPeriodEnd: childText(item, "elszdatig"),
744
+ vatDeduction: childNumber(item, "afalevon"),
745
+ labels: readLabels(findChild(item, "cimkek"))
746
+ };
747
+ }
748
+ function readTotals(root, reader) {
749
+ const totals = reader.element(root, "osszegek", "osszegek");
750
+ const total = reader.element(totals, "totalossz", "osszegek/totalossz");
751
+ const path = "osszegek/totalossz";
752
+ return {
753
+ netAmount: reader.number(total, "netto", path),
754
+ vatAmount: reader.number(total, "afa", path),
755
+ grossAmount: reader.number(total, "brutto", path),
756
+ byVat: findChildren(totals, "afakulcsossz").map((entry) => ({
757
+ vat: reader.number(entry, "afakulcs", "osszegek/afakulcsossz"),
758
+ vatCode: childText(entry, "afatipus"),
759
+ netAmount: reader.number(entry, "netto", "osszegek/afakulcsossz"),
760
+ vatAmount: reader.number(entry, "afa", "osszegek/afakulcsossz"),
761
+ grossAmount: reader.number(entry, "brutto", "osszegek/afakulcsossz")
762
+ }))
763
+ };
764
+ }
765
+ function readPayment(payment, reader) {
766
+ const path = "kifizetesek/kifizetes";
767
+ return {
768
+ date: reader.text(payment, "datum", path),
769
+ method: reader.text(payment, "jogcim", path),
770
+ amount: reader.number(payment, "osszeg", path),
771
+ comment: childText(payment, "megjegyzes"),
772
+ bankAccountNumber: childText(payment, "bankszamlaszam"),
773
+ bankTransactionId: childNumber(payment, "banktranzid"),
774
+ exchangeRate: childNumber(payment, "devizaarf")
775
+ };
776
+ }
777
+ function parseInvoiceDetailsXml(root, response) {
778
+ const reader = new InvoiceReader(response);
779
+ return {
780
+ seller: readSeller(root, reader),
781
+ header: readHeader(root, reader),
782
+ buyer: readBuyer(root, reader),
783
+ items: findChildren(findChild(root, "tetelek"), "tetel").map((item) => readItem(item, reader)),
784
+ financialItems: findChildren(findChild(root, "qutetek"), "qutet").map((item) => readFinancialItem(item, reader)),
785
+ labels: readLabels(findChild(root, "cimkek")),
786
+ totals: readTotals(root, reader),
787
+ payments: findChildren(findChild(root, "kifizetesek"), "kifizetes").map((payment) => readPayment(payment, reader)),
788
+ pdf: decodeResponsePdf(root, response)
789
+ };
790
+ }
791
+ function parseGetInvoiceResponse(response) {
792
+ throwIfHeaderError(response);
793
+ throwIfTextError(response);
794
+ throwIfHttpError(response);
795
+ const root = parseResponseXml(response);
796
+ throwIfXmlFailure(root, response);
797
+ if (root.name !== "szamla") throw unexpectedResponse(response, "A számla XML (<szamla>) helyett más válasz érkezett.");
798
+ return parseInvoiceDetailsXml(root, response);
799
+ }
800
+ async function getInvoice(ctx, reference, query = {}, options = {}) {
801
+ const xml = buildGetInvoiceXml(ctx.credentials, reference, query);
802
+ return ctx.execute({
803
+ action: "getInvoiceXml",
804
+ xml,
805
+ signal: options.signal,
806
+ safeToRetry: true
807
+ }, parseGetInvoiceResponse);
808
+ }
809
+ function normalizeRegisterInput(input) {
810
+ const payments = "payments" in input ? input.payments : [{
811
+ amount: input.amount,
812
+ method: input.method ?? "átutalás",
813
+ date: input.date,
814
+ description: input.description
815
+ }];
816
+ if (!Array.isArray(payments) || payments.length === 0) throw validationError("Adj meg legalább egy befizetést (payments). A korábbi befizetések törléséhez a clearPayments függvényt használd.");
817
+ if (payments.length > 5) throw validationError(`Egy kérésben legfeljebb 5 befizetés rögzíthető, kapott: ${payments.length}.`);
818
+ return {
819
+ invoiceNumber: input.invoiceNumber,
820
+ taxNumber: input.taxNumber,
821
+ additive: input.additive ?? true,
822
+ payments
823
+ };
824
+ }
825
+ function normalizeClearInput(input) {
826
+ const target = typeof input === "string" ? { invoiceNumber: input } : input;
827
+ return {
828
+ invoiceNumber: target.invoiceNumber,
829
+ taxNumber: target.taxNumber,
830
+ additive: false,
831
+ payments: []
832
+ };
833
+ }
834
+ function paymentNode(payment, index) {
835
+ const position = index + 1;
836
+ if (typeof payment.amount !== "number" || !Number.isFinite(payment.amount)) throw validationError(`A(z) ${position}. befizetés összege (amount) nem véges szám.`);
837
+ return el("kifizetes", [
838
+ el("datum", payment.date === void 0 ? todayInBudapest() : agentDate(payment.date, "date")),
839
+ el("jogcim", requireText(payment.method, `Add meg a(z) ${position}. befizetés módját (method).`)),
840
+ el("osszeg", payment.amount),
841
+ optionalEl("leiras", optionalText(payment.description))
842
+ ]);
843
+ }
844
+ function buildPaymentXml(credentials, request) {
845
+ const invoiceNumber = requireText(request.invoiceNumber, "Add meg a számla számát (invoiceNumber), amelyhez a befizetés tartozik.");
846
+ return buildXmlDocument({
847
+ root: "xmlszamlakifiz",
848
+ namespace: "http://www.szamlazz.hu/xmlszamlakifiz",
849
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentkifiz/xmlszamlakifiz.xsd`,
850
+ children: [el("beallitasok", [
851
+ ...credentials,
852
+ el("szamlaszam", invoiceNumber),
853
+ optionalEl("adoszam", optionalText(request.taxNumber)),
854
+ el("additiv", request.additive),
855
+ el("valaszVerzio", 2)
856
+ ]), ...request.payments.map(paymentNode)]
857
+ });
858
+ }
859
+ function parseRegisterPaymentResponse(response, invoiceNumber) {
860
+ const result = parseInvoiceResult(response);
861
+ return {
862
+ invoiceNumber: result.number ?? invoiceNumber.trim(),
863
+ netTotal: result.netTotal,
864
+ grossTotal: result.grossTotal,
865
+ outstanding: result.outstanding,
866
+ buyerAccountUrl: result.buyerAccountUrl
867
+ };
868
+ }
869
+ function sendPaymentRequest(ctx, request, options) {
870
+ const xml = buildPaymentXml(ctx.credentials, request);
871
+ return ctx.execute({
872
+ action: "registerPayment",
873
+ xml,
874
+ signal: options.signal,
875
+ safeToRetry: !request.additive
876
+ }, (response) => parseRegisterPaymentResponse(response, request.invoiceNumber));
877
+ }
878
+ async function registerPayment(ctx, input, options = {}) {
879
+ return sendPaymentRequest(ctx, normalizeRegisterInput(input), options);
880
+ }
881
+ async function clearPayments(ctx, input, options = {}) {
882
+ return sendPaymentRequest(ctx, normalizeClearInput(input), options);
883
+ }
884
+ //#endregion
885
+ //#region src/invoices/pdf.ts
886
+ function buildInvoicePdfXml(credentials, reference) {
887
+ const resolved = resolveInvoiceReference(reference);
888
+ return buildXmlDocument({
889
+ root: "xmlszamlapdf",
890
+ namespace: "http://www.szamlazz.hu/xmlszamlapdf",
891
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentpdf/xmlszamlapdf.xsd`,
892
+ children: [
893
+ ...credentials,
894
+ optionalEl("szamlaszam", referenceValue(resolved, "invoiceNumber")),
895
+ optionalEl("rendelesSzam", referenceValue(resolved, "orderNumber")),
896
+ el("valaszVerzio", 2),
897
+ optionalEl("szamlaKulsoAzon", referenceValue(resolved, "externalId"))
898
+ ]
899
+ });
900
+ }
901
+ function parseInvoicePdfResponse(response) {
902
+ const { pdf, ...rest } = parseInvoiceResult(response);
903
+ if (pdf === void 0 || pdf.length === 0) throw unexpectedResponse(response, "A válasz nem tartalmaz PDF-et.");
904
+ return {
905
+ ...rest,
906
+ pdf
907
+ };
908
+ }
909
+ async function getInvoicePdf(ctx, reference, options = {}) {
910
+ const xml = buildInvoicePdfXml(ctx.credentials, reference);
911
+ return ctx.execute({
912
+ action: "getInvoicePdf",
913
+ xml,
914
+ signal: options.signal,
915
+ safeToRetry: true
916
+ }, parseInvoicePdfResponse);
917
+ }
918
+ const RESPONSE_ROOTS = /* @__PURE__ */ new Set(["xmlszamladbkdelvalasz", "xmlszamlavalasz"]);
919
+ const REFERENCE_HINT = "Add meg a díjbekérő számát szövegként, vagy pontosan egyet ezek közül: { proformaNumber }, { orderNumber }.";
920
+ function resolveProformaReference(reference) {
921
+ if (typeof reference === "string") return { proformaNumber: requireText(reference, `Üres díjbekérőszám. ${REFERENCE_HINT}`) };
922
+ if (typeof reference !== "object" || reference === null) throw validationError(`Érvénytelen díjbekérő-hivatkozás. ${REFERENCE_HINT}`);
923
+ const record = reference;
924
+ const hasNumber = record.proformaNumber !== void 0;
925
+ if (hasNumber === (record.orderNumber !== void 0)) throw validationError(`Érvénytelen díjbekérő-hivatkozás. ${REFERENCE_HINT}`);
926
+ return hasNumber ? { proformaNumber: requireText(record.proformaNumber, `Üres proformaNumber. ${REFERENCE_HINT}`) } : { orderNumber: requireText(record.orderNumber, `Üres orderNumber. ${REFERENCE_HINT}`) };
927
+ }
928
+ function buildDeleteProformaXml(credentials, reference) {
929
+ const resolved = resolveProformaReference(reference);
930
+ return buildXmlDocument({
931
+ root: "xmlszamladbkdel",
932
+ namespace: "http://www.szamlazz.hu/xmlszamladbkdel",
933
+ schemaLocation: "http://www.szamlazz.hu/docs/xsds/szamladbkdel/xmlszamladbkdel.xsd",
934
+ children: [el("beallitasok", [...credentials]), el("fejlec", [optionalEl("szamlaszam", resolved.proformaNumber), optionalEl("rendelesszam", resolved.orderNumber)])]
935
+ });
936
+ }
937
+ function withProformaCategory(error) {
938
+ if (!(error instanceof SzamlazzError) || error.code !== 335) return error;
939
+ return new SzamlazzError(error.message, {
940
+ category: "not_found",
941
+ code: error.code,
942
+ hint: "A díjbekérő nem létezik, vagy már törölték.",
943
+ action: error.action,
944
+ httpStatus: error.httpStatus,
945
+ rawResponse: error.rawResponse,
946
+ cause: error
947
+ });
948
+ }
949
+ function parseDeleteProformaResponse(response) {
950
+ try {
951
+ throwIfHeaderError(response);
952
+ throwIfTextError(response);
953
+ throwIfHttpError(response);
954
+ const root = parseResponseXml(response);
955
+ throwIfXmlFailure(root, response);
956
+ if (!RESPONSE_ROOTS.has(root.name) || childText(root, "sikeres")?.toLowerCase() !== "true") throw unexpectedResponse(response, "xmlszamladbkdelvalasz XML választ vártunk.");
957
+ } catch (error) {
958
+ throw withProformaCategory(error);
959
+ }
960
+ }
961
+ async function deleteProforma(ctx, reference, options = {}) {
962
+ const xml = buildDeleteProformaXml(ctx.credentials, reference);
963
+ await ctx.execute({
964
+ action: "deleteProforma",
965
+ xml,
966
+ signal: options.signal
967
+ }, parseDeleteProformaResponse);
968
+ }
969
+ const templates = new Set(INVOICE_TEMPLATES);
970
+ function normalizeInput$2(input) {
971
+ return typeof input === "string" ? { invoiceNumber: input } : input;
972
+ }
973
+ function validateTemplate(template) {
974
+ if (template === void 0 || templates.has(template)) return template;
975
+ throw validationError(`Ismeretlen számlasablon: ${String(template)}. Lehetséges értékek: ${INVOICE_TEMPLATES.join(", ")}.`);
976
+ }
977
+ function buildReverseInvoiceXml(credentials, input) {
978
+ const options = normalizeInput$2(input);
979
+ const invoiceNumber = requireText(options.invoiceNumber, "Add meg a sztornózandó számla számát (invoiceNumber).");
980
+ const email = options.email;
981
+ const buyer = options.buyer;
982
+ return buildXmlDocument({
983
+ root: "xmlszamlast",
984
+ namespace: "http://www.szamlazz.hu/xmlszamlast",
985
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentst/xmlszamlast.xsd`,
986
+ children: [
987
+ el("beallitasok", [
988
+ ...credentials,
989
+ el("eszamla", options.eInvoice ?? false),
990
+ el("szamlaLetoltes", options.downloadPdf ?? true),
991
+ el("valaszVerzio", 2),
992
+ optionalEl("szamlaKulsoAzon", optionalText(options.externalId))
993
+ ]),
994
+ el("fejlec", [
995
+ el("szamlaszam", invoiceNumber),
996
+ optionalEl("keltDatum", optionalAgentDate(options.issueDate, "issueDate")),
997
+ optionalEl("teljesitesDatum", optionalAgentDate(options.fulfillmentDate, "fulfillmentDate")),
998
+ optionalEl("megjegyzes", optionalText(options.comment)),
999
+ el("tipus", "SS"),
1000
+ optionalEl("szamlaSablon", validateTemplate(options.template))
1001
+ ]),
1002
+ optionalEl("elado", [
1003
+ optionalEl("emailReplyto", optionalText(email?.replyTo)),
1004
+ optionalEl("emailTargy", optionalText(email?.subject)),
1005
+ optionalEl("emailSzoveg", optionalText(email?.text))
1006
+ ]),
1007
+ optionalEl("vevo", [
1008
+ optionalEl("email", optionalText(buyer?.email)),
1009
+ optionalEl("adoszam", optionalText(buyer?.taxNumber)),
1010
+ optionalEl("adoszamEU", optionalText(buyer?.euTaxNumber))
1011
+ ])
1012
+ ]
1013
+ });
1014
+ }
1015
+ function parseReverseInvoiceResponse(response, originalInvoiceNumber) {
1016
+ const result = parseInvoiceResult(response);
1017
+ if (result.number === void 0) throw unexpectedResponse(response, "A válaszban nincs sztornó számlaszám.");
1018
+ if (originalInvoiceNumber !== void 0 && result.number === originalInvoiceNumber.trim()) throw new SzamlazzError(`A(z) ${result.number} bizonylat nem lett sztornózva: a Számlázz.hu az eredeti bizonylatot adta vissza.`, {
1019
+ category: "validation",
1020
+ action: response.action,
1021
+ httpStatus: response.status,
1022
+ hint: "Díjbekérő és szállítólevél nem sztornózható. Díjbekérőt a deleteProforma függvénnyel törölhetsz."
1023
+ });
1024
+ return {
1025
+ ...result,
1026
+ number: result.number
1027
+ };
1028
+ }
1029
+ async function reverseInvoice(ctx, input, options = {}) {
1030
+ const invoiceNumber = normalizeInput$2(input).invoiceNumber;
1031
+ const xml = buildReverseInvoiceXml(ctx.credentials, input);
1032
+ return ctx.execute({
1033
+ action: "reverseInvoice",
1034
+ xml,
1035
+ signal: options.signal
1036
+ }, (response) => parseReverseInvoiceResponse(response, invoiceNumber));
1037
+ }
1038
+ //#endregion
1039
+ //#region src/receipts/get.ts
1040
+ const GET_RECEIPT_NAMESPACE = "http://www.szamlazz.hu/xmlnyugtaget";
1041
+ function normalizeInput$1(input) {
1042
+ return typeof input === "string" ? { receiptNumber: input } : input;
1043
+ }
1044
+ function resolveIdentifier(input) {
1045
+ const receiptNumber = optionalText$1(input.receiptNumber);
1046
+ const orderNumber = optionalText$1(input.orderNumber);
1047
+ if (receiptNumber === void 0 && orderNumber === void 0) throw receiptValidationError("A nyugta lekérdezéséhez add meg a nyugtaszámot (receiptNumber) vagy a rendelésszámot (orderNumber).");
1048
+ if (receiptNumber !== void 0 && orderNumber !== void 0) throw receiptValidationError("A nyugta lekérdezéséhez a nyugtaszám (receiptNumber) és a rendelésszám (orderNumber) közül csak az egyiket add meg.");
1049
+ return {
1050
+ receiptNumber,
1051
+ orderNumber
1052
+ };
1053
+ }
1054
+ function buildGetReceiptXml(credentials, input) {
1055
+ const normalized = normalizeInput$1(input);
1056
+ const { receiptNumber, orderNumber } = resolveIdentifier(normalized);
1057
+ return buildXmlDocument({
1058
+ root: "xmlnyugtaget",
1059
+ namespace: GET_RECEIPT_NAMESPACE,
1060
+ schemaLocation: `${RECEIPT_XSD_BASE_URL}nyugtaget/xmlnyugtaget.xsd`,
1061
+ children: [el("beallitasok", [...credentials, el("pdfLetoltes", normalized.downloadPdf ?? true)]), el("fejlec", [
1062
+ optionalEl("nyugtaszam", receiptNumber),
1063
+ optionalEl("rendelesSzam", orderNumber),
1064
+ optionalEl("hivasAzonosito", optionalText$1(normalized.callId)),
1065
+ optionalEl("pdfSablon", validateTemplate$1(normalized.template))
1066
+ ])]
1067
+ });
1068
+ }
1069
+ function getReceipt(ctx, input, options = {}) {
1070
+ const xml = buildGetReceiptXml(ctx.credentials, input);
1071
+ return ctx.execute({
1072
+ action: "getReceipt",
1073
+ xml,
1074
+ signal: options.signal,
1075
+ safeToRetry: true
1076
+ }, parseReceiptResponse);
1077
+ }
1078
+ //#endregion
1079
+ //#region src/receipts/reverse.ts
1080
+ const REVERSE_RECEIPT_NAMESPACE = "http://www.szamlazz.hu/xmlnyugtast";
1081
+ function normalizeInput(input) {
1082
+ return typeof input === "string" ? { receiptNumber: input } : input;
1083
+ }
1084
+ function buildReverseReceiptXml(credentials, input) {
1085
+ const normalized = normalizeInput(input);
1086
+ return buildXmlDocument({
1087
+ root: "xmlnyugtast",
1088
+ namespace: REVERSE_RECEIPT_NAMESPACE,
1089
+ schemaLocation: `${RECEIPT_XSD_BASE_URL}nyugtast/xmlnyugtast.xsd`,
1090
+ children: [el("beallitasok", [...credentials, el("pdfLetoltes", normalized.downloadPdf ?? true)]), el("fejlec", [
1091
+ el("nyugtaszam", requireReceiptNumber(normalized.receiptNumber)),
1092
+ optionalEl("pdfSablon", validateTemplate$1(normalized.template)),
1093
+ optionalEl("hivasAzonosito", optionalText$1(normalized.callId))
1094
+ ])]
1095
+ });
1096
+ }
1097
+ function reverseReceipt(ctx, input, options = {}) {
1098
+ const normalized = normalizeInput(input);
1099
+ const xml = buildReverseReceiptXml(ctx.credentials, normalized);
1100
+ return ctx.execute({
1101
+ action: "reverseReceipt",
1102
+ xml,
1103
+ signal: options.signal,
1104
+ safeToRetry: optionalText$1(normalized.callId) !== void 0
1105
+ }, parseReceiptResponse);
1106
+ }
1107
+ //#endregion
1108
+ //#region src/receipts/send.ts
1109
+ const SEND_RECEIPT_NAMESPACE = "http://www.szamlazz.hu/xmlnyugtasend";
1110
+ const EMAIL_PATTERN = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
1111
+ function isValidEmail(value) {
1112
+ return EMAIL_PATTERN.test(value);
1113
+ }
1114
+ function assertEmail(value, field) {
1115
+ if (!isValidEmail(value)) throw receiptValidationError(`Érvénytelen e-mail cím a(z) ${field} mezőben: ${value}`);
1116
+ return value;
1117
+ }
1118
+ function normalizeEmails(emails) {
1119
+ const list = (typeof emails === "string" ? [emails] : [...emails]).flatMap((entry) => entry.split(/[,;]/)).map((entry) => entry.trim()).filter((entry) => entry !== "");
1120
+ if (list.length === 0) throw receiptValidationError("Adj meg legalább egy címzett e-mail címet (emails).");
1121
+ return list.map((email) => assertEmail(email, "emails"));
1122
+ }
1123
+ function buildSendReceiptXml(credentials, input) {
1124
+ const receiptNumber = requireReceiptNumber(input.receiptNumber);
1125
+ const emails = normalizeEmails(input.emails);
1126
+ const replyTo = optionalText$1(input.replyTo);
1127
+ if (replyTo !== void 0) assertEmail(replyTo, "replyTo");
1128
+ return buildXmlDocument({
1129
+ root: "xmlnyugtasend",
1130
+ namespace: SEND_RECEIPT_NAMESPACE,
1131
+ schemaLocation: `${RECEIPT_XSD_BASE_URL}nyugtasend/xmlnyugtasend.xsd`,
1132
+ children: [
1133
+ el("beallitasok", credentials),
1134
+ el("fejlec", [el("nyugtaszam", receiptNumber)]),
1135
+ el("emailKuldes", [
1136
+ el("email", emails.join(",")),
1137
+ optionalEl("emailReplyto", replyTo),
1138
+ el("emailTargy", optionalText$1(input.subject) ?? `Nyugta ${receiptNumber}`),
1139
+ optionalEl("emailSzoveg", input.text?.trim() ? input.text : void 0)
1140
+ ])
1141
+ ]
1142
+ });
1143
+ }
1144
+ function parseSendReceiptResponse(response) {
1145
+ throwIfHeaderError(response);
1146
+ throwIfTextError(response);
1147
+ if (!looksLikeXml(response)) {
1148
+ throwIfHttpError(response);
1149
+ if (parseDoneText(response.text())) return;
1150
+ throw unexpectedResponse(response, "XML választ vártunk a nyugta kiküldésére.");
1151
+ }
1152
+ const root = parseResponseXml(response);
1153
+ throwIfXmlFailure(root, response);
1154
+ if (childBoolean(root, "sikeres") !== true) {
1155
+ throwIfHttpError(response);
1156
+ throw unexpectedResponse(response, "A válasz nem jelez sikeres kiküldést.");
1157
+ }
1158
+ }
1159
+ function sendReceipt(ctx, input, options = {}) {
1160
+ const xml = buildSendReceiptXml(ctx.credentials, input);
1161
+ return ctx.execute({
1162
+ action: "sendReceipt",
1163
+ xml,
1164
+ signal: options.signal
1165
+ }, parseSendReceiptResponse);
1166
+ }
1167
+ //#endregion
1168
+ //#region src/taxpayer/address.ts
1169
+ const ROMAN_NUMERAL = /^[IVX]{1,5}\.?$/;
1170
+ function isShouting(value) {
1171
+ return value === value.toUpperCase() && value !== value.toLowerCase();
1172
+ }
1173
+ function capitalizeWord(word) {
1174
+ if (ROMAN_NUMERAL.test(word)) return word;
1175
+ return word.split("-").map((part) => part.toLowerCase().replace(/\p{L}/u, (letter) => letter.toUpperCase())).join("-");
1176
+ }
1177
+ function toReadableName(value) {
1178
+ if (value === void 0 || !isShouting(value)) return value;
1179
+ return value.split(" ").map(capitalizeWord).join(" ");
1180
+ }
1181
+ function toLowerIfShouting(value) {
1182
+ return value !== void 0 && isShouting(value) ? value.toLowerCase() : value;
1183
+ }
1184
+ function withOrdinalDot(value) {
1185
+ if (value === void 0) return void 0;
1186
+ return /^\d+$/.test(value) ? `${value}.` : value;
1187
+ }
1188
+ function joinParts(parts) {
1189
+ return parts.filter((part) => part !== void 0 && part !== "").join(" ");
1190
+ }
1191
+ function formatAddress(address) {
1192
+ return [
1193
+ joinParts([address.postalCode, address.city]),
1194
+ joinParts([
1195
+ address.street,
1196
+ address.publicPlaceCategory,
1197
+ withOrdinalDot(address.number),
1198
+ address.building === void 0 ? void 0 : `${address.building} ép.`,
1199
+ address.staircase === void 0 ? void 0 : `${withOrdinalDot(address.staircase)} lh.`,
1200
+ address.floor === void 0 ? void 0 : `${withOrdinalDot(address.floor)} em.`,
1201
+ address.door === void 0 ? void 0 : `${withOrdinalDot(address.door)} ajtó`
1202
+ ]),
1203
+ address.lotNumber === void 0 ? void 0 : `hrsz. ${address.lotNumber}`,
1204
+ address.countryCode === "" || address.countryCode === "HU" ? void 0 : address.countryCode
1205
+ ].filter((part) => part !== void 0 && part !== "").join(", ");
1206
+ }
1207
+ function readDetailedAddress(element) {
1208
+ return {
1209
+ countryCode: childText(element, "countryCode"),
1210
+ region: childText(element, "region"),
1211
+ postalCode: childText(element, "postalCode"),
1212
+ city: childText(element, "city"),
1213
+ streetName: childText(element, "streetName"),
1214
+ publicPlaceCategory: childText(element, "publicPlaceCategory"),
1215
+ number: childText(element, "number"),
1216
+ building: childText(element, "building"),
1217
+ staircase: childText(element, "staircase"),
1218
+ floor: childText(element, "floor"),
1219
+ door: childText(element, "door"),
1220
+ lotNumber: childText(element, "lotNumber")
1221
+ };
1222
+ }
1223
+ function parseTaxpayerAddress(item) {
1224
+ const raw = readDetailedAddress(findChild(item, "taxpayerAddress"));
1225
+ const address = {
1226
+ type: childText(item, "taxpayerAddressType")?.toUpperCase() ?? "",
1227
+ countryCode: raw.countryCode?.toUpperCase() ?? "",
1228
+ region: toReadableName(raw.region),
1229
+ postalCode: raw.postalCode ?? "",
1230
+ city: toReadableName(raw.city) ?? "",
1231
+ street: toReadableName(raw.streetName),
1232
+ publicPlaceCategory: toLowerIfShouting(raw.publicPlaceCategory),
1233
+ number: raw.number,
1234
+ building: raw.building,
1235
+ staircase: raw.staircase,
1236
+ floor: raw.floor,
1237
+ door: raw.door,
1238
+ lotNumber: raw.lotNumber
1239
+ };
1240
+ return {
1241
+ ...address,
1242
+ formatted: formatAddress(address),
1243
+ raw
1244
+ };
1245
+ }
1246
+ //#endregion
1247
+ //#region src/taxpayer/query-taxpayer.ts
1248
+ const TAXPAYER_NAMESPACE = "http://www.szamlazz.hu/xmltaxpayer";
1249
+ const TAXPAYER_SCHEMA_LOCATION = "http://www.szamlazz.hu/docs/xsds/agent/xmltaxpayer.xsd";
1250
+ function toTaxpayerId(taxNumber) {
1251
+ const digits = typeof taxNumber === "string" ? taxNumber.replace(/[\s-]+/g, "").replace(/^HU/i, "") : "";
1252
+ if (!/^(?:\d{8}|\d{11})$/.test(digits)) throw new SzamlazzError(`Érvénytelen adószám: "${String(taxNumber)}". Add meg a 8 jegyű törzsszámot vagy a 11 jegyű adószámot (pl. 12345678-2-42).`, {
1253
+ category: "validation",
1254
+ action: "queryTaxpayer"
1255
+ });
1256
+ return digits.slice(0, 8);
1257
+ }
1258
+ function buildQueryTaxpayerXml(credentials, taxNumber) {
1259
+ return buildXmlDocument({
1260
+ root: "xmltaxpayer",
1261
+ namespace: TAXPAYER_NAMESPACE,
1262
+ schemaLocation: TAXPAYER_SCHEMA_LOCATION,
1263
+ children: [el("beallitasok", credentials), el("torzsszam", toTaxpayerId(taxNumber))]
1264
+ });
1265
+ }
1266
+ function throwIfNavError(root, response) {
1267
+ const result = findChild(root, "result");
1268
+ if (childText(result, "funcCode")?.toUpperCase() !== "ERROR") return;
1269
+ const errorCode = childText(result, "errorCode");
1270
+ const code = parseErrorCode(errorCode);
1271
+ const message = childText(result, "message");
1272
+ const textCode = code === void 0 ? errorCode : void 0;
1273
+ throw createAgentError({
1274
+ code,
1275
+ message: textCode === void 0 ? message : [textCode, message].filter(Boolean).join(": "),
1276
+ action: response.action,
1277
+ httpStatus: response.status,
1278
+ rawResponse: response.text().slice(0, 2e3)
1279
+ });
1280
+ }
1281
+ function readTaxNumber(data) {
1282
+ const detail = findChild(data, "taxNumberDetail");
1283
+ const taxpayerId = childText(detail, "taxpayerId");
1284
+ if (taxpayerId === void 0) return void 0;
1285
+ const vatCode = childText(detail, "vatCode");
1286
+ const countyCode = childText(detail, "countyCode");
1287
+ return {
1288
+ taxpayerId,
1289
+ vatCode,
1290
+ countyCode,
1291
+ formatted: vatCode !== void 0 && countyCode !== void 0 ? `${taxpayerId}-${vatCode}-${countyCode}` : void 0
1292
+ };
1293
+ }
1294
+ function readAddresses(data) {
1295
+ return findChildren(findChild(data, "taxpayerAddressList"), "taxpayerAddressItem").map(parseTaxpayerAddress);
1296
+ }
1297
+ function readRequestId(root) {
1298
+ const requestId = childText(findChild(root, "header"), "requestId");
1299
+ return requestId === "-" ? void 0 : requestId;
1300
+ }
1301
+ function parseQueryTaxpayerResponse(response) {
1302
+ throwIfAnyError(response);
1303
+ const root = parseResponseXml(response);
1304
+ throwIfXmlFailure(root, response);
1305
+ if (root.name !== "QueryTaxpayerResponse") throw unexpectedResponse(response, "QueryTaxpayerResponse XML választ vártunk.");
1306
+ throwIfNavError(root, response);
1307
+ const requestId = readRequestId(root);
1308
+ const infoDate = childText(root, "infoDate");
1309
+ const data = findChild(root, "taxpayerData");
1310
+ const validity = childBoolean(root, "taxpayerValidity");
1311
+ if (validity === false || data === void 0) return {
1312
+ valid: validity === true,
1313
+ addresses: [],
1314
+ infoDate,
1315
+ requestId
1316
+ };
1317
+ const addresses = readAddresses(data);
1318
+ return {
1319
+ valid: true,
1320
+ name: childText(data, "taxpayerName"),
1321
+ shortName: childText(data, "taxpayerShortName"),
1322
+ taxNumber: readTaxNumber(data),
1323
+ address: addresses.find((address) => address.type === "HQ") ?? addresses[0],
1324
+ addresses,
1325
+ incorporation: childText(data, "incorporation"),
1326
+ vatGroupMembership: childText(data, "vatGroupMembership"),
1327
+ infoDate,
1328
+ requestId
1329
+ };
1330
+ }
1331
+ async function queryTaxpayer(ctx, taxNumber, options = {}) {
1332
+ const xml = buildQueryTaxpayerXml(ctx.credentials, taxNumber);
1333
+ return ctx.execute({
1334
+ action: "queryTaxpayer",
1335
+ xml,
1336
+ signal: options.signal,
1337
+ safeToRetry: true
1338
+ }, parseQueryTaxpayerResponse);
1339
+ }
1340
+ //#endregion
1341
+ //#region src/client.ts
1342
+ const CREDENTIAL_PROBE_INVOICE_NUMBER = "KASSZA-CREDENTIAL-PROBE-0";
1343
+ async function nullIfNotFound(promise) {
1344
+ try {
1345
+ return await promise;
1346
+ } catch (error) {
1347
+ if (isSzamlazzError(error) && (error.isNotFound || error.code === 7)) return null;
1348
+ throw error;
1349
+ }
1350
+ }
1351
+ function createInvoicesApi(ctx, defaults) {
1352
+ return {
1353
+ create: (input, options) => createInvoice(ctx, defaults, input, options),
1354
+ preview: (input, options) => previewInvoice(ctx, defaults, input, options),
1355
+ reverse: (input, options) => reverseInvoice(ctx, input, options),
1356
+ registerPayment: (input, options) => registerPayment(ctx, input, options),
1357
+ clearPayments: (input, options) => clearPayments(ctx, input, options),
1358
+ getPdf: (reference, options) => getInvoicePdf(ctx, reference, options),
1359
+ get: (reference, query, options) => getInvoice(ctx, reference, query, options),
1360
+ find: (reference, query, options) => nullIfNotFound(getInvoice(ctx, reference, query, options)),
1361
+ deleteProforma: (reference, options) => deleteProforma(ctx, reference, options)
1362
+ };
1363
+ }
1364
+ function createReceiptsApi(ctx, defaults) {
1365
+ return {
1366
+ create: (input, options) => createReceipt(ctx, defaults, input, options),
1367
+ reverse: (input, options) => reverseReceipt(ctx, input, options),
1368
+ get: (input, options) => getReceipt(ctx, input, options),
1369
+ find: (input, options) => nullIfNotFound(getReceipt(ctx, input, options)),
1370
+ send: (input, options) => sendReceipt(ctx, input, options)
1371
+ };
1372
+ }
1373
+ function createKassza(options = {}) {
1374
+ const ctx = createAgentContext(options);
1375
+ return {
1376
+ invoices: createInvoicesApi(ctx, options.defaults?.invoice ?? {}),
1377
+ receipts: createReceiptsApi(ctx, options.defaults?.receipt ?? {}),
1378
+ taxpayer: { query: (taxNumber, requestOptions) => queryTaxpayer(ctx, taxNumber, requestOptions) },
1379
+ async verifyCredentials(requestOptions) {
1380
+ try {
1381
+ await getInvoicePdf(ctx, CREDENTIAL_PROBE_INVOICE_NUMBER, requestOptions);
1382
+ return true;
1383
+ } catch (error) {
1384
+ if (!isSzamlazzError(error)) throw error;
1385
+ if (error.category === "auth") return false;
1386
+ if (error.isNotFound || error.code === 7) return true;
1387
+ throw error;
1388
+ }
1389
+ },
1390
+ resetSession: () => ctx.resetSession()
1391
+ };
1392
+ }
1393
+ //#endregion
1394
+ export { AGENT_ACTIONS, AGENT_ERROR_CODES, MAX_INVOICE_ATTACHMENTS, SZAMLAZZ_AGENT_URL, SzamlazzError, addBudapestDays, bytesToBase64, createKassza, isSzamlazzError, memoryCookieStore, toBudapestDate, todayInBudapest };