node-red-contrib-afya-ksef 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,9 @@ Log in with a **KSeF token** or a **KSeF certificate** (`.crt` + `.key`). No dep
10
10
 
11
11
  **[English](#english) · [Polski](#polski)** · part of [dobry.doctor](https://dobry.doctor/)
12
12
 
13
+ ![Invoice page – fictional data](https://raw.githubusercontent.com/mchuc/node-red-contrib-afya-ksef/main/docs/page.png)
14
+
15
+
13
16
  ---
14
17
 
15
18
  ## English
@@ -22,10 +25,12 @@ Log in with a **KSeF token** or a **KSeF certificate** (`.crt` + `.key`). No dep
22
25
  Example SMS (Polish, as it goes to Polish users):
23
26
 
24
27
  ```
25
- Przychód 1 234,50 zł netto – Firma Pacjenta S.A., FV FV/12/11/2026, KSeF 5265877635-20261103-0100000000AA-01
26
- Koszt 5 068,22 zł – Hurtownia Medyczna Sp. z o.o., termin 16.11.2026, FV HM/77/2026, KSeF 3225081610-20261102-0200000000CC-03
28
+ Przychód 1 234,50 zł netto – Firma Pacjenta S.A., FV FV/12/11/2026, KSeF 1111111111-20261103-0100000000AA-01
29
+ Koszt 5 068,22 zł – Hurtownia Medyczna Sp. z o.o., termin 16.11.2026, FV HM/77/2026, KSeF 5555555555-20261102-0200000000CC-03
27
30
  ```
28
31
 
32
+ **Flow library:** [`library/flow.json`](library/flow.json) – afya-week-calendar every 2 h (8–20) → KSeF → revenue and cost SMS → HTTP SMS gateway ([description](library/README.md)).
33
+
29
34
  ### Install
30
35
 
31
36
  Requires Node.js ≥ 18.17 and Node-RED ≥ 3.
@@ -70,9 +75,9 @@ A `.p12` / `.pfx` file has to be split first:
70
75
  | Variable | Optional: the last `msg.payload` also in a **global** or **flow** context variable. |
71
76
 
72
77
  Placeholders: `%kwota%` `%netto%` `%vat%` `%brutto%` `%kontrahent%` `%nip%` `%numer%` `%ksef%` `%data%` `%typ%`
73
- `%waluta%` `%miesiac%` `%suma%` `%firma%`, and for purchase invoices `%przelew%` (transfer amount) `%konto%` `%termin%`.
78
+ `%waluta%` `%miesiac%` `%suma%` `%firma%`, and for purchase invoices `%platnosc%` (account, due date, ⚠ different amount in the notes) `%przelew%` (transfer amount) `%konto%` `%termin%`.
74
79
 
75
- Defaults: `Przychód %kwota% – %kontrahent%, FV %numer%, KSeF %ksef%` and `Koszt %kwota% – %kontrahent%, FV %numer%, KSeF %ksef%`.
80
+ Defaults: `Przychód %kwota% – %kontrahent%, FV %numer%, KSeF %ksef%` and `Koszt %kwota% – %kontrahent%, FV %numer%, %platnosc%, KSeF %ksef%`.
76
81
 
77
82
  ### KSeF limits
78
83
 
@@ -86,17 +91,31 @@ per check, new invoices first, and every invoice only once.
86
91
 
87
92
  With *Show a web page* the node serves `http://<node-red>:1880/afya/ksef` (under `httpNodeRoot`):
88
93
 
89
- * company and NIP, tiles **revenue / costs / result** for the month (net, gross or both),
90
- * two tables like a journal – **Przychody** (sales) and **Koszty** (purchases): date, invoice number,
91
- counterparty with NIP, **KSeF number** with a *kopiuj* (copy) button, amounts and a total row,
92
- * **Do przelewu** under the costs: recipient, **bank account**, **amount**, **title** (invoice number), each with a
94
+ * a big status bar: **when KSeF was checked** and **whether the login worked** (green), the error (red) or a warning
95
+ after 3 hours without a check – so you know the system works,
96
+ * company and NIP, tiles: **revenue** (received / waiting for), **costs** (paid / to pay) and **operating profit** –
97
+ current (received − paid) and expected (all revenue − all costs), net, gross or both,
98
+ * two tables like a journal – **Przychody** (sales) and **Koszty** (purchases): issue date, **due date**,
99
+ invoice number, counterparty with NIP (purchases: also the **bank account** with *kopiuj*), **KSeF number** with
100
+ a *kopiuj* (copy) button, amounts and a total row; **sort by issue date or by due date**,
101
+ * **☐ / ☑** in every row – costs: *paid*, revenue: *received*; tick it on the page, it is saved in Node-RED (separate
102
+ file, survives restarts); invoices marked as paid in their XML are ticked for good. Paid transfer cards move below a
103
+ line, so only the unpaid ones stay on top,
104
+ * **PDF** and **XML** for every invoice: *PDF* opens a readable invoice (parties, items, VAT summary, settlement,
105
+ payment, notes, attachment, KSeF verification link) with *Save PDF / print*; amounts in payment notes are
106
+ highlighted. *XML* shows / downloads the KSeF file. Downloaded XML is **cached for 30 days**,
107
+ * **⚠ different amount in the notes** – when a note on the invoice (additional description, payment description,
108
+ attachment) mentions an amount to pay that is not the invoice amount, the row and the transfer card warn you,
109
+ * **Do przelewu** under the costs – big cards, 2 per row: issue date, a **big due date** with a badge (red **PO TERMINIE ·
110
+ N days**, *pay today*, *tomorrow*, *in N days*, *paid*), then amount, title, KSeF number and account. Ticking paid
111
+ happens in place – the card turns grey, nothing reloads or jumps; each card lists the recipient, **bank account**, **amount**, **title** (invoice number), each with a
93
112
  *kopiuj* button; due date (overdue in red), paid invoices dimmed, split payment (MPP) with the VAT amount,
94
113
  factor account, payment link; a wrong account checksum is flagged,
95
114
  * clicking an amount in the tables copies it as `1518.44` (or `1518,44`),
96
115
  * arrows switch between the stored months (up to 13), badges for new invoices (last 48 h) and corrections,
97
116
  * works on a phone and in dark mode, refreshes itself every 15 minutes.
98
117
 
99
- Copying works over plain `http://` in the local network too (where the browser blocks the clipboard API).
118
+ Copying works over plain `http://` in the local network too (where the browser blocks the clipboard API). At the bottom: the dobry.doctor logo and link and the author's ORCID iD.
100
119
 
101
120
  Access – exactly like the Librus page: a **password** (login form, `HttpOnly` cookie for 30 days, changing the
102
121
  password logs everyone out) and/or an **access token** (`…/afya/ksef?token=…`, no login – keep the link like a
@@ -112,10 +131,13 @@ Put the page behind HTTPS / VPN when it is reachable from the internet – it sh
112
131
  | `tekstPrzychody`, `tekstKoszty`, `tekst` | ready SMS texts; empty when nothing is new |
113
132
  | `przychody`, `koszty` | this month's journal: `ksef` (KSeF number), `numer` (invoice number), `data`, `otrzymana`, `kontrahent`, `nipKontrahenta`, `netto`, `vat`, `brutto`, `vatPln`, `waluta`, `typ`, `korekta`, `miesiac`; costs also `platnosc` (`konta`, `termin`, `forma`, `zaplacono`, `mpp`, …) |
114
133
  | `sumy` | `{ przychody: { PLN: { ile, netto, vat, brutto } }, koszty: {…}, wynik: {…} }` |
134
+ | `rozliczenie` | per currency: `otrzymano`, `czekamy`, `wydano`, `doWydania`, `zyskObecny`, `zyskOczekiwany` (`{ netto, vat, brutto }`) |
115
135
  | `miesiace` | the checked months with their journals and totals |
116
136
  | `firma`, `nip`, `miesiac`, `srodowisko`, `kwoty`, `typDaty` | context of the check |
117
137
  | `pierwszyOdczyt` | `true` on the very first check – invoices are only remembered |
118
138
  | `zapytan`, `pobranoFaktur` | KSeF queries made, invoice XML files downloaded |
139
+ | `koszty[].zaplacona`, `oznaczonaZaplacona` | paid (from the XML or ticked on the page) and when it was ticked |
140
+ | `koszty[].platnosc.uwagi`, `kwotyWUwagach` | notes from the invoice and the amounts mentioned in payment notes |
119
141
  | `certyfikat` | with certificate login: subject, validity, fingerprint |
120
142
 
121
143
  ### SMS test
@@ -181,7 +203,7 @@ Token, certyfikat, klucz i hasła są zapisywane jako dane uwierzytelniające No
181
203
  albo z przecinkiem `1518,44`.
182
204
 
183
205
  Pola w szablonach: `%kwota%` `%netto%` `%vat%` `%brutto%` `%kontrahent%` `%nip%` `%numer%` `%ksef%` `%data%` `%typ%`
184
- `%waluta%` `%miesiac%` `%suma%` `%firma%`, a dla kosztów także `%przelew%` `%konto%` `%termin%`.
206
+ `%waluta%` `%miesiac%` `%suma%` `%firma%`, a dla kosztów także `%platnosc%` (konto, termin, ⚠ inna kwota w opisie) `%przelew%` `%konto%` `%termin%`.
185
207
 
186
208
  ### Limity KSeF
187
209
 
@@ -191,11 +213,27 @@ XML faktur (dane do przelewu): najwyżej 12 przy jednym sprawdzeniu, każda fakt
191
213
 
192
214
  ### Strona z fakturami
193
215
 
194
- `http://<node-red>:1880/afya/ksef` – kafle *przychody / koszty / wynik*, tabele **Przychody** i **Koszty**
195
- (data, numer faktury, kontrahent z NIP-em, **numer KSeF z przyciskiem kopiuj**, kwoty, wiersz „Razem”) i pod nimi
196
- **Do przelewu**: odbiorca, **konto**, **kwota**, **tytuł** – wszystko z przyciskiem *kopiuj*; termin (po terminie na
216
+ `http://<node-red>:1880/afya/ksef` – duży pasek **kiedy sprawdzono KSeF i czy logowanie się udało** (zielony / czerwony,
217
+ ostrzeżenie po 3 godz. bez sprawdzenia), kafle **przychody** (otrzymano / czekamy), **koszty** (wydano / do wydania)
218
+ i **zysk operacyjny** – obecny (otrzymano − wydano) i oczekiwany (przychody − koszty), tabele **Przychody** i **Koszty**
219
+ (data wystawienia, **termin płatności**, numer faktury z linkami **PDF** i **XML**, kontrahent z NIP-em – w kosztach
220
+ też **konto z przyciskiem kopiuj** – **numer KSeF z przyciskiem kopiuj**, kwoty, wiersz „Razem”), **sortowanie po dacie
221
+ wystawienia albo terminie płatności**, **odhaczanie ☐/☑** – koszty „zapłacona”, przychody „otrzymana” (zapisywane
222
+ w Node-RED) i pod nimi
223
+ **Do przelewu**: odbiorca, **konto**, **kwota**, **tytuł**, **numer KSeF** (także „tytuł + nr KSeF”) – wszystko z przyciskiem
224
+ *kopiuj*; karty po 2 w rzędzie z dużym terminem płatności i znaczkiem (czerwone **PO TERMINIE · N dni**, „zapłać dziś”,
225
+ „jutro”, „za N dni”); odhaczenie działa w miejscu – karta szarzeje, strona się nie przeładowuje; zapłacone zjeżdżają pod
226
+ kreskę przy następnym otwarciu; termin (po terminie na
197
227
  czerwono), zapłacone wyszarzone, split payment z kwotą VAT, konto faktora. Kliknięcie kwoty w tabeli kopiuje ją jako
198
228
  `1518.44`. Kopiowanie działa też przez zwykłe `http://` w sieci lokalnej. Strzałki – poprzednie miesiące (do 13).
229
+ Na dole strony: logo i link dobry.doctor oraz ORCID autora.
230
+
231
+ **PDF** otwiera czytelną fakturę (strony, pozycje, VAT, rozliczenie, płatność, **uwagi i załącznik**, link weryfikacyjny
232
+ KSeF) z przyciskiem *Zapisz PDF / drukuj*; kwoty w uwagach o płatności są podświetlone, a gdy w opisie jest **inna kwota
233
+ niż na fakturze** – ostrzeżenie ⚠ w tabeli, w karcie przelewu i w SMS-ie. **XML** pokazuje / pobiera plik z KSeF.
234
+ Pobrany XML jest trzymany **30 dni** (`~/.node-red/afya-ksef/<id-węzła>-xml/`), potem pobierany od nowa.
235
+
236
+ ![Transfer cards – fictional data](https://raw.githubusercontent.com/mchuc/node-red-contrib-afya-ksef/main/docs/transfers.png)
199
237
 
200
238
  Dostęp jak w Librusie: **hasło** (logowanie na 30 dni) i/lub **token** w linku `?token=…`; bez nich strona jest
201
239
  wyłączona, 10 błędnych prób w 15 minut blokuje adres na chwilę. Wystawiając stronę do internetu – tylko przez HTTPS / VPN.
@@ -206,6 +244,8 @@ wyłączona, 10 błędnych prób w 15 minut blokuje adres na chwilę. Wystawiaj
206
244
  osobnymi SMS-ami (przychody do właściciela, koszty do właściciela i księgowej), bramka SMS po HTTP z tokenem
207
245
  w nagłówku, cały wynik do MQTT `afya/ksef/dane`. Pierwsze sprawdzenie tylko zapamiętuje faktury.
208
246
 
247
+ Biblioteka przepływów Node-RED: [`library/flow.json`](library/flow.json) – harmonogram afya-week-calendar co 2 h (8–20) → KSeF → SMS o przychodzie i koszcie → bramka SMS po HTTP ([opis](library/README.md)).
248
+
209
249
  ### Testy
210
250
 
211
251
  `npm install && npm test` – testy na atrapie KSeF, która sprawdza szyfrowanie tokenu, podpis XAdES (RSA i EC),
package/afya-ksef.html CHANGED
@@ -33,22 +33,22 @@
33
33
  .afya-form .afya-file-info.ok { color: #3E9C86; }
34
34
  .afya-form .afya-file-info.err { color: #c0392b; }
35
35
  .afya-form .afya-dd {
36
- display: flex; align-items: center; justify-content: flex-end; gap: 8px;
37
- margin-top: 16px; font-size: 11px; color: var(--red-ui-secondary-text-color, #888);
36
+ display: flex; align-items: center; justify-content: center; gap: 12px;
37
+ margin-top: 20px; font-size: 13px; color: var(--red-ui-secondary-text-color, #888);
38
38
  }
39
39
  .afya-form .afya-dd a {
40
- display: inline-flex; align-items: center; padding: 5px 10px; border-radius: 8px;
40
+ display: inline-flex; align-items: center; padding: 10px 18px; border-radius: 12px;
41
41
  background: #fff; border: 1px solid var(--red-ui-secondary-border-color, #ddd); line-height: 0;
42
42
  }
43
- .afya-form .afya-dd a:hover { border-color: #8cd300; }
44
- .afya-form .afya-dd img { height: 20px; width: auto; }
43
+ .afya-form .afya-dd a:hover { border-color: #8cd300; box-shadow: 0 1px 6px rgba(0, 0, 0, .08); }
44
+ .afya-form .afya-dd img { height: 40px; width: auto; }
45
45
  </style>
46
46
 
47
47
  <script type="text/javascript">
48
48
  (function () {
49
49
  const plainKey = (v) => String(v || '').replace(/^#:\(\S+?\)::/, '');
50
50
  const DEFAULT_REVENUE = 'Przychód %kwota% – %kontrahent%, FV %numer%, KSeF %ksef%';
51
- const DEFAULT_COST = 'Koszt %kwota% – %kontrahent%, FV %numer%, KSeF %ksef%';
51
+ const DEFAULT_COST = 'Koszt %kwota% – %kontrahent%, FV %numer%, %platnosc%, KSeF %ksef%';
52
52
  const esc = (v) => $('<span>').text(v).html();
53
53
  const nipOk = function (v) {
54
54
  const n = String(v || '').replace(/[\s-]/g, '');
@@ -62,7 +62,7 @@
62
62
  en: {
63
63
  name: 'Name', namePh: 'e.g. KSeF – clinic', lang: 'Labels', langAuto: 'system language ({l})',
64
64
  secAccount: 'KSeF account', env: 'Environment', envProd: 'Production (real invoices)',
65
- envDemo: 'Demo (pre-production)', envTest: 'Test', nip: 'Company NIP', nipPh: '10 digits, e.g. 5265877635',
65
+ envDemo: 'Demo (pre-production)', envTest: 'Test', nip: 'Company NIP', nipPh: '10 digits, e.g. 1111111111',
66
66
  method: 'Log in with', methodToken: 'KSeF token', methodCert: 'KSeF certificate (.crt + .key)',
67
67
  token: 'KSeF token', tokenHint: 'Generate it in <i>Aplikacja Podatnika KSeF</i> → <i>Tokeny</i>; reading invoices needs only ' +
68
68
  'the permission <b>przeglądanie faktur</b> (<code>InvoiceRead</code>).',
@@ -116,7 +116,7 @@
116
116
  pl: {
117
117
  name: 'Nazwa', namePh: 'np. KSeF – przychodnia', lang: 'Etykiety', langAuto: 'język systemu ({l})',
118
118
  secAccount: 'Konto KSeF', env: 'Środowisko', envProd: 'Produkcyjne (prawdziwe faktury)',
119
- envDemo: 'Demo (przedprodukcyjne)', envTest: 'Testowe', nip: 'NIP firmy', nipPh: '10 cyfr, np. 5265877635',
119
+ envDemo: 'Demo (przedprodukcyjne)', envTest: 'Testowe', nip: 'NIP firmy', nipPh: '10 cyfr, np. 1111111111',
120
120
  method: 'Logowanie', methodToken: 'token KSeF', methodCert: 'certyfikat KSeF (.crt + .key)',
121
121
  token: 'Token KSeF', tokenHint: 'Wygeneruj go w <i>Aplikacji Podatnika KSeF</i> → <i>Tokeny</i>; do odczytu faktur wystarczy ' +
122
122
  'uprawnienie <b>przeglądanie faktur</b> (<code>InvoiceRead</code>).',
@@ -483,7 +483,7 @@
483
483
  </div>
484
484
  <div class="form-row">
485
485
  <label for="node-input-nip"><i class="fa fa-building"></i> <span data-t="nip">Company NIP</span></label>
486
- <input type="text" id="node-input-nip" data-t-ph="nipPh" placeholder="10 digits, e.g. 5265877635" autocomplete="off" style="width: 65%;">
486
+ <input type="text" id="node-input-nip" data-t-ph="nipPh" placeholder="10 digits, e.g. 1111111111" autocomplete="off" style="width: 65%;">
487
487
  </div>
488
488
  <div class="form-row">
489
489
  <label for="node-input-metoda"><i class="fa fa-sign-in"></i> <span data-t="method">Log in with</span></label>
@@ -573,10 +573,10 @@
573
573
  </div>
574
574
  <div class="form-row afya-ksef-cost">
575
575
  <label for="node-input-szablonKoszty"><i class="fa fa-commenting"></i> <span data-t="text">Text</span></label>
576
- <input type="text" id="node-input-szablonKoszty" placeholder="Koszt %kwota% – %kontrahent%, FV %numer%, KSeF %ksef%" style="width: 65%;">
576
+ <input type="text" id="node-input-szablonKoszty" placeholder="Koszt %kwota% – %kontrahent%, FV %numer%, %platnosc%, KSeF %ksef%" style="width: 65%;">
577
577
  </div>
578
578
  <div class="afya-hint afya-ksef-cost">
579
- + <code>%przelew%</code> <code>%konto%</code> <code>%termin%</code> · <span data-t="output">output</span>: <code>payload.tekstKoszty</code>
579
+ + <code>%platnosc%</code> (konto, termin, ⚠ inna kwota w opisie) <code>%przelew%</code> <code>%konto%</code> <code>%termin%</code> · <span data-t="output">output</span>: <code>payload.tekstKoszty</code>
580
580
  </div>
581
581
 
582
582
  <div class="afya-section"><i class="fa fa-mobile"></i> SMS</div>
@@ -700,6 +700,8 @@
700
700
  <dt>payload.koszty[].platnosc <span class="property-type">object</span></dt>
701
701
  <dd>With <i>Transfers</i> on: data from the purchase invoice XML – <code>konta</code> (<code>nr, czytelny, bank, swift,
702
702
  poprawny</code>), <code>kontaFaktora, termin, forma, zaplacono, dataZaplaty, mpp, link, doZaplaty</code>.</dd>
703
+ <dt>payload.koszty[].zaplacona <span class="property-type">boolean</span></dt>
704
+ <dd>Paid – from the invoice XML or ticked on the page (<code>oznaczonaZaplacona</code> = when).</dd>
703
705
  <dt>payload.pierwszyOdczyt <span class="property-type">boolean</span></dt>
704
706
  <dd><code>true</code> on the very first check – invoices are only remembered, <code>nowe</code> is empty.</dd>
705
707
  </dl>
@@ -716,7 +718,10 @@
716
718
  <p>With <i>Show a web page</i> the node serves <code>http://&lt;node-red&gt;:1880/&lt;page path&gt;</code>
717
719
  (under <code>httpNodeRoot</code>): totals of revenue, costs and the result, and two tables like a journal –
718
720
  date, invoice number, counterparty with NIP, the <b>KSeF number</b> and amounts (net, gross or both) with a
719
- total row. Under the costs, <b>Do przelewu</b> lists each purchase invoice with the recipient, bank account,
721
+ total row. Each row also has the <b>due date</b> (sort by issue date or due date), a <b>☐ / ☑ paid</b> tick
722
+ (saved in Node-RED) and links <b>PDF</b> (readable invoice – <i>Save PDF / print</i>; notes and attachment
723
+ included, amounts in notes highlighted) and <b>XML</b>. Downloaded XML is cached for 30 days. Purchase rows show
724
+ the bank account under the seller. Under the costs, <b>Do przelewu</b> lists each purchase invoice with the recipient, bank account,
720
725
  amount, title and due date (overdue, paid, split payment marked) – every value has a <b>copy</b> button, and a
721
726
  click on an amount in the tables copies it as <code>1518.44</code> (or <code>1518,44</code>). Copying works over
722
727
  plain http in the local network too. Arrows switch between the stored months (up to 13). Access: page password
@@ -739,7 +744,10 @@
739
744
  KSeF pozwala na 20 zapytań o faktury na godzinę – sprawdzaj co godzinę.</p>
740
745
  <p><b>Strona z fakturami</b> – dwie tabele jak w dzienniku (przychody i koszty) z numerami KSeF, sumami
741
746
  i wynikiem miesiąca, a pod kosztami <b>Do przelewu</b>: odbiorca, konto, kwota (brutto albo netto, z kropką
742
- albo przecinkiem) i tytuł – wszystko z przyciskiem <i>kopiuj</i>. Dostęp po haśle albo z linku z tokenem.</p>
747
+ albo przecinkiem) i tytuł – wszystko z przyciskiem <i>kopiuj</i>. W tabelach: data wystawienia i <b>termin
748
+ płatności</b> (sortowanie po jednym albo drugim), <b>odhaczanie ☐/☑ zapłaconych</b>, konto pod sprzedawcą,
749
+ linki <b>PDF</b> (czytelna faktura z uwagami i załącznikiem – zapisz jako PDF) i <b>XML</b> (cache 30 dni).
750
+ Gdy w opisie faktury jest inna kwota niż na fakturze – ostrzeżenie ⚠. Dostęp po haśle albo z linku z tokenem.</p>
743
751
 
744
752
  <p><small>Marcin Chuć · MIT · <a href="https://dobry.doctor/" target="_blank" rel="noopener">dobry.doctor</a> ·
745
753
  unofficial, not affiliated with the Ministry of Finance</small></p>
package/afya-ksef.js CHANGED
@@ -15,6 +15,8 @@ const { zarejestrujStrone, normalizujSciezke } = require('./lib/strona');
15
15
  const MIESIECY_HISTORII = 13; // tyle miesięcy dziennika trzymamy w pliku stanu (i na stronie)
16
16
  const MAKS_XML = 12; // tyle faktur kosztowych (XML → konto do przelewu) pobieramy przy jednym sprawdzeniu
17
17
  const PONOW_BLAD_MS = 24 * 3600 * 1000; // nieudane pobranie XML ponawiamy po dobie
18
+ const CACHE_XML_MS = 30 * 24 * 3600 * 1000; // pobrane XML faktur trzymamy na dysku przez 30 dni
19
+ const NUMER_KSEF = /^[0-9A-Za-z-]{20,64}$/;
18
20
 
19
21
  function wczytajStan(plik) {
20
22
  try {
@@ -56,7 +58,13 @@ module.exports = function (RED) {
56
58
  const szablonP = (config.szablonPrzychody || F.DOMYSLNY_SZABLON_PRZYCHODU) + doklejka;
57
59
  const szablonK = (config.szablonKoszty || F.DOMYSLNY_SZABLON_KOSZTU) + doklejka;
58
60
  // Widziane faktury i dziennik miesięcy – przetrwają restart Node-RED (bez duplikatów SMS)
59
- const plikStanu = path.join(RED.settings.userDir || process.cwd(), 'afya-ksef', `${node.id}.json`);
61
+ const katalog = path.join(RED.settings.userDir || process.cwd(), 'afya-ksef');
62
+ const plikStanu = path.join(katalog, `${node.id}.json`);
63
+ // „Zapłacona” zaznaczane na stronie – osobny plik, żeby sprawdzenie KSeF go nie nadpisało
64
+ const plikZaplaconych = path.join(katalog, `${node.id}-zaplacone.json`);
65
+ // XML faktur – cache na 30 dni (podgląd / PDF / pobieranie bez pytania KSeF)
66
+ const katalogXml = path.join(katalog, `${node.id}-xml`);
67
+ const plikXml = (ksef) => path.join(katalogXml, `${ksef}.xml`);
60
68
  const zakres = config.scope === 'flow' ? 'flow' : 'global';
61
69
  const { key: zmienna, store: magazyn } = RED.util.parseContextStore(String(config.variableName || '').trim());
62
70
  let trwa = false;
@@ -75,11 +83,60 @@ module.exports = function (RED) {
75
83
  przelewy,
76
84
  trybPrzelewu,
77
85
  separator,
86
+ metoda,
78
87
  czas: zapisany.nip === nip ? zapisany.aktualizacja || null : null,
79
88
  blad: null,
80
89
  czasBledu: null,
90
+ zaplacone: wczytajStan(plikZaplaconych) || {},
81
91
  };
82
92
 
93
+ /** XML z cache (młodszy niż 30 dni) albo null. */
94
+ function xmlZCache(ksef) {
95
+ try {
96
+ const st = fs.statSync(plikXml(ksef));
97
+ if (Date.now() - st.mtimeMs > CACHE_XML_MS) return null;
98
+ return fs.readFileSync(plikXml(ksef), 'utf8');
99
+ } catch (_) {
100
+ return null;
101
+ }
102
+ }
103
+ function zapiszXml(ksef, xml) {
104
+ try {
105
+ fs.mkdirSync(katalogXml, { recursive: true });
106
+ fs.writeFileSync(plikXml(ksef), xml);
107
+ } catch (err) {
108
+ node.warn(`Cannot cache invoice XML: ${err.message}`);
109
+ }
110
+ }
111
+ function sprzatnijXml() {
112
+ try {
113
+ for (const plik of fs.readdirSync(katalogXml)) {
114
+ const pelna = path.join(katalogXml, plik);
115
+ if (Date.now() - fs.statSync(pelna).mtimeMs > CACHE_XML_MS) fs.rmSync(pelna, { force: true });
116
+ }
117
+ } catch (_) {
118
+ /* brak katalogu – nic do sprzątania */
119
+ }
120
+ }
121
+ /** XML faktury: z cache, a gdy go nie ma – z KSeF (i do cache). */
122
+ async function xmlFaktury(ksef) {
123
+ if (!NUMER_KSEF.test(String(ksef))) throw new Error('nieprawidłowy numer KSeF');
124
+ const zCache = xmlZCache(ksef);
125
+ if (zCache) return { xml: zCache, zCache: true };
126
+ const xml = await dajKlienta().pobierzFakture(ksef);
127
+ zapiszXml(ksef, xml);
128
+ return { xml, zCache: false };
129
+ }
130
+ /** Zaznaczenie / odznaczenie „zapłacona” ze strony. */
131
+ function oznaczZaplacona(ksef, zaplacona) {
132
+ if (!NUMER_KSEF.test(String(ksef))) throw new Error('nieprawidłowy numer KSeF');
133
+ const z = { ...ostatni.zaplacone };
134
+ if (zaplacona) z[ksef] = { czas: new Date().toISOString() };
135
+ else delete z[ksef];
136
+ zapiszStan(plikZaplaconych, z);
137
+ ostatni.zaplacone = z;
138
+ }
139
+
83
140
  if (!poprawnyNip(nip)) node.status({ fill: 'red', shape: 'ring', text: 'set the company NIP' });
84
141
 
85
142
  let zamknijStrone = null;
@@ -95,6 +152,8 @@ module.exports = function (RED) {
95
152
  tytul: String(config.tytulStrony || '').trim(),
96
153
  nazwa: config.name || '',
97
154
  stan: () => ostatni,
155
+ xml: xmlFaktury,
156
+ oznacz: oznaczZaplacona,
98
157
  });
99
158
  if (poprawnyNip(nip)) node.status({ fill: 'grey', shape: 'ring', text: `page ${sciezka}` });
100
159
  if (!hasloStrony && !tokenStrony) node.warn(`Page ${sciezka} is off until a page password or token is set`);
@@ -187,18 +246,37 @@ module.exports = function (RED) {
187
246
  .slice(0, MAKS_XML);
188
247
  for (const f of doPobrania) {
189
248
  try {
190
- platnosci[f.ksef] = { ...czytajPlatnosc(await k.pobierzFakture(f.ksef)), pobrano: czas };
249
+ const xml = xmlZCache(f.ksef) || (await k.pobierzFakture(f.ksef));
250
+ zapiszXml(f.ksef, xml);
251
+ platnosci[f.ksef] = { ...czytajPlatnosc(xml), pobrano: czas };
191
252
  pobranoFaktur++;
192
253
  } catch (err) {
193
254
  if (err.status === 429) break; // reszta przy następnym sprawdzeniu
194
255
  platnosci[f.ksef] = { blad: err.message, pobrano: czas };
195
256
  }
196
257
  }
197
- wszystkie.forEach((f) => {
198
- const p = platnosci[f.ksef];
199
- if (f.rodzaj === 'koszt' && p) f.platnosc = p.blad ? { blad: p.blad } : p;
200
- });
201
258
  }
259
+ // sprzedaż: termin i konto tylko z XML, który już jest w cache (np. po otwarciu podglądu) – bez pobierania
260
+ wszystkie
261
+ .filter((f) => f.rodzaj === 'przychod' && !platnosci[f.ksef])
262
+ .forEach((f) => {
263
+ const xml = xmlZCache(f.ksef);
264
+ if (!xml) return;
265
+ try {
266
+ platnosci[f.ksef] = { ...czytajPlatnosc(xml), pobrano: czas };
267
+ } catch (_) {
268
+ /* nieczytelny XML – pomijamy */
269
+ }
270
+ });
271
+ const zaplacone = wczytajStan(plikZaplaconych) || {};
272
+ ostatni.zaplacone = zaplacone;
273
+ wszystkie.forEach((f) => {
274
+ const p = platnosci[f.ksef];
275
+ if (p && (przelewy || f.rodzaj === 'przychod')) f.platnosc = p.blad ? { blad: p.blad } : p;
276
+ f.zaplacona = !!(zaplacone[f.ksef] || (f.platnosc && f.platnosc.zaplacono));
277
+ if (zaplacone[f.ksef]) f.oznaczonaZaplacona = zaplacone[f.ksef].czas;
278
+ });
279
+ sprzatnijXml();
202
280
 
203
281
  // Dziennik: sprawdzone miesiące od nowa, starsze zostają (do 13 miesięcy wstecz)
204
282
  const miesiace = zgodny && stan.typDaty === typDaty ? { ...(stan.miesiace || {}) } : {};
@@ -254,6 +332,7 @@ module.exports = function (RED) {
254
332
  przychody: d.przychody,
255
333
  koszty: d.koszty,
256
334
  sumy: d.sumy,
335
+ rozliczenie: F.rozliczenieMiesiaca(d, zaplacone),
257
336
  miesiace: Object.fromEntries(doSprawdzenia.map((m) => [m, miesiace[m]])),
258
337
  zapytan,
259
338
  pobranoFaktur,
package/change.log CHANGED
@@ -1,3 +1,27 @@
1
+ 1.2.0 (2026-11-30):
2
+ - Ticking paid / received no longer reloads the page: the row and the card turn grey and the button is ticked in place,
3
+ tiles and "to pay" sum update at once (fetch + JSON; plain form still works without JavaScript)
4
+ - Transfer cards redesigned: 2 per row and bigger; issue date, a big due date and a clear badge – red PO TERMINIE
5
+ (with days), PAY TODAY, tomorrow, in N days, paid; then amount, title (+ KSeF number), KSeF number and account
6
+ - Page uses the full width of the screen
7
+ - Page footer: dobry.doctor logo and link, author's ORCID iD (inline SVG, light and dark theme, hidden when printing)
8
+ - Example data anonymised (tests, help, examples); flow for the Node-RED flow library (library/) and README screenshots
9
+ with fictional data (docs/)
10
+
11
+ 1.1.0 (2026-11-30):
12
+ - Page: due date column and sorting by issue date or due date; bank account (with copy) under the seller in the costs table
13
+ - Page: ☐ / ☑ "paid" tick in every row and in the transfer cards – saved in Node-RED (separate file), in payload as zaplacona
14
+ - Page: PDF and XML for every invoice – readable invoice (parties, items, VAT, settlement, payment, notes, attachment,
15
+ KSeF verification link) with "Save PDF / print", and the KSeF XML file (view / download); XML cached for 30 days
16
+ - Notes from the invoice (additional description, payment description, footer, attachment) in the transfer card;
17
+ ⚠ warning when a payment note mentions an amount different from the invoice (also in the SMS)
18
+ - Default cost SMS: account and due date (%platnosc%); due date of sales invoices from cached XML
19
+ - Page: big status bar – when KSeF was checked and whether the login worked (warning after 3 h without a check)
20
+ - Page: revenue ticks mean "received"; tiles received / waiting for, paid / to pay, operating profit current and
21
+ expected (payload.rozliczenie); paid transfer cards move below a line; KSeF number (and "title + KSeF number")
22
+ to copy in every transfer card
23
+ - Edit dialog: bigger dobry.doctor badge
24
+
1
25
  1.0.0 (2026-11-30):
2
26
  - First version: KSeF API 2.0 – this month's (and the previous month's) sales = revenue and purchases = costs,
3
27
  with KSeF numbers, net / gross / both amounts, totals and the month's result