@fast-white-cat/integration-ksef-direct 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 (140) hide show
  1. package/README.md +36 -0
  2. package/dist/index.js +2 -0
  3. package/dist/index.js.map +7 -0
  4. package/dist/modules/integration_ksef_direct/acl.js +13 -0
  5. package/dist/modules/integration_ksef_direct/acl.js.map +7 -0
  6. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/documents/[id].js +92 -0
  7. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/documents/[id].js.map +7 -0
  8. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/documents.js +105 -0
  9. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/documents.js.map +7 -0
  10. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/health.js +158 -0
  11. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/health.js.map +7 -0
  12. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/received-documents/[id].js +86 -0
  13. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/received-documents/[id].js.map +7 -0
  14. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/received-documents.js +112 -0
  15. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/received-documents.js.map +7 -0
  16. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/seller-info.js +54 -0
  17. package/dist/modules/integration_ksef_direct/api/get/integration-ksef-direct/seller-info.js.map +7 -0
  18. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/documents/[id]/send.js +64 -0
  19. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/documents/[id]/send.js.map +7 -0
  20. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/documents.js +104 -0
  21. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/documents.js.map +7 -0
  22. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/invoice-numbers.js +41 -0
  23. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/invoice-numbers.js.map +7 -0
  24. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/fetch.js +172 -0
  25. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/fetch.js.map +7 -0
  26. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/sync.js +80 -0
  27. package/dist/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/sync.js.map +7 -0
  28. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/new/page.js +441 -0
  29. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/new/page.js.map +7 -0
  30. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/new/page.meta.js +8 -0
  31. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/new/page.meta.js.map +7 -0
  32. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/page.js +193 -0
  33. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/page.js.map +7 -0
  34. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/received-documents/page.js +314 -0
  35. package/dist/modules/integration_ksef_direct/backend/integration-ksef-direct/received-documents/page.js.map +7 -0
  36. package/dist/modules/integration_ksef_direct/backend/page.js +154 -0
  37. package/dist/modules/integration_ksef_direct/backend/page.js.map +7 -0
  38. package/dist/modules/integration_ksef_direct/commands/create-ksef-direct-document.js +80 -0
  39. package/dist/modules/integration_ksef_direct/commands/create-ksef-direct-document.js.map +7 -0
  40. package/dist/modules/integration_ksef_direct/commands/enqueue-ksef-direct-document.js +43 -0
  41. package/dist/modules/integration_ksef_direct/commands/enqueue-ksef-direct-document.js.map +7 -0
  42. package/dist/modules/integration_ksef_direct/data/entities.js +224 -0
  43. package/dist/modules/integration_ksef_direct/data/entities.js.map +7 -0
  44. package/dist/modules/integration_ksef_direct/data/validators.js +103 -0
  45. package/dist/modules/integration_ksef_direct/data/validators.js.map +7 -0
  46. package/dist/modules/integration_ksef_direct/di.js +11 -0
  47. package/dist/modules/integration_ksef_direct/di.js.map +7 -0
  48. package/dist/modules/integration_ksef_direct/events.js +21 -0
  49. package/dist/modules/integration_ksef_direct/events.js.map +7 -0
  50. package/dist/modules/integration_ksef_direct/index.js +10 -0
  51. package/dist/modules/integration_ksef_direct/index.js.map +7 -0
  52. package/dist/modules/integration_ksef_direct/integration.js +56 -0
  53. package/dist/modules/integration_ksef_direct/integration.js.map +7 -0
  54. package/dist/modules/integration_ksef_direct/lib/health.js +32 -0
  55. package/dist/modules/integration_ksef_direct/lib/health.js.map +7 -0
  56. package/dist/modules/integration_ksef_direct/lib/invoiceNumberFormat.js +23 -0
  57. package/dist/modules/integration_ksef_direct/lib/invoiceNumberFormat.js.map +7 -0
  58. package/dist/modules/integration_ksef_direct/lib/ksefClient.js +523 -0
  59. package/dist/modules/integration_ksef_direct/lib/ksefClient.js.map +7 -0
  60. package/dist/modules/integration_ksef_direct/lib/ksefCrypto.js +103 -0
  61. package/dist/modules/integration_ksef_direct/lib/ksefCrypto.js.map +7 -0
  62. package/dist/modules/integration_ksef_direct/lib/ksefFa2Xml.js +123 -0
  63. package/dist/modules/integration_ksef_direct/lib/ksefFa2Xml.js.map +7 -0
  64. package/dist/modules/integration_ksef_direct/lib/ksefXmlParser.js +76 -0
  65. package/dist/modules/integration_ksef_direct/lib/ksefXmlParser.js.map +7 -0
  66. package/dist/modules/integration_ksef_direct/migrations/Migration20260519210000_integration_ksef_direct.js +15 -0
  67. package/dist/modules/integration_ksef_direct/migrations/Migration20260519210000_integration_ksef_direct.js.map +7 -0
  68. package/dist/modules/integration_ksef_direct/migrations/Migration20260520120000_ksef_direct_documents.js +17 -0
  69. package/dist/modules/integration_ksef_direct/migrations/Migration20260520120000_ksef_direct_documents.js.map +7 -0
  70. package/dist/modules/integration_ksef_direct/migrations/Migration20260520220000_ksef_direct_send_queue.js +15 -0
  71. package/dist/modules/integration_ksef_direct/migrations/Migration20260520220000_ksef_direct_send_queue.js.map +7 -0
  72. package/dist/modules/integration_ksef_direct/migrations/Migration20260520230000_ksef_direct_seller_per_document.js +17 -0
  73. package/dist/modules/integration_ksef_direct/migrations/Migration20260520230000_ksef_direct_seller_per_document.js.map +7 -0
  74. package/dist/modules/integration_ksef_direct/migrations/Migration20260521120000_ksef_direct_received_documents.js +16 -0
  75. package/dist/modules/integration_ksef_direct/migrations/Migration20260521120000_ksef_direct_received_documents.js.map +7 -0
  76. package/dist/modules/integration_ksef_direct/migrations/Migration20260521130000_ksef_received_download_urls.js +15 -0
  77. package/dist/modules/integration_ksef_direct/migrations/Migration20260521130000_ksef_received_download_urls.js.map +7 -0
  78. package/dist/modules/integration_ksef_direct/setup.js +11 -0
  79. package/dist/modules/integration_ksef_direct/setup.js.map +7 -0
  80. package/dist/modules/integration_ksef_direct/subscribers/auto-enqueue-ksef-document.js +19 -0
  81. package/dist/modules/integration_ksef_direct/subscribers/auto-enqueue-ksef-document.js.map +7 -0
  82. package/dist/modules/integration_ksef_direct/workers/check-ksef-document-status.js +103 -0
  83. package/dist/modules/integration_ksef_direct/workers/check-ksef-document-status.js.map +7 -0
  84. package/dist/modules/integration_ksef_direct/workers/send-ksef-document.js +104 -0
  85. package/dist/modules/integration_ksef_direct/workers/send-ksef-document.js.map +7 -0
  86. package/dist/modules/integration_ksef_direct/workers/sync-received-documents.js +137 -0
  87. package/dist/modules/integration_ksef_direct/workers/sync-received-documents.js.map +7 -0
  88. package/dist/types/declarations.d.js +1 -0
  89. package/dist/types/declarations.d.js.map +7 -0
  90. package/package.json +98 -0
  91. package/src/index.ts +1 -0
  92. package/src/modules/integration_ksef_direct/__tests__/invoiceNumberFormat.test.ts +42 -0
  93. package/src/modules/integration_ksef_direct/__tests__/ksefFa2Xml.test.ts +407 -0
  94. package/src/modules/integration_ksef_direct/__tests__/ksefXmlParser.test.ts +230 -0
  95. package/src/modules/integration_ksef_direct/acl.ts +9 -0
  96. package/src/modules/integration_ksef_direct/api/get/integration-ksef-direct/documents/[id].ts +94 -0
  97. package/src/modules/integration_ksef_direct/api/get/integration-ksef-direct/documents.ts +111 -0
  98. package/src/modules/integration_ksef_direct/api/get/integration-ksef-direct/health.ts +194 -0
  99. package/src/modules/integration_ksef_direct/api/get/integration-ksef-direct/received-documents/[id].ts +88 -0
  100. package/src/modules/integration_ksef_direct/api/get/integration-ksef-direct/received-documents.ts +119 -0
  101. package/src/modules/integration_ksef_direct/api/get/integration-ksef-direct/seller-info.ts +62 -0
  102. package/src/modules/integration_ksef_direct/api/post/integration-ksef-direct/documents/[id]/send.ts +64 -0
  103. package/src/modules/integration_ksef_direct/api/post/integration-ksef-direct/documents.ts +109 -0
  104. package/src/modules/integration_ksef_direct/api/post/integration-ksef-direct/invoice-numbers.ts +40 -0
  105. package/src/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/fetch.ts +185 -0
  106. package/src/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/sync.ts +86 -0
  107. package/src/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/new/page.meta.ts +4 -0
  108. package/src/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/new/page.tsx +470 -0
  109. package/src/modules/integration_ksef_direct/backend/integration-ksef-direct/documents/page.tsx +233 -0
  110. package/src/modules/integration_ksef_direct/backend/integration-ksef-direct/received-documents/page.tsx +415 -0
  111. package/src/modules/integration_ksef_direct/backend/page.tsx +183 -0
  112. package/src/modules/integration_ksef_direct/commands/create-ksef-direct-document.ts +93 -0
  113. package/src/modules/integration_ksef_direct/commands/enqueue-ksef-direct-document.ts +57 -0
  114. package/src/modules/integration_ksef_direct/data/entities.ts +195 -0
  115. package/src/modules/integration_ksef_direct/data/validators.ts +115 -0
  116. package/src/modules/integration_ksef_direct/di.ts +9 -0
  117. package/src/modules/integration_ksef_direct/events.ts +18 -0
  118. package/src/modules/integration_ksef_direct/i18n/en.json +115 -0
  119. package/src/modules/integration_ksef_direct/i18n/pl.json +115 -0
  120. package/src/modules/integration_ksef_direct/index.ts +6 -0
  121. package/src/modules/integration_ksef_direct/integration.ts +54 -0
  122. package/src/modules/integration_ksef_direct/lib/health.ts +43 -0
  123. package/src/modules/integration_ksef_direct/lib/invoiceNumberFormat.ts +23 -0
  124. package/src/modules/integration_ksef_direct/lib/ksefClient.ts +668 -0
  125. package/src/modules/integration_ksef_direct/lib/ksefCrypto.ts +138 -0
  126. package/src/modules/integration_ksef_direct/lib/ksefFa2Xml.ts +147 -0
  127. package/src/modules/integration_ksef_direct/lib/ksefXmlParser.ts +97 -0
  128. package/src/modules/integration_ksef_direct/migrations/.snapshot-open-mercato.json +1028 -0
  129. package/src/modules/integration_ksef_direct/migrations/Migration20260519210000_integration_ksef_direct.ts +15 -0
  130. package/src/modules/integration_ksef_direct/migrations/Migration20260520120000_ksef_direct_documents.ts +17 -0
  131. package/src/modules/integration_ksef_direct/migrations/Migration20260520220000_ksef_direct_send_queue.ts +15 -0
  132. package/src/modules/integration_ksef_direct/migrations/Migration20260520230000_ksef_direct_seller_per_document.ts +17 -0
  133. package/src/modules/integration_ksef_direct/migrations/Migration20260521120000_ksef_direct_received_documents.ts +16 -0
  134. package/src/modules/integration_ksef_direct/migrations/Migration20260521130000_ksef_received_download_urls.ts +15 -0
  135. package/src/modules/integration_ksef_direct/setup.ts +9 -0
  136. package/src/modules/integration_ksef_direct/subscribers/auto-enqueue-ksef-document.ts +21 -0
  137. package/src/modules/integration_ksef_direct/workers/check-ksef-document-status.ts +129 -0
  138. package/src/modules/integration_ksef_direct/workers/send-ksef-document.ts +137 -0
  139. package/src/modules/integration_ksef_direct/workers/sync-received-documents.ts +171 -0
  140. package/src/types/declarations.d.ts +1 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../src/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/fetch.ts"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { ReceivedDocumentFetchSchema } from '../../../../data/validators'\nimport { KsefNetworkError } from '../../../../lib/ksefClient'\n\nexport const metadata = {\n path: '/integration-ksef-direct/received-documents/fetch',\n POST: { requireAuth: true, requireFeatures: ['integration_ksef_direct.received_documents.sync'] },\n}\n\nconst receivedDocumentResponseSchema = z.object({\n id: z.string().uuid(),\n ksefReferenceNumber: z.string(),\n invoiceNumber: z.string().nullable(),\n sellerNip: z.string().nullable(),\n sellerName: z.string().nullable(),\n issueDate: z.string().nullable(),\n currency: z.string().nullable(),\n netAmount: z.string().nullable(),\n vatAmount: z.string().nullable(),\n grossAmount: z.string().nullable(),\n rawXml: z.string(),\n status: z.literal('downloaded'),\n errorMessage: z.null(),\n syncedAt: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const body = await readJsonSafe(req, {})\n const parsed = ReceivedDocumentFetchSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid request' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const credentialsService = container.resolve('integrationCredentialsService') as any\n const rawCreds = credentialsService\n ? await credentialsService.resolve('integration_ksef_direct', {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n : null\n\n const { KsefDirectCredentialsSchema } = await import('../../../../data/validators')\n const credsParsed = KsefDirectCredentialsSchema.safeParse(rawCreds)\n if (!credsParsed.success) {\n return NextResponse.json({ error: 'KSeF credentials not configured' }, { status: 409 })\n }\n\n const credentials = {\n ksefToken: credsParsed.data.ksef_token,\n nip: credsParsed.data.nip,\n environment: credsParsed.data.environment,\n tenantId: auth.tenantId,\n }\n\n const { downloadInvoice } = await import('../../../../lib/ksefClient')\n const { parseReceivedInvoiceXml } = await import('../../../../lib/ksefXmlParser')\n const { KsefDirectReceivedDocument } = await import('../../../../data/entities')\n\n let rawContent: string\n let upoDownloadUrl: string | null = null\n let invoiceDownloadUrl: string | null = null\n\n try {\n const result = await downloadInvoice(credentials, parsed.data.ksefReferenceNumber)\n rawContent = result.rawContent\n upoDownloadUrl = result.upoDownloadUrl\n invoiceDownloadUrl = result.invoiceDownloadUrl\n } catch (err) {\n if (err instanceof KsefNetworkError) {\n return NextResponse.json({ error: `KSeF API error: ${err.message}` }, { status: 502 })\n }\n if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {\n return NextResponse.json({ error: 'KSeF API request timed out' }, { status: 504 })\n }\n throw err\n }\n\n const parsedXml = parseReceivedInvoiceXml(rawContent)\n const em = container.resolve('em') as any\n const now = new Date()\n\n let record = await em.findOne(KsefDirectReceivedDocument, {\n organizationId: auth.orgId,\n ksefReferenceNumber: parsed.data.ksefReferenceNumber,\n })\n\n if (record) {\n record.rawXml = rawContent\n if (parsedXml.invoiceNumber) record.invoiceNumber = parsedXml.invoiceNumber\n if (parsedXml.sellerNip) record.sellerNip = parsedXml.sellerNip\n if (parsedXml.sellerName) record.sellerName = parsedXml.sellerName\n if (parsedXml.issueDate) record.issueDate = parsedXml.issueDate\n if (parsedXml.currency) record.currency = parsedXml.currency\n if (parsedXml.netAmount) record.netAmount = parsedXml.netAmount\n if (parsedXml.vatAmount) record.vatAmount = parsedXml.vatAmount\n if (parsedXml.grossAmount) record.grossAmount = parsedXml.grossAmount\n if (upoDownloadUrl) record.upoDownloadUrl = upoDownloadUrl\n if (invoiceDownloadUrl) record.invoiceDownloadUrl = invoiceDownloadUrl\n record.status = 'downloaded'\n record.errorMessage = null\n record.syncedAt = now\n record.updatedAt = now\n } else {\n record = em.create(KsefDirectReceivedDocument, {\n organizationId: auth.orgId,\n tenantId: auth.tenantId,\n ksefReferenceNumber: parsed.data.ksefReferenceNumber,\n rawXml: rawContent,\n invoiceNumber: parsedXml.invoiceNumber ?? null,\n sellerNip: parsedXml.sellerNip ?? null,\n sellerName: parsedXml.sellerName ?? null,\n issueDate: parsedXml.issueDate ?? null,\n currency: parsedXml.currency ?? null,\n netAmount: parsedXml.netAmount ?? null,\n vatAmount: parsedXml.vatAmount ?? null,\n grossAmount: parsedXml.grossAmount ?? null,\n upoDownloadUrl,\n invoiceDownloadUrl,\n status: 'downloaded',\n syncedAt: now,\n })\n em.persist(record)\n }\n\n await em.flush()\n\n return NextResponse.json({\n id: record.id,\n ksefReferenceNumber: record.ksefReferenceNumber,\n invoiceNumber: record.invoiceNumber ?? null,\n sellerNip: record.sellerNip ?? null,\n sellerName: record.sellerName ?? null,\n issueDate: record.issueDate ?? null,\n currency: record.currency ?? null,\n netAmount: record.netAmount ?? null,\n vatAmount: record.vatAmount ?? null,\n grossAmount: record.grossAmount ?? null,\n rawXml: record.rawXml,\n status: 'downloaded',\n errorMessage: null,\n syncedAt: record.syncedAt?.toISOString() ?? now.toISOString(),\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'KSeF Direct',\n summary: 'Fetch received document by KSeF reference',\n methods: {\n POST: {\n summary: 'Fetch and store a single received KSeF document',\n description: 'Downloads the FA(2) XML for a given KSeF reference number and stores it locally. Synchronous \u2014 waits for the download to complete.',\n requestBody: {\n contentType: 'application/json',\n schema: ReceivedDocumentFetchSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Document fetched and stored',\n schema: receivedDocumentResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request', schema: z.object({ error: z.string() }) },\n { status: 409, description: 'KSeF credentials not configured', schema: z.object({ error: z.string() }) },\n { status: 502, description: 'KSeF API error', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
5
+ "mappings":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OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MACxF;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,80 @@
1
+ import { NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
+ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
+ import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
6
+ import { createModuleQueue } from "@open-mercato/queue";
7
+ import { ReceivedDocumentSyncSchema } from "../../../../data/validators.js";
8
+ const metadata = {
9
+ path: "/integration-ksef-direct/received-documents/sync",
10
+ POST: { requireAuth: true, requireFeatures: ["integration_ksef_direct.received_documents.sync"] }
11
+ };
12
+ async function POST(req) {
13
+ const auth = await getAuthFromRequest(req);
14
+ if (!auth?.tenantId || !auth.orgId) {
15
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
16
+ }
17
+ const body = await readJsonSafe(req, {});
18
+ const parsed = ReceivedDocumentSyncSchema.safeParse(body);
19
+ if (!parsed.success) {
20
+ return NextResponse.json(
21
+ { error: "Invalid date range", fieldErrors: parsed.error.flatten().fieldErrors },
22
+ { status: 400 }
23
+ );
24
+ }
25
+ const container = await createRequestContainer();
26
+ const credentialsService = container.resolve("integrationCredentialsService");
27
+ const rawCreds = credentialsService ? await credentialsService.resolve("integration_ksef_direct", {
28
+ tenantId: auth.tenantId,
29
+ organizationId: auth.orgId
30
+ }) : null;
31
+ const { KsefDirectCredentialsSchema } = await import("../../../../data/validators.js");
32
+ if (!KsefDirectCredentialsSchema.safeParse(rawCreds).success) {
33
+ return NextResponse.json(
34
+ { error: "KSeF credentials not configured" },
35
+ { status: 409 }
36
+ );
37
+ }
38
+ const queue = createModuleQueue("ksef_direct_receive");
39
+ const jobId = await queue.enqueue({
40
+ organizationId: auth.orgId,
41
+ tenantId: auth.tenantId,
42
+ dateFrom: parsed.data.dateFrom,
43
+ dateTo: parsed.data.dateTo
44
+ });
45
+ return NextResponse.json({ jobId, message: "Sync job queued" }, { status: 202 });
46
+ }
47
+ const openApi = {
48
+ tag: "KSeF Direct",
49
+ summary: "Sync received documents",
50
+ methods: {
51
+ POST: {
52
+ summary: "Trigger date-range sync of received KSeF documents",
53
+ description: "Enqueues a background worker that fetches all invoices received from KSeF for the given date range.",
54
+ requestBody: {
55
+ contentType: "application/json",
56
+ schema: ReceivedDocumentSyncSchema
57
+ },
58
+ responses: [
59
+ {
60
+ status: 202,
61
+ description: "Sync job queued",
62
+ schema: z.object({
63
+ jobId: z.string(),
64
+ message: z.string()
65
+ })
66
+ }
67
+ ],
68
+ errors: [
69
+ { status: 400, description: "Invalid date range", schema: z.object({ error: z.string() }) },
70
+ { status: 409, description: "KSeF credentials not configured", schema: z.object({ error: z.string() }) }
71
+ ]
72
+ }
73
+ }
74
+ };
75
+ export {
76
+ POST,
77
+ metadata,
78
+ openApi
79
+ };
80
+ //# sourceMappingURL=sync.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../src/modules/integration_ksef_direct/api/post/integration-ksef-direct/received-documents/sync.ts"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { createModuleQueue } from '@open-mercato/queue'\nimport { ReceivedDocumentSyncSchema } from '../../../../data/validators'\nimport type { SyncReceivedDocumentsPayload } from '../../../../workers/sync-received-documents'\n\nexport const metadata = {\n path: '/integration-ksef-direct/received-documents/sync',\n POST: { requireAuth: true, requireFeatures: ['integration_ksef_direct.received_documents.sync'] },\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const body = await readJsonSafe(req, {})\n const parsed = ReceivedDocumentSyncSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n { error: 'Invalid date range', fieldErrors: parsed.error.flatten().fieldErrors },\n { status: 400 },\n )\n }\n\n const container = await createRequestContainer()\n const credentialsService = container.resolve('integrationCredentialsService') as any\n const rawCreds = credentialsService\n ? await credentialsService.resolve('integration_ksef_direct', {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n : null\n\n const { KsefDirectCredentialsSchema } = await import('../../../../data/validators')\n if (!KsefDirectCredentialsSchema.safeParse(rawCreds).success) {\n return NextResponse.json(\n { error: 'KSeF credentials not configured' },\n { status: 409 },\n )\n }\n\n const queue = createModuleQueue<SyncReceivedDocumentsPayload>('ksef_direct_receive')\n const jobId = await queue.enqueue({\n organizationId: auth.orgId,\n tenantId: auth.tenantId,\n dateFrom: parsed.data.dateFrom,\n dateTo: parsed.data.dateTo,\n })\n\n return NextResponse.json({ jobId, message: 'Sync job queued' }, { status: 202 })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'KSeF Direct',\n summary: 'Sync received documents',\n methods: {\n POST: {\n summary: 'Trigger date-range sync of received KSeF documents',\n description: 'Enqueues a background worker that fetches all invoices received from KSeF for the given date range.',\n requestBody: {\n contentType: 'application/json',\n schema: ReceivedDocumentSyncSchema,\n },\n responses: [\n {\n status: 202,\n description: 'Sync job queued',\n schema: z.object({\n jobId: z.string(),\n message: z.string(),\n }),\n },\n ],\n errors: [\n { status: 400, description: 'Invalid date range', schema: z.object({ error: z.string() }) },\n { status: 409, description: 'KSeF credentials not configured', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SA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SAAS,kBAAkB,GAAG,EAAE,QAAQ,IAAI,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE,OAAO;AAAA,YAChB,SAAS,EAAE,OAAO;AAAA,UACpB,CAAC;AAAA,QACH;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QAC1F,EAAE,QAAQ,KAAK,aAAa,mCAAmC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MACzG;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,441 @@
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { useRouter } from "next/navigation";
5
+ import { Plus, RefreshCw, Trash2 } from "lucide-react";
6
+ import { Page, PageBody } from "@open-mercato/ui/backend/Page";
7
+ import { SectionHeader } from "@open-mercato/ui/backend/SectionHeader";
8
+ import { FormField } from "@open-mercato/ui/primitives/form-field";
9
+ import { Button } from "@open-mercato/ui/primitives/button";
10
+ import { IconButton } from "@open-mercato/ui/primitives/icon-button";
11
+ import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
12
+ import { Spinner } from "@open-mercato/ui/primitives/spinner";
13
+ import { flash } from "@open-mercato/ui/backend/FlashMessages";
14
+ import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
15
+ import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
16
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
17
+ const pageMetadata = { features: ["integration_ksef_direct.documents.create"], navHidden: true };
18
+ const VAT_RATES = ["0", "5", "8", "23", "ZW", "NP"];
19
+ const CURRENCIES = ["PLN", "EUR", "USD", "GBP"];
20
+ const VAT_RATE_MULTIPLIERS = { "0": 0, "5": 5, "8": 8, "23": 23, ZW: 0, NP: 0 };
21
+ function round2(v) {
22
+ return Math.round(v * 100) / 100;
23
+ }
24
+ function computeTotals(items) {
25
+ let net = 0, vat = 0;
26
+ for (const item of items) {
27
+ const qty = parseFloat(item.quantity) || 0;
28
+ const price = parseFloat(item.unitNetPrice) || 0;
29
+ const lineNet = round2(qty * price);
30
+ const rate = VAT_RATE_MULTIPLIERS[item.vatRate] ?? 0;
31
+ const lineVat = round2(lineNet * rate / 100);
32
+ net += lineNet;
33
+ vat += lineVat;
34
+ }
35
+ net = round2(net);
36
+ vat = round2(vat);
37
+ return { net, vat, gross: round2(net + vat) };
38
+ }
39
+ function emptyLine() {
40
+ return { description: "", quantity: "1", unit: "szt", unitNetPrice: "0.00", vatRate: "23" };
41
+ }
42
+ function NewKsefDirectDocumentPage() {
43
+ const t = useT();
44
+ const router = useRouter();
45
+ const [buyerNip, setBuyerNip] = React.useState("");
46
+ const [buyerName, setBuyerName] = React.useState("");
47
+ const [invoiceNumber, setInvoiceNumber] = React.useState("");
48
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
49
+ const [issueDate, setIssueDate] = React.useState(today);
50
+ const [saleDate, setSaleDate] = React.useState(today);
51
+ const [currency, setCurrency] = React.useState("PLN");
52
+ const [lineItems, setLineItems] = React.useState([emptyLine()]);
53
+ const [notes, setNotes] = React.useState("");
54
+ const [sellerNip, setSellerNip] = React.useState(null);
55
+ const [sellerName, setSellerName] = React.useState("");
56
+ const [isGeneratingNumber, setIsGeneratingNumber] = React.useState(false);
57
+ const [sellerAddressL1, setSellerAddressL1] = React.useState("");
58
+ const [sellerCity, setSellerCity] = React.useState("");
59
+ const [sellerCountry, setSellerCountry] = React.useState("PL");
60
+ const [submitError, setSubmitError] = React.useState(null);
61
+ const [isMutating, setIsMutating] = React.useState(false);
62
+ const { runMutation } = useGuardedMutation({
63
+ contextId: "integration_ksef_direct:new-document"
64
+ });
65
+ React.useEffect(() => {
66
+ apiCall("/api/integration-ksef-direct/seller-info").then((res) => {
67
+ if (!res.ok) return;
68
+ const data = res.result;
69
+ if (data.sellerNip !== void 0) setSellerNip(data.sellerNip);
70
+ if (data.sellerName && !sellerName) setSellerName(data.sellerName);
71
+ }).catch(() => {
72
+ flash(t("integration_ksef_direct.documents.form.seller_info_error", "Failed to load seller info"), "error");
73
+ });
74
+ }, []);
75
+ const totals = React.useMemo(() => computeTotals(lineItems), [lineItems]);
76
+ React.useEffect(() => {
77
+ function onKeyDown(e) {
78
+ if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
79
+ e.preventDefault();
80
+ void handleSubmit();
81
+ }
82
+ if (e.key === "Escape") router.back();
83
+ }
84
+ window.addEventListener("keydown", onKeyDown);
85
+ return () => window.removeEventListener("keydown", onKeyDown);
86
+ }, [router, buyerNip, buyerName, invoiceNumber, issueDate, saleDate, currency, lineItems, notes, sellerName, sellerAddressL1, sellerCity, sellerCountry]);
87
+ function addLine() {
88
+ setLineItems((prev) => [...prev, emptyLine()]);
89
+ }
90
+ function removeLine(index) {
91
+ if (lineItems.length <= 1) return;
92
+ setLineItems((prev) => prev.filter((_, i) => i !== index));
93
+ }
94
+ function updateLine(index, field, value) {
95
+ setLineItems((prev) => prev.map((item, i) => i === index ? { ...item, [field]: value } : item));
96
+ }
97
+ async function handleGenerateNumber() {
98
+ setIsGeneratingNumber(true);
99
+ try {
100
+ const result = await apiCall("/api/integration-ksef-direct/invoice-numbers", { method: "POST" });
101
+ if (result.ok) {
102
+ const data = result.result;
103
+ setInvoiceNumber(data.number);
104
+ } else {
105
+ flash(t("integration_ksef_direct.documents.form.generate_number_error", "Failed to generate invoice number"), "error");
106
+ }
107
+ } catch {
108
+ flash(t("integration_ksef_direct.documents.form.generate_number_error", "Failed to generate invoice number"), "error");
109
+ } finally {
110
+ setIsGeneratingNumber(false);
111
+ }
112
+ }
113
+ async function handleSubmit() {
114
+ setSubmitError(null);
115
+ if (!sellerAddressL1.trim() || !sellerCity.trim()) {
116
+ setSubmitError(t("integration_ksef_direct.documents.form.error_seller_address_required", "Seller street and city are required."));
117
+ return;
118
+ }
119
+ setIsMutating(true);
120
+ const body = {
121
+ buyerNip,
122
+ buyerName: buyerName || void 0,
123
+ invoiceNumber,
124
+ issueDate,
125
+ saleDate: saleDate || void 0,
126
+ currency,
127
+ lineItems: lineItems.map((item) => ({
128
+ description: item.description,
129
+ quantity: parseFloat(item.quantity) || 0,
130
+ unit: item.unit,
131
+ unitNetPrice: parseFloat(item.unitNetPrice) || 0,
132
+ vatRate: item.vatRate
133
+ })),
134
+ notes: notes || void 0,
135
+ sellerName: sellerName || void 0,
136
+ sellerAddressL1,
137
+ sellerCity,
138
+ sellerCountry: sellerCountry || void 0
139
+ };
140
+ try {
141
+ await runMutation({
142
+ operation: async () => {
143
+ const result = await apiCall("/api/integration-ksef-direct/documents", {
144
+ method: "POST",
145
+ body: JSON.stringify(body),
146
+ headers: { "Content-Type": "application/json" }
147
+ });
148
+ if (!result.ok) {
149
+ const err = result.result?.error;
150
+ throw new Error(typeof err === "string" ? err : t("integration_ksef_direct.documents.form.error", "Submission failed"));
151
+ }
152
+ return result.result;
153
+ },
154
+ context: { entityType: "integration_ksef_direct.document" },
155
+ mutationPayload: { entityType: "integration_ksef_direct.document" }
156
+ });
157
+ flash(t("integration_ksef_direct.documents.form.success", "Document created successfully."), "success");
158
+ router.push("/backend/integration-ksef-direct/documents");
159
+ } catch (err) {
160
+ setSubmitError(err instanceof Error ? err.message : t("integration_ksef_direct.documents.form.error", "Submission failed"));
161
+ } finally {
162
+ setIsMutating(false);
163
+ }
164
+ }
165
+ return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
166
+ /* @__PURE__ */ jsx("h1", { className: "text-xl font-semibold mb-6", children: t("integration_ksef_direct.documents.form.title_new", "New KSeF Document") }),
167
+ submitError && /* @__PURE__ */ jsx(Alert, { variant: "destructive", className: "mb-6", children: /* @__PURE__ */ jsx(AlertDescription, { children: submitError }) }),
168
+ /* @__PURE__ */ jsx(SectionHeader, { title: t("integration_ksef_direct.documents.form.section.buyer", "Buyer") }),
169
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4 mb-6", children: [
170
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.buyer_nip", "Buyer NIP"), required: true, children: /* @__PURE__ */ jsx(
171
+ "input",
172
+ {
173
+ type: "text",
174
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
175
+ value: buyerNip,
176
+ onChange: (e) => setBuyerNip(e.target.value),
177
+ placeholder: "1234567890",
178
+ maxLength: 10
179
+ }
180
+ ) }),
181
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.buyer_name", "Buyer Name"), children: /* @__PURE__ */ jsx(
182
+ "input",
183
+ {
184
+ type: "text",
185
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
186
+ value: buyerName,
187
+ onChange: (e) => setBuyerName(e.target.value)
188
+ }
189
+ ) })
190
+ ] }),
191
+ /* @__PURE__ */ jsx(SectionHeader, { title: t("integration_ksef_direct.documents.form.section.invoice", "Invoice Details") }),
192
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4 mb-6", children: [
193
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.invoice_number", "Invoice Number"), required: true, children: /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-center", children: [
194
+ /* @__PURE__ */ jsx(
195
+ "input",
196
+ {
197
+ type: "text",
198
+ className: "flex-1 border border-input rounded-md px-3 py-2 text-sm",
199
+ value: invoiceNumber,
200
+ onChange: (e) => setInvoiceNumber(e.target.value)
201
+ }
202
+ ),
203
+ /* @__PURE__ */ jsx(
204
+ Button,
205
+ {
206
+ type: "button",
207
+ variant: "outline",
208
+ size: "sm",
209
+ onClick: () => void handleGenerateNumber(),
210
+ disabled: isGeneratingNumber,
211
+ className: "shrink-0",
212
+ children: isGeneratingNumber ? /* @__PURE__ */ jsxs(Fragment, { children: [
213
+ /* @__PURE__ */ jsx(Spinner, { className: "size-4 mr-2" }),
214
+ t("integration_ksef_direct.documents.form.generating", "Generating...")
215
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
216
+ /* @__PURE__ */ jsx(RefreshCw, { className: "size-4 mr-2", "aria-hidden": true }),
217
+ t("integration_ksef_direct.documents.form.generate_number", "Generate number")
218
+ ] })
219
+ }
220
+ )
221
+ ] }) }),
222
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.currency", "Currency"), children: /* @__PURE__ */ jsx(
223
+ "select",
224
+ {
225
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
226
+ value: currency,
227
+ onChange: (e) => setCurrency(e.target.value),
228
+ children: CURRENCIES.map((c) => /* @__PURE__ */ jsx("option", { value: c, children: c }, c))
229
+ }
230
+ ) }),
231
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.issue_date", "Issue Date"), required: true, children: /* @__PURE__ */ jsx(
232
+ "input",
233
+ {
234
+ type: "date",
235
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
236
+ value: issueDate,
237
+ onChange: (e) => setIssueDate(e.target.value)
238
+ }
239
+ ) }),
240
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.sale_date", "Sale Date"), children: /* @__PURE__ */ jsx(
241
+ "input",
242
+ {
243
+ type: "date",
244
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
245
+ value: saleDate,
246
+ onChange: (e) => setSaleDate(e.target.value)
247
+ }
248
+ ) })
249
+ ] }),
250
+ /* @__PURE__ */ jsx(
251
+ SectionHeader,
252
+ {
253
+ title: `${t("integration_ksef_direct.documents.form.line_items", "Line Items")} (${lineItems.length})`,
254
+ className: "mt-6"
255
+ }
256
+ ),
257
+ /* @__PURE__ */ jsx("div", { className: "space-y-3 mb-4", children: lineItems.map((item, index) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-12 gap-2 items-end border border-border rounded-md p-3", children: [
258
+ /* @__PURE__ */ jsx("div", { className: "col-span-4", children: /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.line_items.description", "Description"), required: true, children: /* @__PURE__ */ jsx(
259
+ "input",
260
+ {
261
+ type: "text",
262
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
263
+ value: item.description,
264
+ onChange: (e) => updateLine(index, "description", e.target.value)
265
+ }
266
+ ) }) }),
267
+ /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.line_items.quantity", "Qty"), children: /* @__PURE__ */ jsx(
268
+ "input",
269
+ {
270
+ type: "number",
271
+ min: "0.001",
272
+ step: "any",
273
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
274
+ value: item.quantity,
275
+ onChange: (e) => updateLine(index, "quantity", e.target.value)
276
+ }
277
+ ) }) }),
278
+ /* @__PURE__ */ jsx("div", { className: "col-span-1", children: /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.line_items.unit", "Unit"), children: /* @__PURE__ */ jsx(
279
+ "input",
280
+ {
281
+ type: "text",
282
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
283
+ value: item.unit,
284
+ onChange: (e) => updateLine(index, "unit", e.target.value)
285
+ }
286
+ ) }) }),
287
+ /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.line_items.unit_net_price", "Net Price"), children: /* @__PURE__ */ jsx(
288
+ "input",
289
+ {
290
+ type: "number",
291
+ min: "0",
292
+ step: "0.01",
293
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
294
+ value: item.unitNetPrice,
295
+ onChange: (e) => updateLine(index, "unitNetPrice", e.target.value)
296
+ }
297
+ ) }) }),
298
+ /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.line_items.vat_rate", "VAT"), children: /* @__PURE__ */ jsx(
299
+ "select",
300
+ {
301
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
302
+ value: item.vatRate,
303
+ onChange: (e) => updateLine(index, "vatRate", e.target.value),
304
+ children: VAT_RATES.map((r) => /* @__PURE__ */ jsxs("option", { value: r, children: [
305
+ r,
306
+ "%"
307
+ ] }, r))
308
+ }
309
+ ) }) }),
310
+ /* @__PURE__ */ jsx("div", { className: "col-span-1 flex justify-end pb-1", children: /* @__PURE__ */ jsx(
311
+ IconButton,
312
+ {
313
+ type: "button",
314
+ variant: "ghost",
315
+ size: "sm",
316
+ "aria-label": t("integration_ksef_direct.documents.form.line_items.remove", "Remove line"),
317
+ onClick: () => removeLine(index),
318
+ disabled: lineItems.length <= 1,
319
+ children: /* @__PURE__ */ jsx(Trash2, { className: "size-4" })
320
+ }
321
+ ) })
322
+ ] }, index)) }),
323
+ /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: addLine, className: "mb-6", children: [
324
+ /* @__PURE__ */ jsx(Plus, { className: "size-4 mr-2", "aria-hidden": true }),
325
+ t("integration_ksef_direct.documents.form.line_items.add", "Add Line")
326
+ ] }),
327
+ /* @__PURE__ */ jsx(SectionHeader, { title: t("integration_ksef_direct.documents.form.section.summary", "Summary") }),
328
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-4 mb-6", children: [
329
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.net_amount", "Net Amount"), children: /* @__PURE__ */ jsx(
330
+ "input",
331
+ {
332
+ type: "text",
333
+ readOnly: true,
334
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm bg-muted",
335
+ value: `${totals.net.toFixed(2)} ${currency}`
336
+ }
337
+ ) }),
338
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.vat_amount", "VAT Amount"), children: /* @__PURE__ */ jsx(
339
+ "input",
340
+ {
341
+ type: "text",
342
+ readOnly: true,
343
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm bg-muted",
344
+ value: `${totals.vat.toFixed(2)} ${currency}`
345
+ }
346
+ ) }),
347
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.gross_amount", "Gross Amount"), children: /* @__PURE__ */ jsx(
348
+ "input",
349
+ {
350
+ type: "text",
351
+ readOnly: true,
352
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm bg-muted font-semibold",
353
+ value: `${totals.gross.toFixed(2)} ${currency}`
354
+ }
355
+ ) })
356
+ ] }),
357
+ /* @__PURE__ */ jsx(SectionHeader, { title: t("integration_ksef_direct.documents.form.section.seller", "Seller"), className: "mt-6" }),
358
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4 mb-4", children: [
359
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.seller_nip", "Seller NIP"), children: /* @__PURE__ */ jsx(
360
+ "input",
361
+ {
362
+ type: "text",
363
+ disabled: true,
364
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm bg-muted text-muted-foreground cursor-not-allowed",
365
+ value: sellerNip ?? "",
366
+ placeholder: sellerNip === null ? t("integration_ksef_direct.documents.form.seller_nip_placeholder", "KSeF not configured") : ""
367
+ }
368
+ ) }),
369
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.seller_name", "Seller Name"), required: true, children: /* @__PURE__ */ jsx(
370
+ "input",
371
+ {
372
+ type: "text",
373
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
374
+ value: sellerName,
375
+ onChange: (e) => setSellerName(e.target.value),
376
+ maxLength: 512
377
+ }
378
+ ) })
379
+ ] }),
380
+ /* @__PURE__ */ jsx(SectionHeader, { title: t("integration_ksef_direct.documents.form.section.seller_address", "Seller Address"), className: "mt-0" }),
381
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4 mb-6", children: [
382
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.seller_address_l1", "Street and number"), required: true, children: /* @__PURE__ */ jsx(
383
+ "input",
384
+ {
385
+ type: "text",
386
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
387
+ value: sellerAddressL1,
388
+ onChange: (e) => setSellerAddressL1(e.target.value),
389
+ maxLength: 512
390
+ }
391
+ ) }),
392
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.seller_city", "City"), required: true, children: /* @__PURE__ */ jsx(
393
+ "input",
394
+ {
395
+ type: "text",
396
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
397
+ value: sellerCity,
398
+ onChange: (e) => setSellerCity(e.target.value),
399
+ maxLength: 256
400
+ }
401
+ ) }),
402
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.seller_country", "Country"), children: /* @__PURE__ */ jsx(
403
+ "input",
404
+ {
405
+ type: "text",
406
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
407
+ value: sellerCountry,
408
+ onChange: (e) => setSellerCountry(e.target.value),
409
+ maxLength: 2,
410
+ placeholder: "PL"
411
+ }
412
+ ) })
413
+ ] }),
414
+ /* @__PURE__ */ jsx(FormField, { label: t("integration_ksef_direct.documents.form.notes", "Notes"), className: "mb-6", children: /* @__PURE__ */ jsx(
415
+ "textarea",
416
+ {
417
+ rows: 3,
418
+ className: "w-full border border-input rounded-md px-3 py-2 text-sm",
419
+ value: notes,
420
+ onChange: (e) => setNotes(e.target.value)
421
+ }
422
+ ) }),
423
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-3", children: [
424
+ /* @__PURE__ */ jsx(
425
+ Button,
426
+ {
427
+ type: "button",
428
+ onClick: () => void handleSubmit(),
429
+ disabled: isMutating,
430
+ children: t("integration_ksef_direct.documents.form.submit", "Save Document")
431
+ }
432
+ ),
433
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => router.back(), children: t("common.cancel", "Cancel") })
434
+ ] })
435
+ ] }) });
436
+ }
437
+ export {
438
+ NewKsefDirectDocumentPage as default,
439
+ pageMetadata
440
+ };
441
+ //# sourceMappingURL=page.js.map