Compare commits

...

10 Commits

Author SHA1 Message Date
BOHA
875ef4d79e chore(release): v2.4.47 — KPI cards + Bilance aligned with the print recap
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 00:48:56 +02:00
BOHA
a679f6e8ac fix(attendance): KPI cards + Bilance now use the print-recap formulas
Verification found three divergences from the binding print recap:

- getWorkfund (Bilance page): overtime included nemoc (print Přesčas is
  worked + dovolená only) and missing ignored neplacené volno (print
  Chybějící hodiny counts every approved absence). Both now match; the
  response carries covered (manko base) + covered_prescas (Přesčas base)
  and the page's year aggregate sums them separately.
- AttendanceAdmin fond bar: used = worked + dovolená + worked_holiday +
  svatek — after v2.4.45 the last two fields hold the SAME value, so
  holiday work counted twice (regression). Coverage is now worked + all
  approved absences, and the ± badges show the exact print values
  (ut.prescas / ut.manko) instead of a derived delta; bar color follows
  Přesčas/Chybějící hodiny.
- Fond itself was already aligned everywhere (non-holiday weekdays × 8,
  prorated for the running month).

+1 route-parity test (real DB): worked 80 + dov 24 + nem 16 + nepl 8 vs
fond 176 → covered 128, covered_prescas 104, missing 48, overtime 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 00:47:26 +02:00
BOHA
3530dd247c chore(release): v2.4.46 — Chybějící hodiny (manko) in the payroll recap
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 00:22:36 +02:00
BOHA
996012e3d3 feat(attendance): 'Chybějící hodiny' (manko) row — real hours below the fond
manko = max(0, fond − (worked_total + dovolená + nemoc + neplacené volno))
using REAL clock time, not the paušál. Supplement next to Přesčas — the
verified binding formulas are untouched.

Why: the paušál Odpracováno can nominally cover the fond while dozens of
real hours are missing (Dominik 6/2026: 21 days × 8 + 8h dovolená = 176 =
fond exactly, thanks to weekend shifts compensating 3 recordless weekdays —
yet real worked time was 136,5h). Přesčas = 0 correctly, and the 31,5h gap
vanished from every total. Now it's a permanent summary line, red+bold when
positive, plus a 'Chybí: Xh' chip on the admin screen cards.

+4 tests incl. the real June dataset as a pinned acceptance case (also
pins noc 6,75 — early shifts starting 05:30/05:45 legitimately count
night minutes before 06:00).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 00:12:20 +02:00
BOHA
3cd7cfcc34 chore(release): v2.4.45 — binding payroll-recap formulas (payslip-verified)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 19:03:28 +02:00
BOHA
68d9c224bc fix(attendance): binding payroll-recap formulas, back-computed against a real payslip
Formulas per the owner's verified spec (Dominik Vesecký 5/2026, exact to
a tenth of an hour — built-in acceptance dataset pins every line):

- fond        = (Po-Pá dny mimo svátek) × 8         [was: incl. holidays]
- odpracováno = (dny se záznamem Práce mimo svátek) × 8, paušálně
                [was: actual worked hours minus holiday work]
- přesčas     = max(0, (worked_total + dovolená) − fond)
                [was: worked only, holiday-including fond]
- vč. svátků  = odpracováno + přesčas  [was: worked_total]
- svátek/dovolená/so-ne/noc unchanged (already verified correct)

Expected 5/2026: fond 152 · odpracováno 144 · svátek 8 · dovolená 24 ·
přesčas 17,25→17,3 · vč. 161,25→161,3 · So/Ne 57,25 · noc 36,75 (the
payslip's 31 was the accountant's own error — she missed the 31.5.→1.6.
overnight shift; the spec mandates 36,75).

Two-shift days count once toward odpracováno; 'holiday' placeholder
records stay evidence-only; holiday table remains year-parametric
(fixed dates + computed Easter).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 19:00:54 +02:00
BOHA
200aa0e1a8 chore(release): v2.4.44 — payroll recap per accountant spec
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 18:00:37 +02:00
BOHA
e3b414d22c fix(attendance): payroll recap per accountant spec; multi-shift day rows; shared computation
Rekapitulace (accountant notes, confirmed by owner 2026-07):
- Odpracováno = all worked hours EXCEPT hours worked on holidays
  (was floor(worked/8)×8 — a 3h day printed as 0h)
- Vč. svátků a přesčasů = ALL worked hours; line2 − line1 = Svátek
  (was worked + vacation − 8h×worked-holidays — could print less than
  actually worked, and vacation inflated it)
- Přesčas = max(0, worked − fond), month-level, never negative
  (was the sub-8h remainder + vacation — printed 3h overtime for a
  3h month, 8h overtime for pure vacation, and −6h when a holiday
  was worked)
- Svátek = hours actually WORKED on holiday dates
  (was 8h per UNworked holiday — opposite meaning)
- So/Ne, Práce v noci, Dovolená, Fond unchanged (verified correct)

Single shared computeMzdaSummary now feeds BOTH the print and the
admin screen (they had drifted: capped vs uncapped holiday adjustment).

Print day table: one row PER RECORD — days with two shifts (real in
prod data) silently dropped all but the last record from the table
while the totals counted them all.

+7 spec tests (accountant's own examples); print snapshot updated to
the new spec values.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 18:00:17 +02:00
BOHA
89656ac2c6 chore(release): v2.4.43 — timezone-proof attendance print
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 16:26:44 +02:00
BOHA
94030230e7 fix(attendance): timezone-proof print dates; overnight-only time prefixes
Two bugs in the attendance admin print (Tisk on Správa docházky):

1. Viewer-timezone date shift: day rows are built from date-only strings
   ('2026-06-01'), which new Date() parses as UTC midnight per spec; local
   formatting then rendered the PREVIOUS day for any viewer west of UTC —
   a June print opened with '31. 5. Neděle' (a May row holding June 1's
   punches) and every weekday name + weekend tint shifted by one. Czech
   viewers were unaffected (UTC+1/+2), US viewers always hit it.
   formatDate / getCzechWeekday / isWeekendDate now parse the calendar day
   from the string parts — identical output in every timezone.

2. Every time cell carried a bogus date prefix ('1.6. 08:00'): the
   overnight-only guard compared the extracted date part against the raw
   wire shift_date ('2026-06-01T02:00:00') — never equal. Now compares
   normalized date parts; the prefix fires only for true overnight punches.

Verified end-to-end against the production June payload; +8 regression
tests (timezone-proof by construction — parts-based, no UTC parse).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 16:26:23 +02:00
13 changed files with 815 additions and 242 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "app-ts",
"version": "2.4.42",
"version": "2.4.47",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app-ts",
"version": "2.4.42",
"version": "2.4.47",
"license": "ISC",
"dependencies": {
"@anthropic-ai/sdk": "^0.102.0",

View File

@@ -1,6 +1,6 @@
{
"name": "app-ts",
"version": "2.4.42",
"version": "2.4.47",
"description": "",
"main": "dist/server.js",
"scripts": {

View File

@@ -337,7 +337,7 @@ exports[`buildUserSectionHtml > produces a stable per-user section (full output
</div>
<div class="summary-row">
<span class="summary-label">Odpracováno včetně svátků a přesčasů:</span>
<span class="summary-value">16,00h</span>
<span class="summary-value">8,00h</span>
</div>
<div class="summary-row">
<span class="summary-label">Dovolená:</span>
@@ -345,7 +345,11 @@ exports[`buildUserSectionHtml > produces a stable per-user section (full output
</div>
<div class="summary-row">
<span class="summary-label">Přesčas:</span>
<span class="summary-value">8,00h</span>
<span class="summary-value">0,00h</span>
</div>
<div class="summary-row summary-alert">
<span class="summary-label">Chybějící hodiny:</span>
<span class="summary-value">152,00h</span>
</div>
<div class="summary-row">
<span class="summary-label">Svátek:</span>

View File

@@ -0,0 +1,284 @@
import { describe, it, expect } from "vitest";
import {
computeMzdaSummary,
formatHoursDecimal1,
} from "../admin/utils/attendanceHelpers";
import { buildUserSectionHtml } from "../admin/hooks/useAttendanceAdmin";
/**
* BINDING payroll-recap formulas (owner spec 2026-07, back-computed against
* the real payslip of Dominik Vesecký 5/2026 — the dataset below is the
* built-in acceptance test and MUST match exactly, not approximately):
*
* fond = (PoPá dny, které NEJSOU svátek) × 8
* odpracováno = (kalendářní dny se záznamem Práce mimo svátek) × 8, paušálně
* svátek = čisté odpracované hodiny ve dnech svátku
* dovolená = Σ leave_hours (evidence)
* přesčas = max(0, (worked_total + dovolená) fond) [měsíční]
* vč. svátků = odpracováno + přesčas
* so/ne = čisté hodiny směn začínajících v So/Ne (celá směna)
* noc = průnik s 22:0006:00 minus pauzy v pásmu, ke dni začátku
*
* Expected 5/2026 (holidays 1.5. + 8.5.): fond 152 · odpracováno 144 ·
* svátek 8 · dovolená 24 · přesčas 17,25 (=17,3 na desetiny) · vč. 161,25
* (=161,3) · So/Ne 57,25 · noc 36,75 (payslip said 31 — accountant's own
* error, she missed the 31.5.→1.6. overnight shift; 36,75 is CORRECT).
*/
const W = (d: string, from: string, to: string, brk?: [string, string]) => ({
shift_date: `${d}T02:00:00`,
arrival_time: from.includes(" ") ? from.replace(" ", "T") : `${d}T${from}:00`,
departure_time: to.includes(" ") ? to.replace(" ", "T") : `${d}T${to}:00`,
break_start: brk
? brk[0].includes(" ")
? brk[0].replace(" ", "T")
: `${d}T${brk[0]}:00`
: null,
break_end: brk
? brk[1].includes(" ")
? brk[1].replace(" ", "T")
: `${d}T${brk[1]}:00`
: null,
leave_type: "work",
});
const V = (d: string, h: number) => ({
shift_date: `${d}T02:00:00`,
leave_type: "vacation",
leave_hours: h,
arrival_time: null,
departure_time: null,
break_start: null,
break_end: null,
});
/** The exact dataset from the spec (times with a space carry a full date). */
const DOMINIK_MAY_2026 = [
W("2026-05-01", "08:15", "17:15", ["12:30", "13:30"]),
W("2026-05-03", "21:30", "2026-05-04 06:15:00", [
"2026-05-04 01:52:00",
"2026-05-04 02:22:00",
]),
V("2026-05-05", 8),
V("2026-05-06", 8),
V("2026-05-07", 8),
W("2026-05-10", "21:15", "2026-05-11 06:30:00", [
"2026-05-11 01:52:00",
"2026-05-11 02:22:00",
]),
W("2026-05-12", "07:45", "16:00", ["11:52", "12:22"]),
W("2026-05-13", "08:00", "16:15", ["12:07", "12:37"]),
W("2026-05-14", "08:00", "16:15", ["12:07", "12:37"]),
W("2026-05-15", "08:00", "16:00", ["12:00", "12:30"]),
W("2026-05-16", "10:00", "23:30", ["16:45", "17:45"]),
W("2026-05-17", "21:30", "2026-05-18 06:30:00", [
"2026-05-18 02:00:00",
"2026-05-18 02:30:00",
]),
W("2026-05-19", "09:30", "17:00", ["13:15", "13:45"]),
W("2026-05-20", "08:30", "16:30", ["12:30", "13:00"]),
W("2026-05-21", "09:45", "15:15"),
W("2026-05-22", "10:45", "15:30"),
W("2026-05-24", "17:45", "2026-05-25 06:00:00", [
"23:45",
"2026-05-25 00:45:00",
]),
W("2026-05-26", "09:00", "14:30"),
W("2026-05-27", "10:00", "15:30"),
W("2026-05-28", "08:00", "15:45", ["11:45", "12:15"]),
W("2026-05-29", "08:15", "15:00", ["11:30", "12:00"]),
W("2026-05-31", "19:45", "2026-06-01 04:15:00", [
"2026-06-01 00:00:00",
"2026-06-01 00:30:00",
]),
];
describe("computeMzdaSummary — built-in acceptance dataset (Dominik 5/2026)", () => {
const s = computeMzdaSummary(DOMINIK_MAY_2026 as never, "2026-05");
it("Fond měsíce = 152 (19 PoPá dnů mimo svátky 1.5. a 8.5.)", () => {
expect(s.businessDays).toBe(19);
expect(s.fund).toBe(152);
});
it("Odpracováno = 144 (18 pracovních dnů mimo svátek × 8, paušálně)", () => {
expect(s.odpracovano).toBe(144);
});
it("Svátek = 8 (skutečné hodiny odpracované 1. 5.)", () => {
expect(s.svatekHours).toBe(8);
});
it("Dovolená = 24", () => {
expect(s.vacationHours).toBe(24);
});
it("worked_total = 145,25 (145:15 čistého času)", () => {
expect(s.workedHoursRaw).toBe(145.25);
});
it("Přesčas = 17,25 → zobrazeno 17,3 ((145,25 + 24) 152)", () => {
expect(s.prescas).toBe(17.25);
expect(formatHoursDecimal1(s.prescas * 60)).toBe("17,3");
});
it("Odpracováno včetně svátků a přesčasů = 161,25 → zobrazeno 161,3 (144 + 17,25)", () => {
expect(s.vcetneSvatku).toBe(161.25);
expect(formatHoursDecimal1(s.vcetneSvatku * 60)).toBe("161,3");
});
it("So/Ne = 57,25 (6 směn začínajících v So/Ne, celé směny)", () => {
expect(s.weekendHours).toBe(57.25);
});
it("Práce v noci = 36,75 — VČETNĚ směny 31.5.→1.6. (výplatnice s 31 h se mýlí)", () => {
expect(s.nightMinutes / 60).toBe(36.75);
});
it("Chybějící hodiny = 0 (145,25 + 24 pokrývá fond 152)", () => {
expect(s.manko).toBe(0);
});
});
describe("computeMzdaSummary — Chybějící hodiny (Dominik 6/2026, reálná data)", () => {
// Real production month exposing the gap the paušál hides: 21 attended days
// × 8 = 168 + 8h dovolená = 176 = fond exactly (weekend shifts nominally
// compensate 3 missing weekdays 1.6./11.6./15.6.), yet REAL worked time is
// only 136,5h → 31,5h below the fond. Přesčas must stay 0 (formulas are
// binding), manko must surface the 31,5.
const JUNE = [
W("2026-06-02", "06:15", "14:00", ["10:00", "10:30"]),
W("2026-06-03", "06:30", "13:30", ["10:00", "10:30"]),
W("2026-06-04", "06:00", "13:45", ["09:45", "10:15"]),
W("2026-06-05", "06:15", "13:45", ["10:00", "10:30"]),
W("2026-06-07", "07:15", "13:00", ["09:30", "10:00"]), // Sunday
W("2026-06-08", "07:15", "13:30", ["10:15", "10:45"]),
W("2026-06-09", "06:00", "11:15", ["09:30", "10:00"]),
W("2026-06-10", "06:00", "11:45", ["09:30", "10:00"]),
W("2026-06-12", "06:00", "13:45", ["09:45", "10:15"]),
W("2026-06-14", "17:30", "2026-06-15 04:15:00", ["22:45", "23:15"]), // Sun→Mon
W("2026-06-16", "07:30", "13:30", ["10:00", "10:30"]),
W("2026-06-17", "10:45", "13:15"),
W("2026-06-18", "06:00", "13:15", ["09:30", "10:00"]),
W("2026-06-19", "07:00", "13:15", ["10:00", "10:30"]),
W("2026-06-22", "06:00", "13:30", ["09:45", "10:15"]),
W("2026-06-23", "06:00", "13:45", ["09:45", "10:15"]),
W("2026-06-24", "05:30", "13:45", ["09:30", "10:00"]),
V("2026-06-25", 8),
W("2026-06-26", "05:45", "14:45", ["10:15", "10:45"]),
W("2026-06-27", "05:45", "17:00", ["11:15", "11:45"]), // Saturday
W("2026-06-29", "11:45", "14:30"),
W("2026-06-30", "06:30", "09:15"),
W("2026-06-30", "10:45", "13:30"),
];
const s = computeMzdaSummary(JUNE as never, "2026-06");
it("verified rows stay exactly as before (fond 176, odpracováno 168, přesčas 0)", () => {
expect(s.fund).toBe(176);
expect(s.businessDays).toBe(22);
expect(s.odpracovano).toBe(168); // 21 days × 8 flat
expect(s.vacationHours).toBe(8);
expect(s.workedHoursRaw).toBe(136.5);
expect(s.prescas).toBe(0); // (136,5 + 8) 176 < 0 — unchanged formula
expect(s.vcetneSvatku).toBe(168);
expect(s.svatekHours).toBe(0);
expect(s.weekendHours).toBe(26.25); // shifts starting 7.6., 14.6., 27.6.
// 14.6. shift (22:0004:15 minus break = 5:45) + early starts before
// 06:00: 24.6. 05:30 (0:30), 26.6. 05:45 (0:15), 27.6. 05:45 (0:15).
expect(s.nightMinutes / 60).toBe(6.75);
});
it("Chybějící hodiny = 31,5 — the gap the paušál nominally hides", () => {
expect(s.manko).toBe(31.5); // 176 (136,5 + 8)
});
it("nemoc a neplacené volno kryjí fond stejně jako dovolená", () => {
const withSick = [...JUNE, { ...V("2026-06-01", 8), leave_type: "sick" }];
const s2 = computeMzdaSummary(withSick as never, "2026-06");
expect(s2.sickHours).toBe(8);
expect(s2.manko).toBe(23.5); // 31,5 8
});
});
describe("computeMzdaSummary — formula edge cases", () => {
it("Odpracováno is a flat 8h per day: a lone 4:45 day counts as 8", () => {
const s = computeMzdaSummary(
[W("2026-06-02", "10:45", "15:30")] as never,
"2026-06",
);
expect(s.odpracovano).toBe(8);
expect(s.workedHoursRaw).toBe(4.75);
expect(s.prescas).toBe(0); // (4,75 + 0) 176 < 0
expect(s.vcetneSvatku).toBe(8); // odpracováno + přesčas
});
it("two shifts on one day count that day ONCE (8h, not 16h)", () => {
const s = computeMzdaSummary(
[
W("2026-06-02", "06:00", "10:00"),
W("2026-06-02", "14:00", "18:00"),
] as never,
"2026-06",
);
expect(s.odpracovano).toBe(8);
expect(s.workedHoursRaw).toBe(8);
});
it("dovolená covers the fond in Přesčas", () => {
// 176h fond (June 2026): 152h worked + 30h vacation = 182 → +6 přesčas.
const recs: unknown[] = [];
const days = [
"01",
"02",
"03",
"04",
"05",
"08",
"09",
"10",
"11",
"12",
"15",
"16",
"17",
"18",
"19",
"22",
"23",
"24",
"25",
].map((d) => `2026-06-${d}`);
for (const d of days) recs.push(W(d, "08:00", "16:30", ["12:00", "12:30"])); // 19×8=152
recs.push(V("2026-06-29", 8), V("2026-06-30", 8), V("2026-06-26", 14));
const s = computeMzdaSummary(recs as never, "2026-06");
expect(s.vacationHours).toBe(30);
expect(s.prescas).toBe(6);
});
it("a shift STARTING on a holiday goes to Svátek, not to Odpracováno days", () => {
const s = computeMzdaSummary(
[W("2026-07-06", "08:00", "18:30", ["12:00", "12:30"])] as never, // 6.7. holiday, 10h
"2026-07",
);
expect(s.svatekHours).toBe(10);
expect(s.odpracovano).toBe(0);
expect(s.fund).toBe(176); // 23 MonFri 6.7. holiday = 22 × 8
});
});
describe("print day table — multiple records on one day", () => {
it("renders one row per record (two shifts are both visible)", () => {
const records = [
W("2026-06-02", "06:00", "10:00"),
W("2026-06-02", "14:00", "18:00"),
];
const html = buildUserSectionHtml(
"1",
{ name: "Test", minutes: 480, vacation_hours: 0, records } as never,
{ month: "2026-06", month_name: "Červen 2026", user_totals: {} } as never,
);
expect(html).toContain("06:00");
expect(html).toContain("14:00");
const rows = html.match(/<td>2\. 6\. 2026<\/td>/g) || [];
expect(rows.length).toBe(2);
});
});

View File

@@ -0,0 +1,77 @@
import { describe, it, expect } from "vitest";
import {
getCzechWeekday,
isWeekendDate,
formatTimeOrDatetimePrint,
} from "../admin/utils/attendanceHelpers";
import { formatDate } from "../admin/utils/formatters";
/**
* Regression: the attendance admin print builds its day rows from date-ONLY
* strings ("2026-06-01"). `new Date("YYYY-MM-DD")` is UTC midnight per the
* ECMAScript spec, so formatting it with local getters rendered the PREVIOUS
* day for viewers west of UTC — a June print opened with "31. 5. 2026 Neděle"
* (a May row) and every weekday name was shifted by one. The helpers now
* parse the calendar day from the string parts, which is timezone-proof by
* construction: these assertions hold in EVERY zone (on a machine west of
* UTC the old implementation fails them).
*/
describe("attendance print — timezone-proof date rendering", () => {
it("formatDate renders a date-only string as that exact calendar day", () => {
expect(formatDate("2026-06-01")).toBe("1. 6. 2026");
expect(formatDate("2026-06-30")).toBe("30. 6. 2026");
});
it("formatDate keeps naive-datetime (wire format) behavior", () => {
expect(formatDate("2026-06-01T02:00:00")).toBe("1. 6. 2026");
});
it("getCzechWeekday names the string's own calendar day", () => {
expect(getCzechWeekday("2026-06-01")).toBe("Pondělí");
expect(getCzechWeekday("2026-06-06")).toBe("Sobota");
expect(getCzechWeekday("2026-06-07")).toBe("Neděle");
// naive-datetime wire format resolves to the same day
expect(getCzechWeekday("2026-06-01T02:00:00")).toBe("Pondělí");
});
it("isWeekendDate flags the string's own calendar day", () => {
expect(isWeekendDate("2026-06-06")).toBe(true); // Saturday
expect(isWeekendDate("2026-06-07")).toBe(true); // Sunday
expect(isWeekendDate("2026-06-01")).toBe(false); // Monday
expect(isWeekendDate("2026-06-06T02:00:00")).toBe(true);
});
it("agrees with a locally-constructed date in the current zone (guards a regression to UTC parsing)", () => {
// Local construction is the ground truth for "calendar day" in any zone.
const local = new Date(2026, 5, 1, 12).toLocaleDateString("cs-CZ", {
weekday: "long",
});
const expected = local.charAt(0).toUpperCase() + local.slice(1);
expect(getCzechWeekday("2026-06-01")).toBe(expected);
});
});
describe("attendance print — overnight date prefix on time cells", () => {
// shift_date arrives as a naive datetime on the wire ("2026-06-01T02:00:00");
// the guard used to compare it raw against the extracted date part, so the
// overnight-only "d.m." prefix fired on EVERY cell ("1.6. 08:00").
const wireShiftDate = "2026-06-01T02:00:00";
it("same-day punch renders time only", () => {
expect(
formatTimeOrDatetimePrint("2026-06-01T08:00:00", wireShiftDate),
).toBe("08:00");
});
it("overnight punch keeps the date prefix", () => {
expect(
formatTimeOrDatetimePrint("2026-06-02T01:30:00", wireShiftDate),
).toBe("2.6. 01:30");
});
it("date-only shiftDate also matches", () => {
expect(formatTimeOrDatetimePrint("2026-06-01T08:00:00", "2026-06-01")).toBe(
"08:00",
);
});
});

View File

@@ -0,0 +1,124 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import prisma from "../config/database";
import { getWorkfund } from "../services/attendance.service";
/**
* Print-recap parity for the Bilance page's monthly fund overview
* (getWorkfund), per the binding formulas (computeMzdaSummary):
* overtime (Přesčas) = max(0, worked + dovolená fond)
* missing (Chybějící hodiny) = max(0, fond (worked + dovolená + nemoc
* + neplacené volno))
* The two coverage bases differ deliberately: only dovolená earns toward
* overtime, every approved absence covers the fond.
*/
const USERNAME = "wf_parity_test_user";
let userId: number;
const june = (day: string) => new Date(`2026-06-${day}T00:00:00Z`);
const dt = (day: string, hm: string) => new Date(`2026-06-${day}T${hm}:00`);
beforeAll(async () => {
await prisma.attendance.deleteMany({
where: { users: { username: USERNAME } },
});
await prisma.users.deleteMany({ where: { username: USERNAME } });
// getAttendanceUsers includes only users whose role carries
// attendance.record — the seeded admin role has every permission.
const adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
if (!adminRole) throw new Error("Admin role not found — seed the DB first");
const user = await prisma.users.create({
data: {
username: USERNAME,
email: `${USERNAME}@test.local`,
password_hash:
"$2a$12$LJ3m4ys3Lg4oLBFnYP2amuPBzJnJBbGzCl5Y6X9Y8r0q5.s3L6OyO",
first_name: "Workfund",
last_name: "Parity",
is_active: true,
role_id: adminRole.id,
},
});
userId = user.id;
// June 2026 (fond 176 = 22 non-holiday weekdays × 8):
// 10 work days of 8h net (08:0016:30, 30min break) → worked 80
const workDays = ["01", "02", "03", "04", "05", "08", "09", "10", "11", "12"];
for (const d of workDays) {
await prisma.attendance.create({
data: {
user_id: userId,
shift_date: june(d),
arrival_time: dt(d, "08:00"),
departure_time: dt(d, "16:30"),
break_start: dt(d, "12:00"),
break_end: dt(d, "12:30"),
leave_type: "work",
},
});
}
// dovolená 24, nemoc 16, neplacené volno 8
const leaves: Array<[string, string, number]> = [
["15", "vacation", 8],
["16", "vacation", 8],
["17", "vacation", 8],
["18", "sick", 8],
["19", "sick", 8],
["22", "unpaid", 8],
];
for (const [d, type, hours] of leaves) {
await prisma.attendance.create({
data: {
user_id: userId,
shift_date: june(d),
leave_type: type as never,
leave_hours: hours,
},
});
}
});
afterAll(async () => {
await prisma.attendance.deleteMany({ where: { user_id: userId } });
await prisma.users.deleteMany({ where: { id: userId } });
});
describe("getWorkfund — print-recap parity", () => {
it("computes overtime from worked+dovolená and missing from all approved absences", async () => {
const data = await getWorkfund(2026);
// getWorkfund's future-year early return types months as a bare {} —
// narrow to the populated shape (2026 is never a future year here).
const months = data.months as Record<
string,
{
fund: number;
users: Record<
string,
{
worked: number;
covered: number;
covered_prescas: number;
overtime: number;
missing: number;
}
>;
}
>;
const juneData = months["6"];
expect(juneData).toBeTruthy();
expect(juneData.fund).toBe(176);
const us = juneData.users[String(userId)];
expect(us).toBeTruthy();
expect(us.worked).toBe(80);
// covered (manko base): 80 + 24 + 16 + 8
expect(us.covered).toBe(128);
// covered_prescas (Přesčas base): 80 + 24 — sick/unpaid excluded
expect(us.covered_prescas).toBe(104);
// Chybějící hodiny: 176 128
expect(us.missing).toBe(48);
// Přesčas: max(0, 104 176)
expect(us.overtime).toBe(0);
});
});

View File

@@ -18,10 +18,8 @@ import {
getDaysInMonth,
shiftDateForMonth,
formatHoursDecimal,
calculateNightMinutes,
normalizeDateStr,
holidaysInMonth,
calculateFreeHolidayHours,
computeMzdaSummary,
getCzechWeekday,
} from "../utils/attendanceHelpers";
import type {
@@ -99,6 +97,7 @@ interface UserTotal {
weekend_hours?: number;
night_minutes?: number;
worked_holiday_hours?: number; // sum of hours worked ON a holiday
manko?: number; // Chybějící hodiny: real clock time below the fond
records?: AttendanceRecord[];
}
@@ -216,116 +215,36 @@ function computeUserTotals(
}
}
// Add fund data per user (matching PHP addFundDataToUserTotals)
const [yearStr, monthStr] = month.split("-");
const yr = parseInt(yearStr, 10);
const mo = parseInt(monthStr, 10) - 1;
// Count Mon-Fri business days in month (INCLUDING holidays).
// The fund is rawBizDays × 8 — holidays stay in the count so the
// user is paid for them via the fund. Svátek (free holiday hours) is
// computed separately as "8h per holiday the user did not work".
let rawBizDays = 0;
const cur = new Date(yr, mo, 1);
while (cur.getMonth() === mo) {
const dow = cur.getDay();
if (dow !== 0 && dow !== 6) rawBizDays++;
cur.setDate(cur.getDate() + 1);
}
const holidayDates = holidaysInMonth(yr, mo + 1);
// Rekapitulace per user — the SAME shared computation the print uses
// (computeMzdaSummary), so the screen and the printed sheet can never
// disagree. Accountant spec 2026-07: Odpracováno = worked minus
// holiday-worked; Vč. svátků = ALL worked; Přesčas = max(0, worked fond);
// Svátek = hours actually worked on holidays.
for (const uid of Object.keys(totals)) {
const t = totals[uid];
const userRecords = recordsByUser.get(Number(uid)) || [];
// Odpracováno: floor(worked / 8) × 8 — round to whole days, drop remainder.
const workedHoursRaw = t.minutes / 60;
const odpracovano = Math.floor(workedHoursRaw / 8) * 8;
// So/Ne: sum of worked hours on Sat/Sun (raw, not rounded).
const weekendHours = userRecords
.filter(
(r) =>
(r.leave_type || "work") === "work" && isWeekendDate(r.shift_date),
)
.reduce((sum, r) => sum + calculateWorkMinutesPrint(r) / 60, 0);
// Práce v noci: minutes in 22:00-06:00 across all work records.
const nightMinutes = userRecords
.filter((r) => (r.leave_type || "work") === "work")
.reduce((sum, r) => sum + calculateNightMinutes(r), 0);
// Svátek (free): 8h per holiday the user did not work.
const freeHolidayHours = calculateFreeHolidayHours(
userRecords,
holidayDates,
);
// Worked holidays: holidays the user DID work (counted toward
// Odpracováno, but their 8h must not flow into Přesčas).
const workedDatesSet = new Set(
userRecords
.filter((r) => (r.leave_type || "work") === "work")
.map((r) => normalizeDateStr(r.shift_date))
.filter(Boolean),
);
let workedHolidayCount = 0;
let workedHolidayHours = 0;
for (const hd of holidayDates) {
if (workedDatesSet.has(hd)) workedHolidayCount++;
}
// Sum the actual hours worked on holiday dates (for the KPI card's
// "fond used" total = real_work + vacation + worked_holiday + free_holiday).
for (const r of userRecords) {
if ((r.leave_type || "work") !== "work") continue;
const d = normalizeDateStr(r.shift_date);
if (d && holidayDates.includes(d)) {
workedHolidayHours += calculateWorkMinutesPrint(r) / 60;
}
}
// Fund = Mon-Fri × 8h. Holidays count as work days (already in rawBizDays).
const fund = rawBizDays * 8;
// Včetně svátků a přesčasů (mzda formula):
// odpracovano + vacation + remainder min(freeHols, workedHols × 8)
//
// Two-way logic matching the print:
// • If the user worked at least one holiday, that worked holiday's
// 8h is in Odpracováno and shouldn't also count as Přesčas. We
// subtract one 8h per worked holiday (capped at the total free
// holiday hours — can't go negative).
// • If the user did NOT work any holiday, no adjustment is needed:
// all unworked holidays are already paid via the Svátek line and
// don't flow into Přesčas, so vcetne_svatku just equals the
// work + vacation + remainder.
const remainder = workedHoursRaw - odpracovano;
const holidayAdj = Math.min(freeHolidayHours, workedHolidayCount * 8);
const vcetneSv = odpracovano - holidayAdj + t.vacation_hours + remainder;
// Přesčas = vcetneSv odpracovano (derived).
const prescas = vcetneSv - odpracovano;
const s = computeMzdaSummary(userRecords, month);
// Legacy fields (kept so existing UI doesn't break).
const workedHours = Math.round(workedHoursRaw * 10) / 10;
const workedHours = Math.round(s.workedHoursRaw * 10) / 10;
const covered = Math.round((workedHours + t.vacation_hours) * 10) / 10;
t.fund = fund;
t.business_days = rawBizDays;
t.fund = s.fund;
t.business_days = s.businessDays;
t.worked_hours = workedHours;
t.covered = covered;
t.missing = Math.max(0, Math.round((fund - covered) * 10) / 10);
t.overtime = Math.max(0, Math.round((covered - fund) * 10) / 10);
t.missing = Math.max(0, Math.round((s.fund - covered) * 10) / 10);
t.overtime = Math.max(0, Math.round((covered - s.fund) * 10) / 10);
t.worked_hours_raw = workedHoursRaw;
t.odpracovano = odpracovano;
t.vcetne_svatku = vcetneSv;
t.prescas = prescas;
t.svatek = freeHolidayHours;
t.weekend_hours = weekendHours;
t.night_minutes = nightMinutes;
t.worked_holiday_hours = workedHolidayHours;
t.worked_hours_raw = s.workedHoursRaw;
t.odpracovano = s.odpracovano;
t.vcetne_svatku = s.vcetneSvatku;
t.prescas = s.prescas;
t.svatek = s.svatekHours;
t.weekend_hours = s.weekendHours;
t.night_minutes = s.nightMinutes;
t.worked_holiday_hours = s.svatekHours;
t.manko = s.manko;
}
return totals;
@@ -390,10 +309,23 @@ export function buildUserSectionHtml(
userData: UserTotal,
printData: PrintData,
): string {
// Build a date-keyed lookup of the user's records.
const recordsByDate = new Map<string, AttendanceRecord>();
// Build a date-keyed lookup of the user's records. A day may hold MULTIPLE
// records (two shifts, or work + partial-day vacation) — keep them ALL; a
// single-record map silently dropped every shift but the last one.
const recordsByDate = new Map<string, AttendanceRecord[]>();
for (const r of userData.records || []) {
recordsByDate.set(normalizeDateStr(r.shift_date), r);
const key = normalizeDateStr(r.shift_date);
const list = recordsByDate.get(key);
if (list) list.push(r);
else recordsByDate.set(key, [r]);
}
// Stable in-day order: by arrival time (leave records without times last).
for (const list of recordsByDate.values()) {
list.sort((a, b) =>
String(a.arrival_time || "9999").localeCompare(
String(b.arrival_time || "9999"),
),
);
}
// Iterate one row per day of the month.
@@ -407,19 +339,14 @@ export function buildUserSectionHtml(
const rows: string[] = [];
for (let d = 1; d <= daysInMonth; d++) {
const dateStr = shiftDateForMonth(yr, mo, d);
const record = recordsByDate.get(dateStr);
const dayRecords = recordsByDate.get(dateStr);
const weekend = isWeekendDate(dateStr);
const holiday = isHoliday(dateStr);
const leaveType = (record?.leave_type as string) || "work";
const rowClasses = [
weekend && "weekend",
holiday && "holiday",
leaveType === "vacation" && "vacation",
]
if (!dayRecords || dayRecords.length === 0) {
const rowClasses = [weekend && "weekend", holiday && "holiday"]
.filter(Boolean)
.join(" ");
if (!record) {
rows.push(`<tr class="${rowClasses}">
<td>${escapeHtml(formatDate(dateStr))}</td>
<td>${escapeHtml(getCzechWeekday(dateStr))}</td>
@@ -434,6 +361,18 @@ export function buildUserSectionHtml(
continue;
}
// One row PER RECORD — a day can hold two shifts, or work + partial-day
// vacation. (A single row per day silently dropped the extra shifts.)
for (const record of dayRecords) {
const leaveType = (record.leave_type as string) || "work";
const rowClasses = [
weekend && "weekend",
holiday && "holiday",
leaveType === "vacation" && "vacation",
]
.filter(Boolean)
.join(" ");
const isLeave = leaveType !== "work";
const workMinutes = calculateWorkMinutesPrint(record);
const hours = Math.floor(workMinutes / 60);
@@ -464,109 +403,51 @@ export function buildUserSectionHtml(
<td>${escapeHtml(record.notes || "")}</td>
</tr>`);
}
// ----- mzda-style summary numbers (computed here, not from userData,
// because the backend's getPrintData only returns the legacy fields). -----
// Worked minutes: sum of calculateWorkMinutesPrint across work records.
let workedMinutes = 0;
let weekendHoursRaw = 0;
let nightMinutes = 0;
for (const r of userRecords) {
const leaveType = r.leave_type || "work";
if (leaveType !== "work") continue;
const m = calculateWorkMinutesPrint(r);
workedMinutes += m;
if (isWeekendDate(r.shift_date)) {
weekendHoursRaw += m / 60;
}
nightMinutes += calculateNightMinutes(r);
}
// Sum of vacation/sick/unpaid hours (in hours, not minutes). The
// "holiday" leave_type is auto-computed from Czech holidays further down
// and no longer selectable in the UI, so it's deliberately omitted here.
let vacationHours = 0;
for (const r of userRecords) {
const lt = r.leave_type || "work";
if (lt === "work") continue;
const h = Number(r.leave_hours) || 8;
if (lt === "vacation") vacationHours += h;
}
// Odpracováno: floor(worked / 8) × 8.
const workedHoursRaw = workedMinutes / 60;
const odpracovano = Math.floor(workedHoursRaw / 8) * 8;
// Free Svátek: 8h per holiday date the user did not work.
const holidayDates = holidaysInMonth(yr, mo);
const workedDates = new Set(
userRecords
.filter((r) => (r.leave_type || "work") === "work")
.map((r) => normalizeDateStr(r.shift_date))
.filter(Boolean),
);
let freeHolidayHours = 0;
let workedHolidayCount = 0;
for (const hd of holidayDates) {
if (workedDates.has(hd)) workedHolidayCount++;
else freeHolidayHours += 8;
}
// Fund: count Mon-Fri (incl. holidays) × 8h.
let rawBizDays = 0;
const cur = new Date(yr, mo - 1, 1);
while (cur.getMonth() === mo - 1) {
const dow = cur.getDay();
if (dow !== 0 && dow !== 6) rawBizDays++;
cur.setDate(cur.getDate() + 1);
}
const businessDays = rawBizDays;
const fund = businessDays * 8;
// Včetně svátků a přesčasů: floor(worked/8)*8 worked_holiday*8 + vacation + remainder.
// (A worked holiday counts toward Odpracováno, but its 8h should not flow
// into Přesčas — so we subtract it here. Unworked holidays are paid via
// the fund and don't affect this line.)
const remainder = workedHoursRaw - odpracovano;
const vcetneSv =
odpracovano - workedHolidayCount * 8 + vacationHours + remainder;
// Přesčas = #2 - #1.
const prescas = vcetneSv - odpracovano;
// Rekapitulace — single shared implementation (accountant spec 2026-07):
// Odpracováno = all worked hours EXCEPT hours worked on holidays
// Vč. svátků a přesč. = ALL worked hours (line2 line1 = Svátek)
// Přesčas = max(0, worked fond)
// Svátek = hours actually worked on holiday dates
const s = computeMzdaSummary(userRecords, printData.month);
const summaryHtml = `<div class="user-summary">
<div class="summary-row">
<span class="summary-label">Odpracováno:</span>
<span class="summary-value">${formatHoursDecimal(odpracovano * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.odpracovano * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Odpracováno včetně svátků a přesčasů:</span>
<span class="summary-value">${formatHoursDecimal(vcetneSv * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.vcetneSvatku * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Dovolená:</span>
<span class="summary-value">${formatHoursDecimal(vacationHours * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.vacationHours * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Přesčas:</span>
<span class="summary-value">${formatHoursDecimal(prescas * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.prescas * 60)}h</span>
</div>
<div class="summary-row${s.manko > 0 ? " summary-alert" : ""}">
<span class="summary-label">Chybějící hodiny:</span>
<span class="summary-value">${formatHoursDecimal(s.manko * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Svátek:</span>
<span class="summary-value">${formatHoursDecimal(freeHolidayHours * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.svatekHours * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">So/Ne:</span>
<span class="summary-value">${formatHoursDecimal(weekendHoursRaw * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.weekendHours * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Práce v noci:</span>
<span class="summary-value">${formatHoursDecimal(nightMinutes)}h</span>
<span class="summary-value">${formatHoursDecimal(s.nightMinutes)}h</span>
</div>
<div class="summary-row summary-fund">
<span class="summary-label">Fond měsíce:</span>
<span class="summary-value">${formatHoursDecimal(fund * 60)}h (${businessDays} dnů)</span>
<span class="summary-value">${formatHoursDecimal(s.fund * 60)}h (${s.businessDays} dnů)</span>
</div>
<div class="legend">
<span class="legend-item"><span class="legend-swatch weekend"></span>Víkend (So/Ne)</span>
@@ -672,6 +553,9 @@ export function buildPrintHtml(
}
.user-summary .summary-label { color: #555; }
.user-summary .summary-value { font-weight: 600; }
/* Chybějící hodiny > 0 — must jump out of the sheet, not hide in it. */
.user-summary .summary-alert .summary-label,
.user-summary .summary-alert .summary-value { color: #b00020; font-weight: 700; }
.user-summary .summary-fund {
border-top: 1px solid #ddd; margin-top: 4px; padding-top: 6px;
}

View File

@@ -77,7 +77,10 @@ export interface BalancesData {
export interface FundUserData {
name: string;
worked: number;
/** worked + dovolená + nemoc + neplacené volno — covers the fond (manko base). */
covered: number;
/** worked + dovolená only — the Přesčas base (print-recap parity). */
covered_prescas: number;
overtime: number;
missing: number;
}

View File

@@ -46,28 +46,29 @@ interface UserTotalData {
prescas?: number;
svatek?: number;
worked_holiday_hours?: number;
/** Chybějící hodiny: real clock time below the fond (approved absences count). */
manko?: number;
}
/** Fond "used" total mirrors the Fond footer line below:
* real_worked + vacation + worked_holiday + free_holiday. */
/** Fond coverage — print-recap parity (computeMzdaSummary): real worked
* hours + every approved absence (dovolená + nemoc + neplacené volno).
* This is the base the Chybějící hodiny line measures against. */
function getFondUsed(data: UserTotalData): number {
const realWorked = data.worked_hours_raw ?? data.worked_hours;
return (
realWorked +
(data.vacation_hours ?? 0) +
(data.worked_holiday_hours ?? 0) +
(data.svatek ?? 0)
(data.sick_hours ?? 0) +
(data.unpaid_hours ?? 0)
);
}
/** Maps the Fond delta (used fund) to a ProgressBar color token, mirroring
* the legacy getFundBarBackground conditional: over fund → warning, exactly
* at fund → success, under fund → primary (was the accent gradient). */
/** Bar color follows the print recap: Přesčas > 0 → warning, Chybějící
* hodiny > 0 → error, exactly covered → success. */
function getFundBarColor(data: UserTotalData): ProgressColor {
const delta = getFondUsed(data) - (data.fund ?? 0);
if (delta > 0) return "warning";
if (delta >= 0) return "success";
return "primary";
if ((data.prescas ?? 0) > 0) return "warning";
if ((data.manko ?? 0) > 0) return "error";
return "success";
}
const PrintIcon = (
@@ -293,17 +294,24 @@ export default function AttendanceAdmin() {
label={`Nep: ${ut.unpaid_hours}h`}
/>
)}
{ut.manko !== undefined && ut.manko > 0 && (
<StatusChip
color="error"
label={`Chybí: ${String(Math.round(ut.manko * 100) / 100).replace(".", ",")}h`}
title="Skutečně odpracované hodiny + schválené absence nedosahují fondu měsíce"
/>
)}
</Box>
{/* Fond usage */}
{/* Fond usage — the ± badges are the PRINT recap values
(Přesčas / Chybějící hodiny), so the card and the
printed sheet can never disagree. */}
{ut.fund !== null &&
(() => {
// Fond "used" = real_worked + vacation +
// worked_holiday + free_holiday (everything the user
// actually got paid for this month).
const fondUsed = getFondUsed(ut);
const fundVal = ut.fund ?? 0;
const delta = fondUsed - fundVal;
const prescas = ut.prescas ?? 0;
const manko = ut.manko ?? 0;
const pct = Math.min(
100,
(fondUsed / (ut.fund || 1)) * 100,
@@ -325,26 +333,28 @@ export default function AttendanceAdmin() {
Fond: {formatHoursDecimal(fondUsed * 60)}h /{" "}
{formatHoursDecimal(fundVal * 60)}h
</Typography>
{delta > 0 && (
{prescas > 0 && (
<Typography
variant="caption"
title="Přesčas (worked + dovolená nad fond)"
sx={{
fontWeight: 600,
color: "warning.main",
}}
>
+{formatHoursDecimal(delta * 60)}h
+{formatHoursDecimal(prescas * 60)}h
</Typography>
)}
{delta < 0 && (
{manko > 0 && (
<Typography
variant="caption"
title="Chybějící hodiny do fondu"
sx={{
fontWeight: 600,
color: "error.main",
}}
>
-{formatHoursDecimal(Math.abs(delta) * 60)}h
-{formatHoursDecimal(manko * 60)}h
</Typography>
)}
</Box>

View File

@@ -251,6 +251,7 @@ export default function AttendanceBalances() {
let totalFund = 0;
let totalWorked = 0;
let totalCovered = 0;
let totalCoveredPrescas = 0;
for (const monthData of Object.values(fundData.months)) {
// Use prorated fund (fund_to_date) for current month, full fund for past
totalFund += monthData.fund_to_date ?? monthData.fund;
@@ -258,15 +259,20 @@ export default function AttendanceBalances() {
if (us) {
totalWorked += us.worked;
totalCovered += us.covered;
// Older cached payloads may lack covered_prescas — fall back to
// covered (the pre-parity behavior) rather than dropping to 0.
totalCoveredPrescas += us.covered_prescas ?? us.covered;
}
}
// Print-recap parity: missing (Chybějící hodiny) counts every approved
// absence; overtime (Přesčas) counts only worked + dovolená.
const missing = Math.max(
0,
Math.round((totalFund - totalCovered) * 10) / 10,
);
const overtime = Math.max(
0,
Math.round((totalCovered - totalFund) * 10) / 10,
Math.round((totalCoveredPrescas - totalFund) * 10) / 10,
);
return {
fund: totalFund,

View File

@@ -173,7 +173,10 @@ export const formatTimeOrDatetimePrint = (
const timeDate = dateMatch
? `${dateMatch[1]}-${dateMatch[2]}-${dateMatch[3]}`
: "";
if (timeDate && timeDate !== shiftDate) {
// Compare DATE PARTS: shiftDate arrives as a naive datetime off the wire
// ("2026-06-01T02:00:00"), so a raw string compare never matched and the
// overnight-only date prefix fired on every single time cell.
if (timeDate && timeDate !== normalizeDateStr(shiftDate)) {
const datePart = `${parseInt(dateMatch![3])}.${parseInt(dateMatch![2])}.`;
return `${datePart} ${extractTime(datetime)}`;
}
@@ -203,9 +206,23 @@ export const calculateWorkMinutesPrint = (record: AttendanceRecord): number => {
// Print template helpers (mzda-style counting)
// ---------------------------------------------------------------------------
/**
* Parse the calendar day of a date-only or naive-datetime string as a LOCAL
* Date. `new Date("YYYY-MM-DD")` is UTC midnight per the ECMAScript spec —
* in timezones west of UTC it renders as the PREVIOUS day, so a US viewer's
* June print started with "31. 5. Neděle" and every weekday name was shifted.
* Building the Date from its string parts keeps the calendar day identical
* in every timezone.
*/
const localDayFromString = (dateStr: string): Date => {
const m = String(dateStr).match(/^(\d{4})-(\d{2})-(\d{2})/);
if (m) return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
return new Date(dateStr);
};
/** Returns the Czech weekday name with the first letter capitalized. */
export const getCzechWeekday = (dateStr: string): string => {
const wd = new Date(dateStr).toLocaleDateString("cs-CZ", {
const wd = localDayFromString(dateStr).toLocaleDateString("cs-CZ", {
weekday: "long",
});
return wd.charAt(0).toUpperCase() + wd.slice(1);
@@ -213,7 +230,7 @@ export const getCzechWeekday = (dateStr: string): string => {
/** True if the date is a Saturday or Sunday. */
export const isWeekendDate = (dateStr: string): boolean => {
const dow = new Date(dateStr).getDay();
const dow = localDayFromString(dateStr).getDay();
return dow === 0 || dow === 6;
};
@@ -353,3 +370,142 @@ export const calculateFreeHolidayHours = (
}
return free;
};
// ---------------------------------------------------------------------------
// Mzda rekapitulace (single source — the print AND the admin screen consume
// this, so the two can never drift again). Formulas are BINDING per the
// accountant-verified spec (2026-07, back-computed to the tenth of an hour
// against a real payslip — Dominik Vesecký 5/2026; the built-in dataset test
// in attendance-mzda-summary.test.ts pins every line). Do not "improve" them:
// fond = (PoPá dny, které NEJSOU svátek) × 8
// odpracováno = (kalendářní dny se záznamem Práce mimo svátek) × 8 — FLAT
// 8 h per day regardless of the shift's real length; real
// deviations settle monthly via Přesčas
// svátek = skutečné čisté hodiny odpracované ve dnech svátku
// dovolená = Σ leave_hours (evidence only, never from timestamps)
// přesčas = max(0, (worked_total + dovolená) fond) [monthly]
// vč. svátků = odpracováno + přesčas (plain sum, NOT from timestamps)
// so/ne = čisté hodiny směn ZAČÍNAJÍCÍCH v So/Ne (celá směna)
// noc = průnik směny s 22:0006:00 minus pauzy v pásmu; celá směna
// patří dni svého ZAČÁTKU (i přes hranici měsíce)
// ---------------------------------------------------------------------------
export interface MzdaSummary {
/** worked_total: all net worked hours (arrival→departure minus breaks). */
workedHoursRaw: number;
/** Odpracováno: non-holiday calendar days with a work record × 8 h flat. */
odpracovano: number;
/** Odpracováno včetně svátků a přesčasů = odpracovano + prescas. */
vcetneSvatku: number;
/** Dovolená: sum of vacation leave_hours (hour-based, partial days allowed). */
vacationHours: number;
/** Přesčas: max(0, (worked_total + dovolená) fond) — monthly, never daily. */
prescas: number;
/** Svátek: net hours actually WORKED on public-holiday dates. */
svatekHours: number;
/** So/Ne: net hours of shifts whose START day is Sat/Sun (whole shift). */
weekendHours: number;
/** Práce v noci: minutes in 22:0006:00 minus breaks in the window. */
nightMinutes: number;
/** Fond měsíce: MonFri days that are NOT public holidays × 8 h. */
fund: number;
/** MonFri non-holiday day count backing the fond. */
businessDays: number;
/** Nemoc: sum of sick leave_hours (evidence records). */
sickHours: number;
/** Neplacené volno: sum of unpaid leave_hours (evidence records). */
unpaidHours: number;
/**
* Chybějící hodiny (manko):
* max(0, fond (worked_total + dovolená + nemoc + neplacené volno))
* — REAL clock hours below the fond. A supplement next to Přesčas, never a
* replacement: the paušál Odpracováno can nominally cover the fond (weekend
* work compensating missing weekdays) while dozens of real hours are
* missing — e.g. Dominik 6/2026: paušál 168 + 8 dovolená = fond 176, yet
* real worked was 136,5 → manko 31,5. This line makes that visible.
*/
manko: number;
}
/** Compute the payroll recap for one user's month of records. */
export const computeMzdaSummary = (
records: AttendanceRecord[],
monthStr: string,
): MzdaSummary => {
const [yearStr, monthNumStr] = monthStr.split("-");
const yr = parseInt(yearStr, 10);
const mo = parseInt(monthNumStr, 10);
const holidaySet = new Set(holidaysInMonth(yr, mo));
let workedMinutes = 0;
let svatekMinutes = 0;
let weekendMinutes = 0;
let nightMinutes = 0;
let vacationHours = 0;
let sickHours = 0;
let unpaidHours = 0;
// Distinct non-holiday calendar days (start day) with a "Práce" record —
// two shifts on one day still count that day once.
const workDays = new Set<string>();
for (const r of records) {
const lt = r.leave_type || "work";
if (lt !== "work") {
// "holiday" placeholder records are evidence-only — skip everywhere.
if (lt === "vacation") vacationHours += Number(r.leave_hours) || 8;
else if (lt === "sick") sickHours += Number(r.leave_hours) || 8;
else if (lt === "unpaid") unpaidHours += Number(r.leave_hours) || 8;
continue;
}
const m = calculateWorkMinutesPrint(r);
workedMinutes += m;
const day = normalizeDateStr(r.shift_date);
if (holidaySet.has(day)) {
svatekMinutes += m;
} else if (day) {
workDays.add(day);
}
if (isWeekendDate(day)) weekendMinutes += m;
nightMinutes += calculateNightMinutes(r);
}
// Fond: MonFri days that are NOT public holidays × 8 h.
let businessDays = 0;
const cur = new Date(yr, mo - 1, 1);
while (cur.getMonth() === mo - 1) {
const dow = cur.getDay();
if (dow !== 0 && dow !== 6) {
const dayStr = `${yr}-${String(mo).padStart(2, "0")}-${String(cur.getDate()).padStart(2, "0")}`;
if (!holidaySet.has(dayStr)) businessDays++;
}
cur.setDate(cur.getDate() + 1);
}
const fund = businessDays * 8;
const workedHoursRaw = workedMinutes / 60;
const odpracovano = workDays.size * 8;
const prescas = Math.max(0, workedHoursRaw + vacationHours - fund);
// Chybějící hodiny: REAL clock time (not the paušál) vs the fond — approved
// absences (dovolená/nemoc/neplacené volno) cover the fond.
const manko = Math.max(
0,
fund - (workedHoursRaw + vacationHours + sickHours + unpaidHours),
);
return {
workedHoursRaw,
odpracovano,
vcetneSvatku: odpracovano + prescas,
vacationHours,
prescas,
svatekHours: svatekMinutes / 60,
weekendHours: weekendMinutes / 60,
nightMinutes,
fund,
businessDays,
sickHours,
unpaidHours,
manko,
};
};

View File

@@ -33,7 +33,15 @@ export function formatMultiCurrency(
export function formatDate(dateStr: string | null | undefined): string {
if (!dateStr) return "—";
const d = new Date(dateStr);
// Date-ONLY strings ("2026-06-01") parse as UTC midnight per the spec, which
// renders as the PREVIOUS day in timezones west of UTC — a US viewer's June
// attendance print started with 31. 5. Parse the parts instead so the
// calendar day is identical in every timezone. Datetime strings keep the
// local-parse behavior (naive wire times are already local).
const m = String(dateStr).match(/^(\d{4})-(\d{2})-(\d{2})$/);
const d = m
? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
: new Date(dateStr);
return d.toLocaleDateString("cs-CZ");
}

View File

@@ -574,6 +574,7 @@ export async function getWorkfund(year: number) {
name: string;
worked: number;
covered: number;
covered_prescas: number;
overtime: number;
missing: number;
}
@@ -614,6 +615,7 @@ export async function getWorkfund(year: number) {
name: string;
worked: number;
covered: number;
covered_prescas: number;
overtime: number;
missing: number;
}
@@ -624,6 +626,7 @@ export async function getWorkfund(year: number) {
let worked = 0;
let vacationHours = 0;
let sickHours = 0;
let unpaidHours = 0;
for (const rec of recs) {
const lt = (rec.leave_type as string) || "work";
if (lt === "work") {
@@ -639,21 +642,35 @@ export async function getWorkfund(year: number) {
vacationHours += Number(rec.leave_hours) || 8;
} else if (lt === "sick") {
sickHours += Number(rec.leave_hours) || 8;
} else if (lt === "unpaid") {
unpaidHours += Number(rec.leave_hours) || 8;
}
// "holiday" is auto-derived from Czech public holidays.
}
// Print-recap parity (computeMzdaSummary — the binding formulas):
// overtime (Přesčas) = max(0, worked + dovolená fond)
// missing (Chybějící hodiny) = max(0, fond (worked + dovolená
// + nemoc + neplacené volno))
// The two coverage sets differ deliberately: only dovolená earns
// toward overtime, but every approved absence covers the fond.
const userFund = fundToDate;
const workedRound = Math.round(worked * 10) / 10;
const leaveHours = vacationHours + sickHours;
const covered = Math.round((worked + leaveHours) * 10) / 10;
const coveredPrescas = Math.round((worked + vacationHours) * 10) / 10;
const covered =
Math.round((worked + vacationHours + sickHours + unpaidHours) * 10) /
10;
const missing = Math.max(0, Math.round((userFund - covered) * 10) / 10);
const overtime = Math.max(0, Math.round((covered - userFund) * 10) / 10);
const overtime = Math.max(
0,
Math.round((coveredPrescas - userFund) * 10) / 10,
);
monthUsers[String(u.id)] = {
name: `${u.first_name} ${u.last_name}`.trim(),
worked: workedRound,
covered,
covered_prescas: coveredPrescas,
overtime,
missing,
};