kassza 0.11.0 → 0.13.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 (132) hide show
  1. package/README.md +376 -111
  2. package/agents/README.md +20 -5
  3. package/agents/api.md +165 -2
  4. package/agents/pitfalls.md +16 -3
  5. package/agents/recipes.md +215 -45
  6. package/agents/skills/kassza/SKILL.md +11 -8
  7. package/dist/cli.cjs +552 -0
  8. package/dist/cli.d.cts +1 -0
  9. package/dist/cli.d.ts +1 -0
  10. package/dist/cli.js +552 -0
  11. package/dist/client-6MkeuFqD.d.ts +268 -0
  12. package/dist/client-B5FryKxJ.d.cts +268 -0
  13. package/dist/client-C-PdfL_P.cjs +1275 -0
  14. package/dist/client-CfaS1-Jx.js +1228 -0
  15. package/dist/context-BxQlIlug.d.ts +425 -0
  16. package/dist/context-DXNbTPwz.d.cts +425 -0
  17. package/dist/create-once-Cz621l8r.js +330 -0
  18. package/dist/create-once-DgMtKKcG.cjs +395 -0
  19. package/dist/crypto-Dpn4FHQ6.cjs +65 -0
  20. package/dist/crypto-usDg8L2K.js +36 -0
  21. package/dist/data-link/index.cjs +232 -0
  22. package/dist/data-link/index.d.cts +79 -0
  23. package/dist/data-link/index.d.ts +79 -0
  24. package/dist/data-link/index.js +224 -0
  25. package/dist/{dates-DtHzwNU6.d.cts → dates-9zvESP0i.d.cts} +2 -1
  26. package/dist/{dates-DtHzwNU6.d.ts → dates-9zvESP0i.d.ts} +2 -1
  27. package/dist/{dates-PPxH0n5H.cjs → dates-CPgBodkP.cjs} +44 -1
  28. package/dist/{dates-D2XebOIg.js → dates-CXyj7Azy.js} +39 -2
  29. package/dist/delegation/index.cjs +396 -0
  30. package/dist/delegation/index.d.cts +100 -0
  31. package/dist/delegation/index.d.ts +100 -0
  32. package/dist/delegation/index.js +378 -0
  33. package/dist/{errors-DapdV5DK.js → errors-DLrb0g64.js} +122 -5
  34. package/dist/{errors-B0QJhUW1.cjs → errors-DxeuTslP.cjs} +127 -4
  35. package/dist/get-Byc9T5WO.d.cts +151 -0
  36. package/dist/get-Byc9T5WO.d.ts +151 -0
  37. package/dist/get-Csm2n0rZ.cjs +445 -0
  38. package/dist/get-DT3JEgQ6.js +380 -0
  39. package/dist/index.cjs +21 -1410
  40. package/dist/index.d.cts +20 -3
  41. package/dist/index.d.ts +20 -3
  42. package/dist/index.js +8 -1409
  43. package/dist/ipn/index.cjs +1 -1
  44. package/dist/ipn/index.js +1 -1
  45. package/dist/issue-AGRohSm7.cjs +914 -0
  46. package/dist/issue-DtSLpVdJ.js +777 -0
  47. package/dist/json-4y4E2xxS.cjs +61 -0
  48. package/dist/json-B70TwoX1.d.cts +4 -0
  49. package/dist/json-B70TwoX1.d.ts +4 -0
  50. package/dist/json-DjnqnaJK.js +32 -0
  51. package/dist/mcp/index.cjs +10 -0
  52. package/dist/mcp/index.d.cts +71 -0
  53. package/dist/mcp/index.d.ts +71 -0
  54. package/dist/mcp/index.js +2 -0
  55. package/dist/money/index.cjs +12 -10
  56. package/dist/money/index.js +3 -1
  57. package/dist/{money-DkiGukAw.cjs → money-BxytJW6f.cjs} +42 -177
  58. package/dist/{money-C9j7nBNP.js → money-t7uy1n91.js} +29 -110
  59. package/dist/nav/index.cjs +1046 -0
  60. package/dist/nav/index.d.cts +247 -0
  61. package/dist/nav/index.d.ts +247 -0
  62. package/dist/nav/index.js +1012 -0
  63. package/dist/nav-BEwcX7-N.cjs +203 -0
  64. package/dist/nav-CK1WgYo7.js +156 -0
  65. package/dist/parse-BJj-aqKy.cjs +380 -0
  66. package/dist/parse-C608ehqM.js +291 -0
  67. package/dist/payments/barion.cjs +208 -0
  68. package/dist/payments/barion.d.cts +28 -0
  69. package/dist/payments/barion.d.ts +28 -0
  70. package/dist/payments/barion.js +199 -0
  71. package/dist/payments/index.cjs +16 -0
  72. package/dist/payments/index.d.cts +31 -0
  73. package/dist/payments/index.d.ts +31 -0
  74. package/dist/payments/index.js +3 -0
  75. package/dist/payments/paypal.cjs +351 -0
  76. package/dist/payments/paypal.d.cts +59 -0
  77. package/dist/payments/paypal.d.ts +59 -0
  78. package/dist/payments/paypal.js +337 -0
  79. package/dist/payments/revolut.cjs +261 -0
  80. package/dist/payments/revolut.d.cts +48 -0
  81. package/dist/payments/revolut.d.ts +48 -0
  82. package/dist/payments/revolut.js +249 -0
  83. package/dist/payments/simplepay.cjs +313 -0
  84. package/dist/payments/simplepay.d.cts +86 -0
  85. package/dist/payments/simplepay.d.ts +86 -0
  86. package/dist/payments/simplepay.js +299 -0
  87. package/dist/payments/stripe.cjs +315 -0
  88. package/dist/payments/stripe.d.cts +49 -0
  89. package/dist/payments/stripe.d.ts +49 -0
  90. package/dist/payments/stripe.js +303 -0
  91. package/dist/reports/index.cjs +103 -0
  92. package/dist/reports/index.d.cts +70 -0
  93. package/dist/reports/index.d.ts +70 -0
  94. package/dist/reports/index.js +94 -0
  95. package/dist/request-body-CH6ZGOrq.cjs +34 -0
  96. package/dist/request-body-uZHMRlQr.js +29 -0
  97. package/dist/rounding-BLyHjjI5.js +20 -0
  98. package/dist/rounding-TxoWy2ww.cjs +37 -0
  99. package/dist/serialize-BXOww1Uq.cjs +286 -0
  100. package/dist/serialize-DSE_o9RK.js +215 -0
  101. package/dist/server-C6PoNkdD.cjs +1557 -0
  102. package/dist/server-Cd8HB661.js +1504 -0
  103. package/dist/storage/fs.cjs +1 -1
  104. package/dist/storage/fs.js +1 -1
  105. package/dist/storage/index.cjs +2 -2
  106. package/dist/storage/index.d.cts +1 -1
  107. package/dist/storage/index.d.ts +1 -1
  108. package/dist/storage/index.js +2 -2
  109. package/dist/tax-number-BYFkBp4A.cjs +141 -0
  110. package/dist/tax-number-BdqKsxNR.js +76 -0
  111. package/dist/testing/index.cjs +1656 -84
  112. package/dist/testing/index.d.cts +203 -3
  113. package/dist/testing/index.d.ts +203 -3
  114. package/dist/testing/index.js +1653 -83
  115. package/dist/types-BVeR7KyU.d.cts +56 -0
  116. package/dist/types-BVeR7KyU.d.ts +56 -0
  117. package/dist/types-DH8QoNZK.d.cts +135 -0
  118. package/dist/types-k--zHf4l.d.ts +135 -0
  119. package/dist/validators/index.cjs +14 -88
  120. package/dist/validators/index.js +1 -75
  121. package/dist/vat-g35srbNG.cjs +116 -0
  122. package/dist/vat-v_dcWCto.js +81 -0
  123. package/dist/webhook-81giRMdQ.cjs +223 -0
  124. package/dist/webhook-CpCMHhn2.d.ts +6 -0
  125. package/dist/webhook-CpMJuP6c.d.cts +6 -0
  126. package/dist/webhook-CrEGohbg.js +152 -0
  127. package/llms.txt +4 -4
  128. package/package.json +148 -2
  129. package/dist/client-B9kbKKBf.d.cts +0 -748
  130. package/dist/client-zv4enyq7.d.ts +0 -748
  131. package/dist/create-5YkUcJSe.js +0 -957
  132. package/dist/create-DZsl3Z4m.cjs +0 -1178
@@ -0,0 +1,1228 @@
1
+ import { c as emitDocumentEvent, i as resolveInvoice, l as AGENT_ACTIONS, n as optionalAgentDate, o as INVOICE_TEMPLATES, r as presentText, s as TAXPAYER_TYPE_CODES, t as createReceiptOnce } from "./create-once-Cz621l8r.js";
2
+ import { a as parseErrorCode, i as isSzamlazzError, n as SzamlazzError, r as createAgentError } from "./errors-DLrb0g64.js";
3
+ import { t as base64ToBytes } from "./binary-D0M9U2MD.js";
4
+ import { a as optionalEl, c as childNumber, d as findChildren, l as childText, n as buildXmlDocument, r as el, s as childBoolean, u as findChild } from "./serialize-DSE_o9RK.js";
5
+ import { a as looksLikeXml, c as readDocumentHeaders, d as throwIfHeaderError, f as throwIfHttpError, h as unexpectedResponse, m as throwIfXmlFailure, n as parseReceiptResponse, o as parseDoneText, p as throwIfTextError, r as createAgentResponse, s as parseResponseXml, u as throwIfAnyError } from "./parse-C608ehqM.js";
6
+ import { i as sessionKeyFor, n as memoryCookieStore, r as mergeSetCookies, t as SESSION_TTL_SECONDS } from "./session-rMKaJcmq.js";
7
+ import { a as todayInBudapest } from "./dates-CXyj7Azy.js";
8
+ import { r as formatVatRate } from "./vat-v_dcWCto.js";
9
+ import { i as summarizeItems } from "./money-t7uy1n91.js";
10
+ import { _ as createInvoiceOnce, c as optionalText, d as validateTemplate$1, l as receiptValidationError, n as issueForPayment, o as createReceipt, p as convertReceiptToInvoice, s as RECEIPT_XSD_BASE_URL, u as requireReceiptNumber } from "./issue-DtSLpVdJ.js";
11
+ import { a as optionalAgentDate$1, c as referenceValue, d as validationError, i as agentDate, l as requireText, o as optionalText$1, r as AGENT_XSD_BASE_URL, s as parseInvoiceResult, t as getInvoice, u as resolveInvoiceReference } from "./get-DT3JEgQ6.js";
12
+ //#region src/core/attempt-ledger.ts
13
+ const ATTEMPT_LEDGER_TTL_SECONDS = 86400;
14
+ const ATTEMPT_LEDGER_KEY_PREFIX = "szamlazz:attempts:";
15
+ const COUNTED_CATEGORIES = /* @__PURE__ */ new Set([
16
+ "auth",
17
+ "account",
18
+ "validation",
19
+ "maintenance",
20
+ "rate_limit",
21
+ "network",
22
+ "timeout",
23
+ "unexpected_response",
24
+ "unknown"
25
+ ]);
26
+ function countsAsFailedAttempt(error) {
27
+ return COUNTED_CATEGORIES.has(error.category);
28
+ }
29
+ const encoder = new TextEncoder();
30
+ async function attemptLedgerKey(request) {
31
+ const attachments = (request.attachments ?? []).map((attachment) => `${attachment.filename}:${attachment.size}`).join("|");
32
+ const digest = await crypto.subtle.digest("SHA-256", encoder.encode(`${request.action}\n${request.xml}\n${attachments}`));
33
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0"));
34
+ return `${ATTEMPT_LEDGER_KEY_PREFIX}${hex.join("")}`;
35
+ }
36
+ function parseCount(value) {
37
+ if (value === void 0 || value === null) return 0;
38
+ const parsed = Number.parseInt(value, 10);
39
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 0;
40
+ }
41
+ function createAttemptLedger(store) {
42
+ return {
43
+ async failures(key) {
44
+ return parseCount(await store.get(key));
45
+ },
46
+ async recordFailure(key, previous) {
47
+ const next = previous + 1;
48
+ await store.set(key, String(next), ATTEMPT_LEDGER_TTL_SECONDS);
49
+ return next;
50
+ },
51
+ async reset(key) {
52
+ await store.delete(key);
53
+ }
54
+ };
55
+ }
56
+ function attemptLimitError(action, key, failures) {
57
+ return new SzamlazzError(`Ezt a kérést már ${failures} alkalommal sikertelenül küldtük el, ezért a kassza nem küldi el újra.`, {
58
+ category: "attempt_limit",
59
+ action,
60
+ details: { attemptKey: key },
61
+ hint: "A Számlázz.hu szabályai szerint öt sikertelen próbálkozás után emberi beavatkozás kell, különben kitiltás jöhet. Javítsd a hibát, majd a kassza.resetAttempts(error) hívással töröld a számlálót."
62
+ });
63
+ }
64
+ const DEFAULT_SAFE_ATTEMPTS = 3;
65
+ const DEFAULT_RETRY_DELAY_MS = 1e3;
66
+ function readEnv(name) {
67
+ const value = (globalThis.process?.env)?.[name]?.trim();
68
+ return value ? value : void 0;
69
+ }
70
+ function configurationError(message) {
71
+ return new SzamlazzError(message, { category: "configuration" });
72
+ }
73
+ function resolveCredentials(options) {
74
+ const agentKey = options.agentKey?.trim() || (options.username ? void 0 : readEnv("SZAMLAZZ_AGENT_KEY"));
75
+ if (agentKey) {
76
+ 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.");
77
+ return [el("szamlaagentkulcs", agentKey)];
78
+ }
79
+ if (options.username && options.password) return [el("felhasznalo", options.username), el("jelszo", options.password)];
80
+ 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.");
81
+ }
82
+ function toBlob(attachment) {
83
+ const type = attachment.contentType ?? "application/octet-stream";
84
+ if (attachment.content instanceof Blob) return attachment.content;
85
+ return new Blob([attachment.content], { type });
86
+ }
87
+ function buildFormData(request) {
88
+ const form = new FormData();
89
+ form.append(AGENT_ACTIONS[request.action], new Blob([request.xml], { type: "text/xml; charset=UTF-8" }), "request.xml");
90
+ request.attachments?.forEach((attachment, index) => {
91
+ form.append(`attachfile${index + 1}`, toBlob(attachment), attachment.filename);
92
+ });
93
+ return form;
94
+ }
95
+ function isAbortError(error) {
96
+ return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
97
+ }
98
+ function sleep(ms, signal) {
99
+ return new Promise((resolve, reject) => {
100
+ if (signal?.aborted) {
101
+ reject(signal.reason);
102
+ return;
103
+ }
104
+ const timer = setTimeout(() => {
105
+ signal?.removeEventListener("abort", onAbort);
106
+ resolve();
107
+ }, ms);
108
+ const onAbort = () => {
109
+ clearTimeout(timer);
110
+ reject(signal?.reason);
111
+ };
112
+ signal?.addEventListener("abort", onAbort, { once: true });
113
+ });
114
+ }
115
+ async function ignoreStoreFailure(operation) {
116
+ try {
117
+ return await operation();
118
+ } catch {
119
+ return;
120
+ }
121
+ }
122
+ function callHook(hook, event) {
123
+ if (!hook) return;
124
+ try {
125
+ const result = hook(event);
126
+ if (result instanceof Promise) result.catch(() => void 0);
127
+ } catch {
128
+ return;
129
+ }
130
+ }
131
+ function clampAttempts(value) {
132
+ if (value === void 0) return DEFAULT_SAFE_ATTEMPTS;
133
+ if (!Number.isInteger(value) || value < 1) throw configurationError(`A maxAttempts értéke legalább 1 egész szám legyen, kapott: ${value}`);
134
+ return Math.min(value, 5);
135
+ }
136
+ function resolveCooldown(value) {
137
+ if (value === void 0) return 0;
138
+ if (!Number.isFinite(value) || value < 0) throw configurationError(`A maintenanceCooldownMs értéke nemnegatív szám legyen, kapott: ${value}`);
139
+ return value;
140
+ }
141
+ function attachmentSize(attachment) {
142
+ const { content } = attachment;
143
+ if (typeof content === "string") return new TextEncoder().encode(content).byteLength;
144
+ if (content instanceof Blob) return content.size;
145
+ return content.byteLength;
146
+ }
147
+ function maintenanceCooldownError(action, remainingMs) {
148
+ return new SzamlazzError(`A Számlázz.hu karbantartás miatt nem érhető el, a kassza még ${Math.ceil(remainingMs / 1e3)} másodpercig nem küld kérést.`, {
149
+ category: "maintenance",
150
+ action,
151
+ hint: "A maintenanceCooldownMs beállítás miatt a kérés el sem indult. Válts tartalék folyamatra (például kézi nyugtatömbre), vagy próbáld később."
152
+ });
153
+ }
154
+ function createAgentContext(options = {}) {
155
+ const credentials = resolveCredentials(options);
156
+ const endpoint = options.endpoint ?? "https://www.szamlazz.hu/szamla/";
157
+ const fetchImpl = options.fetch ?? globalThis.fetch;
158
+ if (typeof fetchImpl !== "function") throw configurationError("Nem található fetch implementáció. Add meg a fetch opciót.");
159
+ const timeoutMs = options.timeoutMs ?? 6e4;
160
+ const safeAttempts = clampAttempts(options.maxAttempts);
161
+ const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
162
+ const cookieStore = options.cookieStore === false ? void 0 : options.cookieStore ?? memoryCookieStore();
163
+ const sessionSecret = credentials.map((node) => String(node.content)).join("|");
164
+ let sessionKeyPromise;
165
+ const resolveSessionKey = () => {
166
+ sessionKeyPromise ??= sessionKeyFor(sessionSecret);
167
+ return sessionKeyPromise;
168
+ };
169
+ const hooks = options.hooks ?? {};
170
+ const ledger = options.attemptLedger ? createAttemptLedger(options.attemptLedger) : void 0;
171
+ const cooldownMs = resolveCooldown(options.maintenanceCooldownMs);
172
+ let blockedUntil = 0;
173
+ async function send(request) {
174
+ const cookie = cookieStore ? await ignoreStoreFailure(async () => cookieStore.get(await resolveSessionKey())) : void 0;
175
+ request.signal?.throwIfAborted();
176
+ const headers = new Headers({ Accept: "application/xml, application/pdf, text/plain, */*" });
177
+ if (cookie) headers.set("Cookie", cookie);
178
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
179
+ const signal = request.signal ? AbortSignal.any([request.signal, timeoutSignal]) : timeoutSignal;
180
+ let response;
181
+ let body;
182
+ try {
183
+ response = await fetchImpl(endpoint, {
184
+ method: "POST",
185
+ headers,
186
+ body: buildFormData(request),
187
+ signal
188
+ });
189
+ body = new Uint8Array(await response.arrayBuffer());
190
+ } catch (error) {
191
+ if (request.signal?.aborted) throw request.signal.reason;
192
+ if (timeoutSignal.aborted || isAbortError(error)) throw new SzamlazzError(`A Számlázz.hu nem válaszolt ${timeoutMs} ms alatt.`, {
193
+ category: "timeout",
194
+ action: request.action,
195
+ cause: error
196
+ });
197
+ throw new SzamlazzError("Hálózati hiba a Számlázz.hu elérésekor.", {
198
+ category: "network",
199
+ action: request.action,
200
+ cause: error
201
+ });
202
+ }
203
+ if (cookieStore) {
204
+ const merged = mergeSetCookies(cookie, response.headers);
205
+ if (merged) await ignoreStoreFailure(async () => cookieStore.set(await resolveSessionKey(), merged, SESSION_TTL_SECONDS));
206
+ }
207
+ return createAgentResponse(request.action, response.status, response.headers, body);
208
+ }
209
+ async function resetSession() {
210
+ if (cookieStore) await ignoreStoreFailure(async () => cookieStore.delete(await resolveSessionKey()));
211
+ }
212
+ async function resetAttempts(key) {
213
+ if (ledger) await ledger.reset(key);
214
+ }
215
+ async function ledgerKeyFor(request) {
216
+ if (!ledger) return void 0;
217
+ return attemptLedgerKey({
218
+ action: request.action,
219
+ xml: request.xml,
220
+ attachments: (request.attachments ?? []).map((attachment) => ({
221
+ filename: attachment.filename,
222
+ size: attachmentSize(attachment)
223
+ }))
224
+ });
225
+ }
226
+ function assertNoCooldown(action) {
227
+ const remainingMs = blockedUntil - Date.now();
228
+ if (remainingMs > 0) throw maintenanceCooldownError(action, remainingMs);
229
+ }
230
+ async function execute(request, parse) {
231
+ const maxAttempts = request.safeToRetry ? safeAttempts : 1;
232
+ const ledgerKey = await ledgerKeyFor(request);
233
+ for (let attempt = 1;; attempt++) {
234
+ assertNoCooldown(request.action);
235
+ const failures = ledger && ledgerKey !== void 0 ? await ignoreStoreFailure(() => ledger.failures(ledgerKey)) ?? 0 : 0;
236
+ if (ledgerKey !== void 0 && failures >= 5) throw attemptLimitError(request.action, ledgerKey, failures);
237
+ const startedAt = Date.now();
238
+ callHook(hooks.onRequest, {
239
+ action: request.action,
240
+ attempt
241
+ });
242
+ try {
243
+ const response = await send(request);
244
+ callHook(hooks.onResponse, {
245
+ action: request.action,
246
+ attempt,
247
+ status: response.status,
248
+ durationMs: Date.now() - startedAt
249
+ });
250
+ const result = await parse(response);
251
+ if (ledger && ledgerKey !== void 0 && failures > 0) await ignoreStoreFailure(() => ledger.reset(ledgerKey));
252
+ return result;
253
+ } catch (error) {
254
+ if (!(error instanceof SzamlazzError)) throw error;
255
+ if (ledger && ledgerKey !== void 0 && countsAsFailedAttempt(error)) await ignoreStoreFailure(() => ledger.recordFailure(ledgerKey, failures));
256
+ if (error.category === "maintenance" && cooldownMs > 0) blockedUntil = Date.now() + cooldownMs;
257
+ const willRetry = error.retryable && attempt < maxAttempts && !(error.category === "maintenance" && cooldownMs > 0);
258
+ callHook(hooks.onError, {
259
+ action: request.action,
260
+ attempt,
261
+ error,
262
+ willRetry
263
+ });
264
+ if (error.category === "auth") await resetSession();
265
+ if (!willRetry) throw error;
266
+ await sleep(retryDelayMs * 2 ** (attempt - 1), request.signal);
267
+ }
268
+ }
269
+ }
270
+ return {
271
+ credentials,
272
+ execute,
273
+ resetSession,
274
+ resetAttempts
275
+ };
276
+ }
277
+ //#endregion
278
+ //#region src/invoices/create-response.ts
279
+ function readRawResponse(response) {
280
+ throwIfAnyError(response);
281
+ const headers = readDocumentHeaders(response.headers);
282
+ const fromHeaders = {
283
+ number: headers.number,
284
+ netTotal: headers.netTotal,
285
+ grossTotal: headers.grossTotal,
286
+ outstanding: void 0,
287
+ buyerAccountUrl: headers.buyerAccountUrl,
288
+ pdf: void 0
289
+ };
290
+ if (response.isPdf) return {
291
+ ...fromHeaders,
292
+ pdf: response.body
293
+ };
294
+ if (looksLikeXml(response)) {
295
+ const root = parseResponseXml(response);
296
+ throwIfXmlFailure(root, response);
297
+ const pdfBase64 = childText(root, "pdf");
298
+ return {
299
+ number: childText(root, "szamlaszam") ?? headers.number,
300
+ netTotal: childNumber(root, "szamlanetto") ?? headers.netTotal,
301
+ grossTotal: childNumber(root, "szamlabrutto") ?? headers.grossTotal,
302
+ outstanding: childNumber(root, "kintlevoseg"),
303
+ buyerAccountUrl: childText(root, "vevoifiokurl") ?? headers.buyerAccountUrl,
304
+ pdf: pdfBase64 === void 0 ? void 0 : base64ToBytes(pdfBase64)
305
+ };
306
+ }
307
+ const done = parseDoneText(response.text());
308
+ if (done) return {
309
+ ...fromHeaders,
310
+ number: done.number ?? headers.number
311
+ };
312
+ if (headers.number !== void 0) return fromHeaders;
313
+ throw unexpectedResponse(response, "Számlaszámot vagy PDF-et vártunk.");
314
+ }
315
+ function totalsFor(raw, items) {
316
+ if (raw.netTotal !== void 0 && raw.grossTotal !== void 0) return {
317
+ netTotal: raw.netTotal,
318
+ grossTotal: raw.grossTotal
319
+ };
320
+ const computed = summarizeItems(items);
321
+ return {
322
+ netTotal: raw.netTotal ?? computed.netAmount,
323
+ grossTotal: raw.grossTotal ?? computed.grossAmount
324
+ };
325
+ }
326
+ function parseCreateInvoiceResponse(response, items = []) {
327
+ const raw = readRawResponse(response);
328
+ if (raw.number === void 0) throw unexpectedResponse(response, "A sikeres válaszból hiányzik a számlaszám.");
329
+ return {
330
+ number: raw.number,
331
+ ...totalsFor(raw, items),
332
+ outstanding: raw.outstanding,
333
+ buyerAccountUrl: raw.buyerAccountUrl,
334
+ pdf: raw.pdf,
335
+ items
336
+ };
337
+ }
338
+ function parseInvoicePreviewResponse(response, items = []) {
339
+ const raw = readRawResponse(response);
340
+ if (raw.pdf === void 0) throw unexpectedResponse(response, "Az előnézeti válaszból hiányzik a PDF.");
341
+ return {
342
+ pdf: raw.pdf,
343
+ ...totalsFor(raw, items),
344
+ items
345
+ };
346
+ }
347
+ //#endregion
348
+ //#region src/invoices/create-xml.ts
349
+ const INVOICE_XML_NAMESPACE = "http://www.szamlazz.hu/xmlszamla";
350
+ const INVOICE_XML_SCHEMA_LOCATION = "https://www.szamlazz.hu/szamla/docs/xsds/agent/xmlszamla.xsd";
351
+ const RESPONSE_VERSION_XML = 2;
352
+ function textEl(name, value) {
353
+ return optionalEl(name, presentText(value));
354
+ }
355
+ function settingsNode(credentials, invoice, preview) {
356
+ return el("beallitasok", [
357
+ ...credentials,
358
+ el("eszamla", invoice.eInvoice),
359
+ el("szamlaLetoltes", preview || invoice.downloadPdf),
360
+ el("valaszVerzio", RESPONSE_VERSION_XML),
361
+ textEl("aggregator", invoice.aggregator),
362
+ optionalEl("guardian", invoice.guardian),
363
+ optionalEl("cikkazoninvoice", invoice.articleIdentifierInvoice),
364
+ textEl("szamlaKulsoAzon", invoice.input.externalId)
365
+ ]);
366
+ }
367
+ function documentTypeNodes(invoice) {
368
+ const { input, type } = invoice;
369
+ return [
370
+ type === "advance" && el("elolegszamla", true),
371
+ type === "final" && el("vegszamla", true),
372
+ input.type === "final" && textEl("elolegSzamlaszam", input.advanceInvoiceNumber),
373
+ type === "corrective" && el("helyesbitoszamla", true),
374
+ input.type === "corrective" && textEl("helyesbitettSzamlaszam", input.correctedInvoiceNumber),
375
+ type === "proforma" && el("dijbekero", true),
376
+ type === "deliveryNote" && el("szallitolevel", true)
377
+ ];
378
+ }
379
+ function headerNode(invoice, preview) {
380
+ const { input } = invoice;
381
+ return el("fejlec", [
382
+ el("keltDatum", invoice.issueDate),
383
+ el("teljesitesDatum", invoice.fulfillmentDate),
384
+ el("fizetesiHataridoDatum", invoice.dueDate),
385
+ el("fizmod", invoice.paymentMethod),
386
+ el("penznem", invoice.currency),
387
+ el("szamlaNyelve", invoice.language),
388
+ textEl("megjegyzes", input.comment),
389
+ textEl("arfolyamBank", invoice.exchangeBank),
390
+ optionalEl("arfolyam", invoice.exchangeRate),
391
+ textEl("rendelesSzam", input.orderNumber),
392
+ textEl("dijbekeroSzamlaszam", input.proformaNumber),
393
+ ...documentTypeNodes(invoice),
394
+ textEl("logoExtra", invoice.logoExtra),
395
+ textEl("szamlaszamElotag", invoice.prefix),
396
+ optionalEl("fizetendoKorrekcio", input.paymentCorrection),
397
+ optionalEl("fizetve", input.paid),
398
+ optionalEl("arresAfa", input.marginVat),
399
+ optionalEl("eusAfa", invoice.euVat),
400
+ optionalEl("szamlaSablon", invoice.template),
401
+ preview && el("elonezetpdf", true),
402
+ optionalEl("simpleItems", invoice.simpleItems)
403
+ ]);
404
+ }
405
+ function sellerNode(seller) {
406
+ return el("elado", [
407
+ textEl("bank", seller.bank),
408
+ textEl("bankszamlaszam", seller.bankAccount),
409
+ textEl("emailReplyto", seller.emailReplyTo),
410
+ textEl("emailTargy", seller.emailSubject),
411
+ textEl("emailSzoveg", seller.emailText),
412
+ textEl("alairoNeve", seller.signatoryName)
413
+ ]);
414
+ }
415
+ function buyerLedgerNode(ledger) {
416
+ if (!ledger) return void 0;
417
+ return optionalEl("vevoFokonyv", [
418
+ optionalEl("konyvelesDatum", optionalAgentDate(ledger.bookingDate, "buyer.ledger.bookingDate")),
419
+ textEl("vevoAzonosito", ledger.buyerId),
420
+ textEl("vevoFokonyviSzam", ledger.ledgerAccount),
421
+ optionalEl("folyamatosTelj", ledger.continuousFulfillment),
422
+ optionalEl("elszDatumTol", optionalAgentDate(ledger.settlementPeriodStart, "buyer.ledger.settlementPeriodStart")),
423
+ optionalEl("elszDatumIg", optionalAgentDate(ledger.settlementPeriodEnd, "buyer.ledger.settlementPeriodEnd"))
424
+ ]);
425
+ }
426
+ function buyerNode(buyer, sendEmail) {
427
+ const taxpayerType = buyer.taxpayerType;
428
+ return el("vevo", [
429
+ el("nev", buyer.name),
430
+ textEl("orszag", buyer.country),
431
+ el("irsz", buyer.zip),
432
+ el("telepules", buyer.city),
433
+ el("cim", buyer.address),
434
+ textEl("email", buyer.email),
435
+ el("sendEmail", sendEmail),
436
+ optionalEl("adoalany", taxpayerType === void 0 ? void 0 : TAXPAYER_TYPE_CODES[taxpayerType]),
437
+ textEl("adoszam", buyer.taxNumber),
438
+ textEl("csoportazonosito", buyer.groupTaxNumber),
439
+ textEl("adoszamEU", buyer.euTaxNumber),
440
+ textEl("postazasiNev", buyer.postal?.name),
441
+ textEl("postazasiOrszag", buyer.postal?.country),
442
+ textEl("postazasiIrsz", buyer.postal?.zip),
443
+ textEl("postazasiTelepules", buyer.postal?.city),
444
+ textEl("postazasiCim", buyer.postal?.address),
445
+ buyerLedgerNode(buyer.ledger),
446
+ textEl("azonosito", buyer.identifier),
447
+ textEl("alairoNeve", buyer.signatoryName),
448
+ textEl("telefonszam", buyer.phone),
449
+ textEl("megjegyzes", buyer.comment)
450
+ ]);
451
+ }
452
+ function waybillNode(waybill) {
453
+ if (!waybill) return void 0;
454
+ const { transOFlex: tof, pickPackPoint: ppp, sprinter, mpl } = waybill;
455
+ return el("fuvarlevel", [
456
+ textEl("futarSzolgalat", waybill.courier),
457
+ textEl("vonalkod", waybill.barcode),
458
+ textEl("megjegyzes", waybill.comment),
459
+ tof && el("tof", [
460
+ textEl("azonosito", tof.id),
461
+ textEl("shipmentID", tof.shipmentId),
462
+ optionalEl("csomagszam", tof.packageCount),
463
+ textEl("countryCode", tof.countryCode),
464
+ textEl("zip", tof.zip),
465
+ textEl("service", tof.service)
466
+ ]),
467
+ ppp && el("ppp", [textEl("vonalkodPrefix", ppp.barcodePrefix), textEl("vonalkodPostfix", ppp.barcodePostfix)]),
468
+ sprinter && el("sprinter", [
469
+ textEl("azonosito", sprinter.id),
470
+ textEl("feladokod", sprinter.senderCode),
471
+ textEl("iranykod", sprinter.directionCode),
472
+ optionalEl("csomagszam", sprinter.packageCount),
473
+ textEl("vonalkodPostfix", sprinter.barcodePostfix),
474
+ textEl("szallitasiIdo", sprinter.deliveryTime)
475
+ ]),
476
+ mpl && el("mpl", [
477
+ el("vevokod", mpl.customerCode),
478
+ el("vonalkod", mpl.barcode),
479
+ el("tomeg", String(mpl.weight)),
480
+ textEl("kulonszolgaltatasok", mpl.services),
481
+ optionalEl("erteknyilvanitas", mpl.declaredValue)
482
+ ])
483
+ ]);
484
+ }
485
+ function itemLedgerNode(ledger, label) {
486
+ if (!ledger) return void 0;
487
+ return optionalEl("tetelFokonyv", [
488
+ textEl("gazdasagiEsem", ledger.economicEvent),
489
+ textEl("gazdasagiEsemAfa", ledger.vatEconomicEvent),
490
+ textEl("arbevetelFokonyviSzam", ledger.revenueLedgerAccount),
491
+ textEl("afaFokonyviSzam", ledger.vatLedgerAccount),
492
+ optionalEl("elszDatumTol", optionalAgentDate(ledger.settlementPeriodStart, `${label} settlementPeriodStart`)),
493
+ optionalEl("elszDatumIg", optionalAgentDate(ledger.settlementPeriodEnd, `${label} settlementPeriodEnd`))
494
+ ]);
495
+ }
496
+ function itemNode(item, index) {
497
+ const { input, amounts } = item;
498
+ return el("tetel", [
499
+ el("megnevezes", input.name),
500
+ textEl("azonosito", input.identifier),
501
+ el("mennyiseg", amounts.quantity),
502
+ el("mennyisegiEgyseg", item.unit),
503
+ el("nettoEgysegar", amounts.netUnitPrice),
504
+ el("afakulcs", formatVatRate(amounts.vat)),
505
+ optionalEl("arresAfaAlap", input.marginVatBase),
506
+ el("nettoErtek", amounts.netAmount),
507
+ el("afaErtek", amounts.vatAmount),
508
+ el("bruttoErtek", amounts.grossAmount),
509
+ textEl("megjegyzes", input.comment),
510
+ itemLedgerNode(input.ledger, `${index + 1}. tétel ledger`),
511
+ optionalEl("torloKod", input.dataDeletionCode)
512
+ ]);
513
+ }
514
+ function renderInvoiceXml(credentials, invoice, options = {}) {
515
+ const preview = options.preview === true;
516
+ return buildXmlDocument({
517
+ root: "xmlszamla",
518
+ namespace: INVOICE_XML_NAMESPACE,
519
+ schemaLocation: INVOICE_XML_SCHEMA_LOCATION,
520
+ children: [
521
+ settingsNode(credentials, invoice, preview),
522
+ headerNode(invoice, preview),
523
+ sellerNode(invoice.seller),
524
+ buyerNode(invoice.input.buyer, invoice.sendEmail),
525
+ waybillNode(invoice.input.waybill),
526
+ el("tetelek", invoice.items.map(itemNode))
527
+ ]
528
+ });
529
+ }
530
+ function buildCreateInvoiceXml(credentials, defaults, input, now = /* @__PURE__ */ new Date()) {
531
+ return renderInvoiceXml(credentials, resolveInvoice(defaults, input, now));
532
+ }
533
+ //#endregion
534
+ //#region src/invoices/create.ts
535
+ function buildRequest(ctx, invoice, preview, options) {
536
+ const xml = renderInvoiceXml(ctx.credentials, invoice, { preview });
537
+ const attachments = preview ? [] : invoice.attachments;
538
+ return {
539
+ action: "createInvoice",
540
+ xml,
541
+ signal: options.signal,
542
+ ...attachments.length > 0 ? { attachments } : {}
543
+ };
544
+ }
545
+ function itemsOf(invoice) {
546
+ return invoice.items.map((item) => item.amounts);
547
+ }
548
+ async function createInvoice(ctx, defaults, input, options = {}) {
549
+ const invoice = resolveInvoice(defaults, input, /* @__PURE__ */ new Date());
550
+ const items = itemsOf(invoice);
551
+ return ctx.execute(buildRequest(ctx, invoice, false, options), (response) => parseCreateInvoiceResponse(response, items));
552
+ }
553
+ async function previewInvoice(ctx, defaults, input, options = {}) {
554
+ const invoice = resolveInvoice(defaults, input, /* @__PURE__ */ new Date());
555
+ const items = itemsOf(invoice);
556
+ return ctx.execute(buildRequest(ctx, invoice, true, options), (response) => parseInvoicePreviewResponse(response, items));
557
+ }
558
+ function normalizeRegisterInput(input) {
559
+ const payments = "payments" in input ? input.payments : [{
560
+ amount: input.amount,
561
+ method: input.method ?? "átutalás",
562
+ date: input.date,
563
+ description: input.description
564
+ }];
565
+ 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.");
566
+ if (payments.length > 5) throw validationError(`Egy kérésben legfeljebb 5 befizetés rögzíthető, kapott: ${payments.length}.`);
567
+ return {
568
+ invoiceNumber: input.invoiceNumber,
569
+ taxNumber: input.taxNumber,
570
+ additive: input.additive ?? true,
571
+ payments
572
+ };
573
+ }
574
+ function normalizeClearInput(input) {
575
+ const target = typeof input === "string" ? { invoiceNumber: input } : input;
576
+ return {
577
+ invoiceNumber: target.invoiceNumber,
578
+ taxNumber: target.taxNumber,
579
+ additive: false,
580
+ payments: []
581
+ };
582
+ }
583
+ function paymentNode(payment, index) {
584
+ const position = index + 1;
585
+ if (typeof payment.amount !== "number" || !Number.isFinite(payment.amount)) throw validationError(`A(z) ${position}. befizetés összege (amount) nem véges szám.`);
586
+ return el("kifizetes", [
587
+ el("datum", payment.date === void 0 ? todayInBudapest() : agentDate(payment.date, "date")),
588
+ el("jogcim", requireText(payment.method, `Add meg a(z) ${position}. befizetés módját (method).`)),
589
+ el("osszeg", payment.amount),
590
+ optionalEl("leiras", optionalText$1(payment.description))
591
+ ]);
592
+ }
593
+ function buildPaymentXml(credentials, request) {
594
+ const invoiceNumber = requireText(request.invoiceNumber, "Add meg a számla számát (invoiceNumber), amelyhez a befizetés tartozik.");
595
+ return buildXmlDocument({
596
+ root: "xmlszamlakifiz",
597
+ namespace: "http://www.szamlazz.hu/xmlszamlakifiz",
598
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentkifiz/xmlszamlakifiz.xsd`,
599
+ children: [el("beallitasok", [
600
+ ...credentials,
601
+ el("szamlaszam", invoiceNumber),
602
+ optionalEl("adoszam", optionalText$1(request.taxNumber)),
603
+ el("additiv", request.additive),
604
+ el("valaszVerzio", 2)
605
+ ]), ...request.payments.map(paymentNode)]
606
+ });
607
+ }
608
+ function parseRegisterPaymentResponse(response, invoiceNumber) {
609
+ const result = parseInvoiceResult(response);
610
+ return {
611
+ invoiceNumber: result.number ?? invoiceNumber.trim(),
612
+ netTotal: result.netTotal,
613
+ grossTotal: result.grossTotal,
614
+ outstanding: result.outstanding,
615
+ buyerAccountUrl: result.buyerAccountUrl
616
+ };
617
+ }
618
+ function sendPaymentRequest(ctx, request, options) {
619
+ const xml = buildPaymentXml(ctx.credentials, request);
620
+ return ctx.execute({
621
+ action: "registerPayment",
622
+ xml,
623
+ signal: options.signal,
624
+ safeToRetry: !request.additive
625
+ }, (response) => parseRegisterPaymentResponse(response, request.invoiceNumber));
626
+ }
627
+ async function registerPayment(ctx, input, options = {}) {
628
+ return sendPaymentRequest(ctx, normalizeRegisterInput(input), options);
629
+ }
630
+ async function clearPayments(ctx, input, options = {}) {
631
+ return sendPaymentRequest(ctx, normalizeClearInput(input), options);
632
+ }
633
+ //#endregion
634
+ //#region src/invoices/pdf.ts
635
+ function buildInvoicePdfXml(credentials, reference) {
636
+ const resolved = resolveInvoiceReference(reference);
637
+ return buildXmlDocument({
638
+ root: "xmlszamlapdf",
639
+ namespace: "http://www.szamlazz.hu/xmlszamlapdf",
640
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentpdf/xmlszamlapdf.xsd`,
641
+ children: [
642
+ ...credentials,
643
+ optionalEl("szamlaszam", referenceValue(resolved, "invoiceNumber")),
644
+ optionalEl("rendelesSzam", referenceValue(resolved, "orderNumber")),
645
+ el("valaszVerzio", 2),
646
+ optionalEl("szamlaKulsoAzon", referenceValue(resolved, "externalId"))
647
+ ]
648
+ });
649
+ }
650
+ function parseInvoicePdfResponse(response) {
651
+ const { pdf, ...rest } = parseInvoiceResult(response);
652
+ if (pdf === void 0 || pdf.length === 0) throw unexpectedResponse(response, "A válasz nem tartalmaz PDF-et.");
653
+ return {
654
+ ...rest,
655
+ pdf
656
+ };
657
+ }
658
+ async function getInvoicePdf(ctx, reference, options = {}) {
659
+ const xml = buildInvoicePdfXml(ctx.credentials, reference);
660
+ return ctx.execute({
661
+ action: "getInvoicePdf",
662
+ xml,
663
+ signal: options.signal,
664
+ safeToRetry: true
665
+ }, parseInvoicePdfResponse);
666
+ }
667
+ const RESPONSE_ROOTS = /* @__PURE__ */ new Set(["xmlszamladbkdelvalasz", "xmlszamlavalasz"]);
668
+ const REFERENCE_HINT = "Add meg a díjbekérő számát szövegként, vagy pontosan egyet ezek közül: { proformaNumber }, { orderNumber }.";
669
+ function resolveProformaReference(reference) {
670
+ if (typeof reference === "string") return { proformaNumber: requireText(reference, `Üres díjbekérőszám. ${REFERENCE_HINT}`) };
671
+ if (typeof reference !== "object" || reference === null) throw validationError(`Érvénytelen díjbekérő-hivatkozás. ${REFERENCE_HINT}`);
672
+ const record = reference;
673
+ const hasNumber = record.proformaNumber !== void 0;
674
+ if (hasNumber === (record.orderNumber !== void 0)) throw validationError(`Érvénytelen díjbekérő-hivatkozás. ${REFERENCE_HINT}`);
675
+ return hasNumber ? { proformaNumber: requireText(record.proformaNumber, `Üres proformaNumber. ${REFERENCE_HINT}`) } : { orderNumber: requireText(record.orderNumber, `Üres orderNumber. ${REFERENCE_HINT}`) };
676
+ }
677
+ function buildDeleteProformaXml(credentials, reference) {
678
+ const resolved = resolveProformaReference(reference);
679
+ return buildXmlDocument({
680
+ root: "xmlszamladbkdel",
681
+ namespace: "http://www.szamlazz.hu/xmlszamladbkdel",
682
+ schemaLocation: "http://www.szamlazz.hu/docs/xsds/szamladbkdel/xmlszamladbkdel.xsd",
683
+ children: [el("beallitasok", [...credentials]), el("fejlec", [optionalEl("szamlaszam", resolved.proformaNumber), optionalEl("rendelesszam", resolved.orderNumber)])]
684
+ });
685
+ }
686
+ function withProformaCategory(error) {
687
+ if (!(error instanceof SzamlazzError) || error.code !== 335) return error;
688
+ return new SzamlazzError(error.message, {
689
+ category: "not_found",
690
+ code: error.code,
691
+ hint: "A díjbekérő nem létezik, vagy már törölték.",
692
+ action: error.action,
693
+ httpStatus: error.httpStatus,
694
+ rawResponse: error.rawResponse,
695
+ cause: error
696
+ });
697
+ }
698
+ function parseDeleteProformaResponse(response) {
699
+ try {
700
+ throwIfHeaderError(response);
701
+ throwIfTextError(response);
702
+ throwIfHttpError(response);
703
+ const root = parseResponseXml(response);
704
+ throwIfXmlFailure(root, response);
705
+ if (!RESPONSE_ROOTS.has(root.name) || childText(root, "sikeres")?.toLowerCase() !== "true") throw unexpectedResponse(response, "xmlszamladbkdelvalasz XML választ vártunk.");
706
+ } catch (error) {
707
+ throw withProformaCategory(error);
708
+ }
709
+ }
710
+ async function deleteProforma(ctx, reference, options = {}) {
711
+ const xml = buildDeleteProformaXml(ctx.credentials, reference);
712
+ await ctx.execute({
713
+ action: "deleteProforma",
714
+ xml,
715
+ signal: options.signal
716
+ }, parseDeleteProformaResponse);
717
+ }
718
+ const templates = new Set(INVOICE_TEMPLATES);
719
+ function normalizeInput$2(input) {
720
+ return typeof input === "string" ? { invoiceNumber: input } : input;
721
+ }
722
+ function validateTemplate(template) {
723
+ if (template === void 0 || templates.has(template)) return template;
724
+ throw validationError(`Ismeretlen számlasablon: ${String(template)}. Lehetséges értékek: ${INVOICE_TEMPLATES.join(", ")}.`);
725
+ }
726
+ function buildReverseInvoiceXml(credentials, input) {
727
+ const options = normalizeInput$2(input);
728
+ const invoiceNumber = requireText(options.invoiceNumber, "Add meg a sztornózandó számla számát (invoiceNumber).");
729
+ const email = options.email;
730
+ const buyer = options.buyer;
731
+ return buildXmlDocument({
732
+ root: "xmlszamlast",
733
+ namespace: "http://www.szamlazz.hu/xmlszamlast",
734
+ schemaLocation: `${AGENT_XSD_BASE_URL}agentst/xmlszamlast.xsd`,
735
+ children: [
736
+ el("beallitasok", [
737
+ ...credentials,
738
+ el("eszamla", options.eInvoice ?? false),
739
+ el("szamlaLetoltes", options.downloadPdf ?? true),
740
+ el("valaszVerzio", 2),
741
+ optionalEl("szamlaKulsoAzon", optionalText$1(options.externalId))
742
+ ]),
743
+ el("fejlec", [
744
+ el("szamlaszam", invoiceNumber),
745
+ optionalEl("keltDatum", optionalAgentDate$1(options.issueDate, "issueDate")),
746
+ optionalEl("teljesitesDatum", optionalAgentDate$1(options.fulfillmentDate, "fulfillmentDate")),
747
+ optionalEl("megjegyzes", optionalText$1(options.comment)),
748
+ el("tipus", "SS"),
749
+ optionalEl("szamlaSablon", validateTemplate(options.template))
750
+ ]),
751
+ optionalEl("elado", [
752
+ optionalEl("emailReplyto", optionalText$1(email?.replyTo)),
753
+ optionalEl("emailTargy", optionalText$1(email?.subject)),
754
+ optionalEl("emailSzoveg", optionalText$1(email?.text))
755
+ ]),
756
+ optionalEl("vevo", [
757
+ optionalEl("email", optionalText$1(buyer?.email)),
758
+ optionalEl("adoszam", optionalText$1(buyer?.taxNumber)),
759
+ optionalEl("adoszamEU", optionalText$1(buyer?.euTaxNumber))
760
+ ])
761
+ ]
762
+ });
763
+ }
764
+ function parseReverseInvoiceResponse(response, originalInvoiceNumber) {
765
+ const result = parseInvoiceResult(response);
766
+ if (result.number === void 0) throw unexpectedResponse(response, "A válaszban nincs sztornó számlaszám.");
767
+ 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.`, {
768
+ category: "validation",
769
+ action: response.action,
770
+ httpStatus: response.status,
771
+ 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."
772
+ });
773
+ return {
774
+ ...result,
775
+ number: result.number
776
+ };
777
+ }
778
+ async function reverseInvoice(ctx, input, options = {}) {
779
+ const invoiceNumber = normalizeInput$2(input).invoiceNumber;
780
+ const xml = buildReverseInvoiceXml(ctx.credentials, input);
781
+ return ctx.execute({
782
+ action: "reverseInvoice",
783
+ xml,
784
+ signal: options.signal
785
+ }, (response) => parseReverseInvoiceResponse(response, invoiceNumber));
786
+ }
787
+ //#endregion
788
+ //#region src/receipts/get.ts
789
+ const GET_RECEIPT_NAMESPACE = "http://www.szamlazz.hu/xmlnyugtaget";
790
+ function normalizeInput$1(input) {
791
+ return typeof input === "string" ? { receiptNumber: input } : input;
792
+ }
793
+ function resolveIdentifier(input) {
794
+ const receiptNumber = optionalText(input.receiptNumber);
795
+ const orderNumber = optionalText(input.orderNumber);
796
+ 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).");
797
+ 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.");
798
+ return {
799
+ receiptNumber,
800
+ orderNumber
801
+ };
802
+ }
803
+ function buildGetReceiptXml(credentials, input) {
804
+ const normalized = normalizeInput$1(input);
805
+ const { receiptNumber, orderNumber } = resolveIdentifier(normalized);
806
+ return buildXmlDocument({
807
+ root: "xmlnyugtaget",
808
+ namespace: GET_RECEIPT_NAMESPACE,
809
+ schemaLocation: `${RECEIPT_XSD_BASE_URL}nyugtaget/xmlnyugtaget.xsd`,
810
+ children: [el("beallitasok", [...credentials, el("pdfLetoltes", normalized.downloadPdf ?? true)]), el("fejlec", [
811
+ optionalEl("nyugtaszam", receiptNumber),
812
+ optionalEl("rendelesSzam", orderNumber),
813
+ optionalEl("hivasAzonosito", optionalText(normalized.callId)),
814
+ optionalEl("pdfSablon", validateTemplate$1(normalized.template))
815
+ ])]
816
+ });
817
+ }
818
+ function getReceipt(ctx, input, options = {}) {
819
+ const xml = buildGetReceiptXml(ctx.credentials, input);
820
+ return ctx.execute({
821
+ action: "getReceipt",
822
+ xml,
823
+ signal: options.signal,
824
+ safeToRetry: true
825
+ }, parseReceiptResponse);
826
+ }
827
+ //#endregion
828
+ //#region src/receipts/reverse.ts
829
+ const REVERSE_RECEIPT_NAMESPACE = "http://www.szamlazz.hu/xmlnyugtast";
830
+ function normalizeInput(input) {
831
+ return typeof input === "string" ? { receiptNumber: input } : input;
832
+ }
833
+ function buildReverseReceiptXml(credentials, input) {
834
+ const normalized = normalizeInput(input);
835
+ return buildXmlDocument({
836
+ root: "xmlnyugtast",
837
+ namespace: REVERSE_RECEIPT_NAMESPACE,
838
+ schemaLocation: `${RECEIPT_XSD_BASE_URL}nyugtast/xmlnyugtast.xsd`,
839
+ children: [el("beallitasok", [...credentials, el("pdfLetoltes", normalized.downloadPdf ?? true)]), el("fejlec", [
840
+ el("nyugtaszam", requireReceiptNumber(normalized.receiptNumber)),
841
+ optionalEl("pdfSablon", validateTemplate$1(normalized.template)),
842
+ optionalEl("hivasAzonosito", optionalText(normalized.callId))
843
+ ])]
844
+ });
845
+ }
846
+ function reverseReceipt(ctx, input, options = {}) {
847
+ const normalized = normalizeInput(input);
848
+ const xml = buildReverseReceiptXml(ctx.credentials, normalized);
849
+ return ctx.execute({
850
+ action: "reverseReceipt",
851
+ xml,
852
+ signal: options.signal,
853
+ safeToRetry: optionalText(normalized.callId) !== void 0
854
+ }, parseReceiptResponse);
855
+ }
856
+ //#endregion
857
+ //#region src/receipts/send.ts
858
+ const SEND_RECEIPT_NAMESPACE = "http://www.szamlazz.hu/xmlnyugtasend";
859
+ const EMAIL_PATTERN = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
860
+ function isValidEmail(value) {
861
+ return EMAIL_PATTERN.test(value);
862
+ }
863
+ function assertEmail(value, field) {
864
+ if (!isValidEmail(value)) throw receiptValidationError(`Érvénytelen e-mail cím a(z) ${field} mezőben: ${value}`);
865
+ return value;
866
+ }
867
+ function normalizeEmails(emails) {
868
+ const list = (typeof emails === "string" ? [emails] : [...emails]).flatMap((entry) => entry.split(/[,;]/)).map((entry) => entry.trim()).filter((entry) => entry !== "");
869
+ if (list.length === 0) throw receiptValidationError("Adj meg legalább egy címzett e-mail címet (emails).");
870
+ return list.map((email) => assertEmail(email, "emails"));
871
+ }
872
+ function buildSendReceiptXml(credentials, input) {
873
+ const receiptNumber = requireReceiptNumber(input.receiptNumber);
874
+ const emails = normalizeEmails(input.emails);
875
+ const replyTo = optionalText(input.replyTo);
876
+ if (replyTo !== void 0) assertEmail(replyTo, "replyTo");
877
+ return buildXmlDocument({
878
+ root: "xmlnyugtasend",
879
+ namespace: SEND_RECEIPT_NAMESPACE,
880
+ schemaLocation: `${RECEIPT_XSD_BASE_URL}nyugtasend/xmlnyugtasend.xsd`,
881
+ children: [
882
+ el("beallitasok", credentials),
883
+ el("fejlec", [el("nyugtaszam", receiptNumber)]),
884
+ el("emailKuldes", [
885
+ el("email", emails.join(",")),
886
+ optionalEl("emailReplyto", replyTo),
887
+ el("emailTargy", optionalText(input.subject) ?? `Nyugta ${receiptNumber}`),
888
+ optionalEl("emailSzoveg", input.text?.trim() ? input.text : void 0)
889
+ ])
890
+ ]
891
+ });
892
+ }
893
+ function parseSendReceiptResponse(response) {
894
+ throwIfHeaderError(response);
895
+ throwIfTextError(response);
896
+ if (!looksLikeXml(response)) {
897
+ throwIfHttpError(response);
898
+ if (parseDoneText(response.text())) return;
899
+ throw unexpectedResponse(response, "XML választ vártunk a nyugta kiküldésére.");
900
+ }
901
+ const root = parseResponseXml(response);
902
+ throwIfXmlFailure(root, response);
903
+ if (childBoolean(root, "sikeres") !== true) {
904
+ throwIfHttpError(response);
905
+ throw unexpectedResponse(response, "A válasz nem jelez sikeres kiküldést.");
906
+ }
907
+ }
908
+ function sendReceipt(ctx, input, options = {}) {
909
+ const xml = buildSendReceiptXml(ctx.credentials, input);
910
+ return ctx.execute({
911
+ action: "sendReceipt",
912
+ xml,
913
+ signal: options.signal
914
+ }, parseSendReceiptResponse);
915
+ }
916
+ //#endregion
917
+ //#region src/taxpayer/address.ts
918
+ const ROMAN_NUMERAL = /^[IVX]{1,5}\.?$/;
919
+ function isShouting(value) {
920
+ return value === value.toUpperCase() && value !== value.toLowerCase();
921
+ }
922
+ function capitalizeWord(word) {
923
+ if (ROMAN_NUMERAL.test(word)) return word;
924
+ return word.split("-").map((part) => part.toLowerCase().replace(/\p{L}/u, (letter) => letter.toUpperCase())).join("-");
925
+ }
926
+ function toReadableName(value) {
927
+ if (value === void 0 || !isShouting(value)) return value;
928
+ return value.split(" ").map(capitalizeWord).join(" ");
929
+ }
930
+ function toLowerIfShouting(value) {
931
+ return value !== void 0 && isShouting(value) ? value.toLowerCase() : value;
932
+ }
933
+ function withOrdinalDot(value) {
934
+ if (value === void 0) return void 0;
935
+ return /^\d+$/.test(value) ? `${value}.` : value;
936
+ }
937
+ function joinParts(parts) {
938
+ return parts.filter((part) => part !== void 0 && part !== "").join(" ");
939
+ }
940
+ function formatAddress(address) {
941
+ return [
942
+ joinParts([address.postalCode, address.city]),
943
+ joinParts([
944
+ address.street,
945
+ address.publicPlaceCategory,
946
+ withOrdinalDot(address.number),
947
+ address.building === void 0 ? void 0 : `${address.building} ép.`,
948
+ address.staircase === void 0 ? void 0 : `${withOrdinalDot(address.staircase)} lh.`,
949
+ address.floor === void 0 ? void 0 : `${withOrdinalDot(address.floor)} em.`,
950
+ address.door === void 0 ? void 0 : `${withOrdinalDot(address.door)} ajtó`
951
+ ]),
952
+ address.lotNumber === void 0 ? void 0 : `hrsz. ${address.lotNumber}`,
953
+ address.countryCode === "" || address.countryCode === "HU" ? void 0 : address.countryCode
954
+ ].filter((part) => part !== void 0 && part !== "").join(", ");
955
+ }
956
+ function readDetailedAddress(element) {
957
+ return {
958
+ countryCode: childText(element, "countryCode"),
959
+ region: childText(element, "region"),
960
+ postalCode: childText(element, "postalCode"),
961
+ city: childText(element, "city"),
962
+ streetName: childText(element, "streetName"),
963
+ publicPlaceCategory: childText(element, "publicPlaceCategory"),
964
+ number: childText(element, "number"),
965
+ building: childText(element, "building"),
966
+ staircase: childText(element, "staircase"),
967
+ floor: childText(element, "floor"),
968
+ door: childText(element, "door"),
969
+ lotNumber: childText(element, "lotNumber")
970
+ };
971
+ }
972
+ function parseTaxpayerAddress(item) {
973
+ const raw = readDetailedAddress(findChild(item, "taxpayerAddress"));
974
+ const address = {
975
+ type: childText(item, "taxpayerAddressType")?.toUpperCase() ?? "",
976
+ countryCode: raw.countryCode?.toUpperCase() ?? "",
977
+ region: toReadableName(raw.region),
978
+ postalCode: raw.postalCode ?? "",
979
+ city: toReadableName(raw.city) ?? "",
980
+ street: toReadableName(raw.streetName),
981
+ publicPlaceCategory: toLowerIfShouting(raw.publicPlaceCategory),
982
+ number: raw.number,
983
+ building: raw.building,
984
+ staircase: raw.staircase,
985
+ floor: raw.floor,
986
+ door: raw.door,
987
+ lotNumber: raw.lotNumber
988
+ };
989
+ return {
990
+ ...address,
991
+ formatted: formatAddress(address),
992
+ raw
993
+ };
994
+ }
995
+ //#endregion
996
+ //#region src/taxpayer/query-taxpayer.ts
997
+ const TAXPAYER_NAMESPACE = "http://www.szamlazz.hu/xmltaxpayer";
998
+ const TAXPAYER_SCHEMA_LOCATION = "http://www.szamlazz.hu/docs/xsds/agent/xmltaxpayer.xsd";
999
+ function toTaxpayerId(taxNumber) {
1000
+ const digits = typeof taxNumber === "string" ? taxNumber.replace(/[\s-]+/g, "").replace(/^HU/i, "") : "";
1001
+ 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).`, {
1002
+ category: "validation",
1003
+ action: "queryTaxpayer"
1004
+ });
1005
+ return digits.slice(0, 8);
1006
+ }
1007
+ function buildQueryTaxpayerXml(credentials, taxNumber) {
1008
+ return buildXmlDocument({
1009
+ root: "xmltaxpayer",
1010
+ namespace: TAXPAYER_NAMESPACE,
1011
+ schemaLocation: TAXPAYER_SCHEMA_LOCATION,
1012
+ children: [el("beallitasok", credentials), el("torzsszam", toTaxpayerId(taxNumber))]
1013
+ });
1014
+ }
1015
+ function throwIfNavError(root, response) {
1016
+ const result = findChild(root, "result");
1017
+ if (childText(result, "funcCode")?.toUpperCase() !== "ERROR") return;
1018
+ const errorCode = childText(result, "errorCode");
1019
+ const code = parseErrorCode(errorCode);
1020
+ const message = childText(result, "message");
1021
+ const textCode = code === void 0 ? errorCode : void 0;
1022
+ throw createAgentError({
1023
+ code,
1024
+ message: textCode === void 0 ? message : [textCode, message].filter(Boolean).join(": "),
1025
+ action: response.action,
1026
+ httpStatus: response.status,
1027
+ rawResponse: response.text().slice(0, 2e3)
1028
+ });
1029
+ }
1030
+ function readTaxNumber(data) {
1031
+ const detail = findChild(data, "taxNumberDetail");
1032
+ const taxpayerId = childText(detail, "taxpayerId");
1033
+ if (taxpayerId === void 0) return void 0;
1034
+ const vatCode = childText(detail, "vatCode");
1035
+ const countyCode = childText(detail, "countyCode");
1036
+ return {
1037
+ taxpayerId,
1038
+ vatCode,
1039
+ countyCode,
1040
+ formatted: vatCode !== void 0 && countyCode !== void 0 ? `${taxpayerId}-${vatCode}-${countyCode}` : void 0
1041
+ };
1042
+ }
1043
+ function readAddresses(data) {
1044
+ return findChildren(findChild(data, "taxpayerAddressList"), "taxpayerAddressItem").map(parseTaxpayerAddress);
1045
+ }
1046
+ function readRequestId(root) {
1047
+ const requestId = childText(findChild(root, "header"), "requestId");
1048
+ return requestId === "-" ? void 0 : requestId;
1049
+ }
1050
+ function parseQueryTaxpayerResponse(response) {
1051
+ throwIfAnyError(response);
1052
+ const root = parseResponseXml(response);
1053
+ throwIfXmlFailure(root, response);
1054
+ if (root.name !== "QueryTaxpayerResponse") throw unexpectedResponse(response, "QueryTaxpayerResponse XML választ vártunk.");
1055
+ throwIfNavError(root, response);
1056
+ const requestId = readRequestId(root);
1057
+ const infoDate = childText(root, "infoDate");
1058
+ const data = findChild(root, "taxpayerData");
1059
+ const validity = childBoolean(root, "taxpayerValidity");
1060
+ if (validity === false || data === void 0) return {
1061
+ valid: validity === true,
1062
+ addresses: [],
1063
+ infoDate,
1064
+ requestId
1065
+ };
1066
+ const addresses = readAddresses(data);
1067
+ return {
1068
+ valid: true,
1069
+ name: childText(data, "taxpayerName"),
1070
+ shortName: childText(data, "taxpayerShortName"),
1071
+ taxNumber: readTaxNumber(data),
1072
+ address: addresses.find((address) => address.type === "HQ") ?? addresses[0],
1073
+ addresses,
1074
+ incorporation: childText(data, "incorporation"),
1075
+ vatGroupMembership: childText(data, "vatGroupMembership"),
1076
+ infoDate,
1077
+ requestId
1078
+ };
1079
+ }
1080
+ async function queryTaxpayer(ctx, taxNumber, options = {}) {
1081
+ const xml = buildQueryTaxpayerXml(ctx.credentials, taxNumber);
1082
+ return ctx.execute({
1083
+ action: "queryTaxpayer",
1084
+ xml,
1085
+ signal: options.signal,
1086
+ safeToRetry: true
1087
+ }, parseQueryTaxpayerResponse);
1088
+ }
1089
+ //#endregion
1090
+ //#region src/client.ts
1091
+ const CREDENTIAL_PROBE_INVOICE_NUMBER = "KASSZA-CREDENTIAL-PROBE-0";
1092
+ async function nullIfNotFound(promise) {
1093
+ try {
1094
+ return await promise;
1095
+ } catch (error) {
1096
+ if (isSzamlazzError(error) && (error.isNotFound || error.code === 7)) return null;
1097
+ throw error;
1098
+ }
1099
+ }
1100
+ function attemptKeyOf(target) {
1101
+ if (typeof target === "string") return target;
1102
+ const key = target.details?.attemptKey;
1103
+ if (key === void 0) throw new TypeError("A resetAttempts egy attempt_limit hibát vagy annak details.attemptKey kulcsát várja.");
1104
+ return key;
1105
+ }
1106
+ function invoiceNumberOf(input) {
1107
+ return typeof input === "string" ? input : input.invoiceNumber;
1108
+ }
1109
+ function receiptNumberOf(input) {
1110
+ return typeof input === "string" ? input : input.receiptNumber;
1111
+ }
1112
+ function createInvoicesApi(ctx, defaults, onDocument) {
1113
+ const api = {
1114
+ async create(input, options) {
1115
+ const document = await createInvoice(ctx, defaults, input, options);
1116
+ await emitDocumentEvent(onDocument, {
1117
+ kind: "invoice",
1118
+ action: "created",
1119
+ number: document.number,
1120
+ document,
1121
+ input
1122
+ });
1123
+ return document;
1124
+ },
1125
+ createOnce: (input, options) => createInvoiceOnce(api, input, options),
1126
+ preview: (input, options) => previewInvoice(ctx, defaults, input, options),
1127
+ async reverse(input, options) {
1128
+ const document = await reverseInvoice(ctx, input, options);
1129
+ await emitDocumentEvent(onDocument, {
1130
+ kind: "invoice",
1131
+ action: "reversed",
1132
+ number: document.number,
1133
+ reversedNumber: invoiceNumberOf(input),
1134
+ document
1135
+ });
1136
+ return document;
1137
+ },
1138
+ async registerPayment(input, options) {
1139
+ const document = await registerPayment(ctx, input, options);
1140
+ await emitDocumentEvent(onDocument, {
1141
+ kind: "invoice",
1142
+ action: "payment",
1143
+ number: document.invoiceNumber,
1144
+ document
1145
+ });
1146
+ return document;
1147
+ },
1148
+ async clearPayments(input, options) {
1149
+ const document = await clearPayments(ctx, input, options);
1150
+ await emitDocumentEvent(onDocument, {
1151
+ kind: "invoice",
1152
+ action: "payment",
1153
+ number: document.invoiceNumber,
1154
+ document
1155
+ });
1156
+ return document;
1157
+ },
1158
+ getPdf: (reference, options) => getInvoicePdf(ctx, reference, options),
1159
+ get: (reference, query, options) => getInvoice(ctx, reference, query, options),
1160
+ find: (reference, query, options) => nullIfNotFound(getInvoice(ctx, reference, query, options)),
1161
+ deleteProforma: (reference, options) => deleteProforma(ctx, reference, options)
1162
+ };
1163
+ return api;
1164
+ }
1165
+ function createReceiptsApi(ctx, defaults, invoices, onDocument) {
1166
+ const api = {
1167
+ async create(input, options) {
1168
+ const document = await createReceipt(ctx, defaults, input, options);
1169
+ await emitDocumentEvent(onDocument, {
1170
+ kind: "receipt",
1171
+ action: "created",
1172
+ number: document.number,
1173
+ document
1174
+ });
1175
+ return document;
1176
+ },
1177
+ createOnce: (input, options) => createReceiptOnce(api, input, options),
1178
+ async reverse(input, options) {
1179
+ const document = await reverseReceipt(ctx, input, options);
1180
+ await emitDocumentEvent(onDocument, {
1181
+ kind: "receipt",
1182
+ action: "reversed",
1183
+ number: document.number,
1184
+ reversedNumber: receiptNumberOf(input),
1185
+ document
1186
+ });
1187
+ return document;
1188
+ },
1189
+ get: (input, options) => getReceipt(ctx, input, options),
1190
+ find: (input, options) => nullIfNotFound(getReceipt(ctx, input, options)),
1191
+ send: (input, options) => sendReceipt(ctx, input, options),
1192
+ convertToInvoice: (input, options) => convertReceiptToInvoice({
1193
+ receipts: api,
1194
+ invoices
1195
+ }, input, options)
1196
+ };
1197
+ return api;
1198
+ }
1199
+ function createKassza(options = {}) {
1200
+ const ctx = createAgentContext(options);
1201
+ const onDocument = options.hooks?.onDocument;
1202
+ const invoices = createInvoicesApi(ctx, options.defaults?.invoice ?? {}, onDocument);
1203
+ const receipts = createReceiptsApi(ctx, options.defaults?.receipt ?? {}, invoices, onDocument);
1204
+ return {
1205
+ invoices,
1206
+ receipts,
1207
+ taxpayer: { query: (taxNumber, requestOptions) => queryTaxpayer(ctx, taxNumber, requestOptions) },
1208
+ async verifyCredentials(requestOptions) {
1209
+ try {
1210
+ await getInvoicePdf(ctx, CREDENTIAL_PROBE_INVOICE_NUMBER, requestOptions);
1211
+ return true;
1212
+ } catch (error) {
1213
+ if (!isSzamlazzError(error)) throw error;
1214
+ if (error.category === "auth") return false;
1215
+ if (error.isNotFound || error.code === 7) return true;
1216
+ throw error;
1217
+ }
1218
+ },
1219
+ resetSession: () => ctx.resetSession(),
1220
+ resetAttempts: (target) => ctx.resetAttempts(attemptKeyOf(target)),
1221
+ issueForPayment: (payment, issueOptions) => issueForPayment({
1222
+ invoices,
1223
+ receipts
1224
+ }, payment, issueOptions)
1225
+ };
1226
+ }
1227
+ //#endregion
1228
+ export { createAgentContext as a, attemptLedgerKey as c, buildCreateInvoiceXml as i, queryTaxpayer as n, ATTEMPT_LEDGER_KEY_PREFIX as o, getInvoicePdf as r, ATTEMPT_LEDGER_TTL_SECONDS as s, createKassza as t };