@kernhq/module-hr 0.18.1 → 0.20.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 (50) hide show
  1. package/dist/contract/capabilities.d.ts.map +1 -1
  2. package/dist/contract/capabilities.js +45 -0
  3. package/dist/contract/capabilities.js.map +1 -1
  4. package/dist/contract/exports.d.ts +459 -0
  5. package/dist/contract/exports.d.ts.map +1 -0
  6. package/dist/contract/exports.js +331 -0
  7. package/dist/contract/exports.js.map +1 -0
  8. package/dist/contract/index.d.ts +2 -0
  9. package/dist/contract/index.d.ts.map +1 -1
  10. package/dist/contract/index.js +2 -0
  11. package/dist/contract/index.js.map +1 -1
  12. package/dist/contract/permissions.d.ts +10 -2
  13. package/dist/contract/permissions.d.ts.map +1 -1
  14. package/dist/contract/permissions.js +44 -5
  15. package/dist/contract/permissions.js.map +1 -1
  16. package/dist/contract/rosters.d.ts +183 -0
  17. package/dist/contract/rosters.d.ts.map +1 -0
  18. package/dist/contract/rosters.js +138 -0
  19. package/dist/contract/rosters.js.map +1 -0
  20. package/dist/contract/router.d.ts +893 -0
  21. package/dist/contract/router.d.ts.map +1 -1
  22. package/dist/contract/router.js +220 -1
  23. package/dist/contract/router.js.map +1 -1
  24. package/dist/server/router.d.ts +1210 -0
  25. package/dist/server/router.d.ts.map +1 -1
  26. package/dist/server/router.js +578 -1
  27. package/dist/server/router.js.map +1 -1
  28. package/dist/server/schema.d.ts +727 -1
  29. package/dist/server/schema.d.ts.map +1 -1
  30. package/dist/server/schema.js +105 -0
  31. package/dist/server/schema.js.map +1 -1
  32. package/dist/server/services/exports.d.ts +321 -0
  33. package/dist/server/services/exports.d.ts.map +1 -0
  34. package/dist/server/services/exports.js +765 -0
  35. package/dist/server/services/exports.js.map +1 -0
  36. package/dist/server/services/rosters.d.ts +166 -0
  37. package/dist/server/services/rosters.d.ts.map +1 -0
  38. package/dist/server/services/rosters.js +268 -0
  39. package/dist/server/services/rosters.js.map +1 -0
  40. package/migrations/0012_rosters.sql +163 -0
  41. package/migrations/meta/0012_snapshot.json +4847 -0
  42. package/migrations/meta/_journal.json +7 -0
  43. package/package.json +1 -1
  44. package/src/client/messages.ts +13 -0
  45. package/src/contract/capabilities.ts +45 -0
  46. package/src/contract/exports.ts +354 -0
  47. package/src/contract/index.ts +2 -0
  48. package/src/contract/permissions.ts +47 -5
  49. package/src/contract/rosters.ts +156 -0
  50. package/src/contract/router.ts +256 -0
@@ -78,6 +78,13 @@
78
78
  "when": 1787858088123,
79
79
  "tag": "0011_privacy",
80
80
  "breakpoints": true
81
+ },
82
+ {
83
+ "idx": 12,
84
+ "version": "7",
85
+ "when": 1787864979651,
86
+ "tag": "0012_rosters",
87
+ "breakpoints": true
81
88
  }
82
89
  ]
83
90
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kernhq/module-hr",
3
- "version": "0.18.1",
3
+ "version": "0.20.0",
4
4
  "description": "Kern HR module: people, offices, org chart, calendars",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -490,6 +490,8 @@ export const en: Record<string, Message> = {
490
490
  'hr.cap_legal_entities_desc': 'Several employing companies, for a group operating across borders',
491
491
  'hr.cap_offices': 'Offices',
492
492
  'hr.cap_offices_desc': 'More than one place of work, each with its own country, timezone and holidays',
493
+ 'hr.cap_payroll_export': 'Payroll export',
494
+ 'hr.cap_payroll_export_desc': 'Hand a closed period to a payroll provider as CSV, per legal entity',
493
495
  'hr.cap_periods': 'Payroll periods',
494
496
  'hr.cap_periods_desc': 'Close a month so a filed payroll cannot move underneath it',
495
497
  'hr.capabilities_desc':
@@ -1946,6 +1948,8 @@ export const ar: Record<string, Message> = {
1946
1948
  'hr.cap_legal_entities_desc': 'عدة شركات موظِّفة، لمجموعة تعمل عبر الحدود',
1947
1949
  'hr.cap_offices': 'المكاتب',
1948
1950
  'hr.cap_offices_desc': 'أكثر من مكان عمل، لكلٍّ منه بلده ومنطقته الزمنية وعطلاته',
1951
+ 'hr.cap_payroll_export': 'تصدير كشوف الرواتب',
1952
+ 'hr.cap_payroll_export_desc': 'تسليم فترة مُقفلة إلى مزوّد كشوف الرواتب بصيغة CSV، لكل كيان قانوني',
1949
1953
  'hr.cap_periods': 'فترات الرواتب',
1950
1954
  'hr.cap_periods_desc': 'إغلاق الشهر حتى لا يتغيّر كشف رواتب مُعتمد بعد اعتماده',
1951
1955
  'hr.capabilities_desc':
@@ -3431,6 +3435,9 @@ export const de: Record<string, Message> = {
3431
3435
  'hr.cap_offices': 'Standorte',
3432
3436
  'hr.cap_offices_desc':
3433
3437
  'Mehr als ein Arbeitsort, jeder mit eigenem Land, eigener Zeitzone und eigenen Feiertagen',
3438
+ 'hr.cap_payroll_export': 'Lohnexport',
3439
+ 'hr.cap_payroll_export_desc':
3440
+ 'Einen abgeschlossenen Zeitraum je Rechtsträger als CSV an einen Lohndienstleister übergeben',
3434
3441
  'hr.cap_periods': 'Abrechnungszeiträume',
3435
3442
  'hr.cap_periods_desc':
3436
3443
  'Einen Monat schließen, damit eine eingereichte Abrechnung sich nicht nachträglich verschiebt',
@@ -4835,6 +4842,9 @@ export const fa: Record<string, Message> = {
4835
4842
  'hr.cap_legal_entities_desc': 'چند شرکت کارفرما، برای گروهی که در چند کشور فعالیت می‌کند',
4836
4843
  'hr.cap_offices': 'دفاتر',
4837
4844
  'hr.cap_offices_desc': 'بیش از یک محل کار، هرکدام با کشور، منطقهٔ زمانی و تعطیلات خودش',
4845
+ 'hr.cap_payroll_export': 'خروجی حقوق و دستمزد',
4846
+ 'hr.cap_payroll_export_desc':
4847
+ 'تحویل یک دورهٔ بسته‌شده به ارائه‌دهندهٔ حقوق و دستمزد به‌صورت CSV، به تفکیک شخصیت حقوقی',
4838
4848
  'hr.cap_periods': 'دوره‌های حقوق و دستمزد',
4839
4849
  'hr.cap_periods_desc': 'بستن یک ماه تا حقوق ثبت‌شده دیگر تغییر نکند',
4840
4850
  'hr.capabilities_desc':
@@ -6207,6 +6217,9 @@ export const tr: Record<string, Message> = {
6207
6217
  'hr.cap_legal_entities_desc': 'Sınır ötesinde faaliyet gösteren bir grup için birden fazla işveren şirket',
6208
6218
  'hr.cap_offices': 'Ofisler',
6209
6219
  'hr.cap_offices_desc': 'Birden fazla çalışma yeri; her biri kendi ülkesi, saat dilimi ve tatilleriyle',
6220
+ 'hr.cap_payroll_export': 'Bordro dışa aktarma',
6221
+ 'hr.cap_payroll_export_desc':
6222
+ 'Kapanmış bir dönemi, tüzel kişilik bazında CSV olarak bordro sağlayıcısına aktarın',
6210
6223
  'hr.cap_periods': 'Bordro dönemleri',
6211
6224
  'hr.cap_periods_desc': 'Bir ayı kapatın; böylece verilmiş bordro sonradan kaymaz',
6212
6225
  'hr.capabilities_desc':
@@ -122,6 +122,18 @@ export const hrCapabilities = defineCapabilities([
122
122
  defaultEnabled: false,
123
123
  level: 1,
124
124
  },
125
+ {
126
+ id: 'rosters',
127
+ label: 'Shift rosters',
128
+ description: 'Rotating shifts on a calendar, and who covers which office-day',
129
+ // Depends on attendance rather than on core: a roster is what the clock and the day sheet are
130
+ // judged against, and rostering a workspace that never clocks anybody in is a planning grid
131
+ // nothing reads. Off by default and level 3 — most companies work a week that repeats, and for
132
+ // them a rotation editor is a screen full of settings that change nothing.
133
+ dependsOn: ['attendance'],
134
+ defaultEnabled: false,
135
+ level: 3,
136
+ },
125
137
  {
126
138
  id: 'documents',
127
139
  label: 'Employee documents',
@@ -130,6 +142,21 @@ export const hrCapabilities = defineCapabilities([
130
142
  defaultEnabled: false,
131
143
  level: 2,
132
144
  },
145
+ {
146
+ id: 'payroll_export',
147
+ label: 'Payroll export',
148
+ description: 'Hand a closed period to a payroll provider as CSV, per legal entity',
149
+ // Everything it reads: the day sheet, the periods that say the numbers have stopped moving, and
150
+ // the employment facts under `core`.
151
+ dependsOn: ['core', 'periods', 'attendance'],
152
+ // Off by default, and its own switch rather than riding on the two above — which is the whole
153
+ // argument for it existing. A company can perfectly well clock people in and close its months
154
+ // and still not want every employee's pay basis leaving the building as a file. The permission
155
+ // decides *who* may export; this decides whether the workspace does that at all, and the two
156
+ // answer different questions.
157
+ defaultEnabled: false,
158
+ level: 3,
159
+ },
133
160
  ])
134
161
 
135
162
  export type HrCapabilityId = (typeof hrCapabilities)[number]['id']
@@ -189,6 +216,7 @@ export const hrCapabilityProcedures: Record<string, readonly string[]> = {
189
216
  'calendars.workingDays',
190
217
  ],
191
218
  documents: ['documents.list', 'documents.attach', 'documents.remove'],
219
+ payroll_export: ['payroll.export.v1', 'payroll.export.preview'],
192
220
  leave: [
193
221
  'leave.types.list',
194
222
  'leave.types.create',
@@ -232,6 +260,23 @@ export const hrCapabilityProcedures: Record<string, readonly string[]> = {
232
260
  'reports.overtime',
233
261
  'reports.absence',
234
262
  ],
263
+ rosters: [
264
+ 'rosters.shifts.list',
265
+ 'rosters.shifts.create',
266
+ 'rosters.shifts.update',
267
+ 'rosters.shifts.archive',
268
+ 'rosters.patterns.list',
269
+ 'rosters.patterns.create',
270
+ 'rosters.patterns.update',
271
+ 'rosters.patterns.archive',
272
+ 'rosters.assignments',
273
+ 'rosters.assign',
274
+ 'rosters.unassign',
275
+ 'rosters.days',
276
+ 'rosters.set',
277
+ 'rosters.clear',
278
+ 'rosters.coverage',
279
+ ],
235
280
  leave_accrual: [
236
281
  'policies.list',
237
282
  'policies.get',
@@ -0,0 +1,354 @@
1
+ import { Timestamp } from '@kernhq/contracts'
2
+ import { z } from 'zod'
3
+ import { LeaveUnit } from './leave.js'
4
+ import { IsoDate } from './models.js'
5
+ import { ReportFinality, ReportScope } from './reports.js'
6
+
7
+ /**
8
+ * The payroll handover, and the four rules that make it safe to hand over.
9
+ *
10
+ * Kern does not compute pay. This file carries identity, the period, the employment facts that let a
11
+ * provider pick a rate, and quantities — minutes and days. There is no gross, no net, no hourly rate,
12
+ * no deduction and no currency amount anywhere in it; the moment a column reads as money, Kern is a
13
+ * payroll system and owes the accuracy of one. `OvertimeConfig.rate` says the same thing one file
14
+ * over: a multiplier is a fact about a policy, and multiplying anything by it is somebody else's job.
15
+ *
16
+ * **1. Per legal entity, keyed by (entity, period, person).** A person who transfers mid-period
17
+ * produces two rows, one in each entity's file, each carrying only that entity's days. Two entities
18
+ * in one workspace are two filings, in two currencies, to two authorities, on two closing days —
19
+ * `periods.legal_entity_id` exists for exactly that reason and `PolicyService.isLocked` already
20
+ * answers per entity. So `legalEntityId` is a **required** input rather than an optional slice: there
21
+ * is no "export everything", because that is an invitation to send one provider another entity's
22
+ * people.
23
+ *
24
+ * **2. Two files, not one.** `hours.csv` has a fixed column set. `leave.csv` is long-form — one row
25
+ * per person per leave type — because leave types are workspace data (`leave_types` is keyed on
26
+ * `(workspace_id, key)`), so a wide file with a column per type would have a column set that depends
27
+ * on the customer's own rows, and a column set that depends on customer data cannot be frozen.
28
+ *
29
+ * **3. Frozen, and the version travels in four places.** See {@link PAYROLL_EXPORT_CONTRACT}.
30
+ *
31
+ * **4. Refuse rather than guess.** An open period, an entity with nobody in it, or a person with no
32
+ * employment row covering their days is a refusal with a sentence, never a row of zeros a payroll
33
+ * clerk will pay from. The one escape hatch is `draft`, and a draft stamps itself — in the manifest,
34
+ * in the filename, and in every row's `open_days`.
35
+ */
36
+
37
+ /**
38
+ * The contract identity, and **not** the package version.
39
+ *
40
+ * `@kernhq/module-hr` bumps on every patch and every image in an instance carries one
41
+ * `KERN_VERSION`; the CSV shape has to move on its own axis, so this is a hardcoded literal rather
42
+ * than `packageVersion(import.meta.url)`. `kernVersion` sits in the manifest as provenance and is
43
+ * never the contract identity.
44
+ *
45
+ * It travels in four places, each doing a different job:
46
+ *
47
+ * 1. **The procedure and its route** — `payroll.export.v1`, `GET /payroll/export/v1`. A new shape is
48
+ * a new procedure, never a parameter on this one: freezing a branch inside a function three people
49
+ * will edit has never worked, and separate procedures are what make the freeze structural.
50
+ * 2. **The filename** — `kern-payroll-v1_<entity>_2026-06_hours.csv`. The only part that survives
51
+ * being emailed to a bureau and opened by somebody who never saw the API.
52
+ * 3. **The manifest** — `contract: 'kern-payroll-v1'` beside `generatedAt`, `kernVersion` and the
53
+ * report header triple.
54
+ * 4. **Every row**, as the first column. A manifest can be separated from its CSVs and a filename can
55
+ * be changed on the way to a payroll system; a file that has lost both must still be able to say
56
+ * what shape it is. This is a column in the frozen set, **not** a banner row above the header —
57
+ * a version line above the column names breaks every importer that assumes row 1 is the header,
58
+ * which is most of them and all of the spreadsheet ones.
59
+ *
60
+ * What "frozen" forbids, once v1 has shipped: no new column, not even appended at the end; no removed
61
+ * or renamed column; no reordering; no changed emptiness semantics (`beyond_cap_minutes` empty means
62
+ * "no ceiling was in force" and must never start meaning zero); no changed units, so minutes stay
63
+ * minutes and `dayLengthMinutes` stays 480 even if this module later grows a per-workspace working
64
+ * day; and no changed encoding, delimiter, line ending or quoting. A later column is
65
+ * `payroll.export.v2` — a new procedure, a new filename prefix, a new manifest `contract` — shipping
66
+ * alongside v1 with v1 untouched. That is expensive on purpose: the expense is what stops the column
67
+ * set drifting, and a contract nobody pays to change is not frozen.
68
+ */
69
+ export const PAYROLL_EXPORT_CONTRACT = 'kern-payroll-v1'
70
+
71
+ /**
72
+ * `hours.csv`, in order. **This array is the file format.**
73
+ *
74
+ * Every column exists in the schema today. The quantities come from `attendance_days` and never from
75
+ * `punches`: punches are append-only and a voided punch survives beside its correction, so summing
76
+ * them double-counts every fix ever made. The day sheet is the projection that has already applied
77
+ * the schedule, the calendar and the rounding.
78
+ *
79
+ * Three of these carry a decision rather than a number:
80
+ *
81
+ * - `beyond_cap_minutes` is **empty, never `0`**, where no statutory ceiling was in force. Zero means
82
+ * a ceiling applied and nothing exceeded it. A provider reading 0 for empty is the one place this
83
+ * export can cause a wrong payment, which is why `capped_days` and `uncapped_days` sit beside it.
84
+ * - `scheduled_worked_minutes` excludes work on unrostered days, because a numerator that includes
85
+ * them over a denominator that excludes them is how a team that turned up exactly as asked reads
86
+ * 121%.
87
+ * - `employment_changed_in_period` is true when more than one employment row overlaps the period.
88
+ * Without it the export hands over the end-state FTE for somebody who went 1.0 → 0.6 on the 15th,
89
+ * and the provider pays the whole month at one of them.
90
+ */
91
+ export const PAYROLL_HOURS_COLUMNS = [
92
+ 'contract',
93
+ 'legal_entity_id',
94
+ 'legal_entity_name',
95
+ 'period_start',
96
+ 'period_end',
97
+ 'person_id',
98
+ 'employee_no',
99
+ 'display_name',
100
+ 'employment_type',
101
+ 'fte',
102
+ 'contract_hours_week',
103
+ 'cost_center_code',
104
+ 'position_title',
105
+ 'hired_on',
106
+ 'terminated_on',
107
+ 'employment_changed_in_period',
108
+ 'day_sheets',
109
+ 'scheduled_minutes',
110
+ 'worked_minutes',
111
+ 'scheduled_worked_minutes',
112
+ 'break_minutes',
113
+ 'overtime_minutes',
114
+ 'late_minutes',
115
+ 'early_leave_minutes',
116
+ 'beyond_cap_minutes',
117
+ 'capped_days',
118
+ 'uncapped_days',
119
+ 'locked_days',
120
+ 'open_days',
121
+ 'paid_leave_days',
122
+ 'unpaid_leave_days',
123
+ ] as const
124
+
125
+ /**
126
+ * `leave.csv`, in order. One row per (person, entity, period, leave type).
127
+ *
128
+ * Built from `leave_request_days` filtered `counted and status = 'approved'`, joined out to
129
+ * `leave_requests` → `leave_types`. **Not** `leave_ledger`: the ledger is the balance and carries
130
+ * `grant`, `accrual`, `carry_in` and `expiry`, which are movements rather than leave anybody took in
131
+ * this period. **Not** `leave_requests.minutes` summed per day either — that counts a five-day
132
+ * request five times, an off-by-a-factor this module has already been bitten by once.
133
+ *
134
+ * `days` sums `fraction`, which is exact and needs no day length. `dayLengthMinutes` is published in
135
+ * the manifest for anyone who wants to convert; this file does not convert for them.
136
+ */
137
+ export const PAYROLL_LEAVE_COLUMNS = [
138
+ 'contract',
139
+ 'legal_entity_id',
140
+ 'legal_entity_name',
141
+ 'period_start',
142
+ 'period_end',
143
+ 'person_id',
144
+ 'employee_no',
145
+ 'leave_type_key',
146
+ 'leave_type_name',
147
+ 'paid',
148
+ 'unit',
149
+ 'days',
150
+ 'requests',
151
+ ] as const
152
+
153
+ export const PayrollHoursRow = z.object({
154
+ personId: z.uuid(),
155
+ /**
156
+ * Unique per **workspace**, not per entity (`hr_people_ws_empno_uq`), and nullable.
157
+ *
158
+ * Exported, and deliberately not the key: a group whose Turkish and Dutch providers each want their
159
+ * own numbering has nowhere to put the second number today, and `HrSettings.employeeNumberPrefix`
160
+ * is one workspace-wide prefix. A per-entity number is a real schema change and it is not v1's job
161
+ * — but the file must not pretend the number it carries is the provider's.
162
+ */
163
+ employeeNo: z.string().nullable(),
164
+ /** Exactly as stored: an erased person keeps their row and carries the erasure token. */
165
+ displayName: z.string(),
166
+ employmentType: z.string(),
167
+ fte: z.number(),
168
+ contractHoursWeek: z.number().nullable(),
169
+ costCenterCode: z.string().nullable(),
170
+ positionTitle: z.string().nullable(),
171
+ /** A joiner or leaver mid-period is the case a provider prorates. */
172
+ hiredOn: IsoDate.nullable(),
173
+ terminatedOn: IsoDate.nullable(),
174
+ /** True when more than one employment row overlapped this person's days in this entity. */
175
+ employmentChangedInPeriod: z.boolean(),
176
+ /** The denominator. Publish it or no total means anything. */
177
+ daySheets: z.number().int(),
178
+ scheduledMinutes: z.number().int(),
179
+ workedMinutes: z.number().int(),
180
+ scheduledWorkedMinutes: z.number().int(),
181
+ breakMinutes: z.number().int(),
182
+ overtimeMinutes: z.number().int(),
183
+ lateMinutes: z.number().int(),
184
+ earlyLeaveMinutes: z.number().int(),
185
+ /** Null where no ceiling was in force — an **empty CSV field**, never zero. */
186
+ beyondCapMinutes: z.number().int().nullable(),
187
+ cappedDays: z.number().int(),
188
+ uncappedDays: z.number().int(),
189
+ /** A locked period can still hold an unlocked day, so both travel per row. */
190
+ lockedDays: z.number().int(),
191
+ openDays: z.number().int(),
192
+ paidLeaveDays: z.number(),
193
+ unpaidLeaveDays: z.number(),
194
+ })
195
+ export type PayrollHoursRow = z.infer<typeof PayrollHoursRow>
196
+
197
+ export const PayrollLeaveRow = z.object({
198
+ personId: z.uuid(),
199
+ employeeNo: z.string().nullable(),
200
+ leaveTypeKey: z.string(),
201
+ leaveTypeName: z.string(),
202
+ paid: z.boolean(),
203
+ unit: LeaveUnit,
204
+ /** Days, summed from `fraction`. Never minutes: `MINUTES_PER_DAY` is a hardcoded eight hours. */
205
+ days: z.number(),
206
+ requests: z.number().int(),
207
+ })
208
+ export type PayrollLeaveRow = z.infer<typeof PayrollLeaveRow>
209
+
210
+ /** The headline figures over the whole population, so a screen shows a total before a file exists. */
211
+ export const PayrollExportTotals = z.object({
212
+ people: z.number().int(),
213
+ daySheets: z.number().int(),
214
+ scheduledMinutes: z.number().int(),
215
+ workedMinutes: z.number().int(),
216
+ scheduledWorkedMinutes: z.number().int(),
217
+ breakMinutes: z.number().int(),
218
+ overtimeMinutes: z.number().int(),
219
+ lateMinutes: z.number().int(),
220
+ earlyLeaveMinutes: z.number().int(),
221
+ beyondCapMinutes: z.number().int().nullable(),
222
+ cappedDays: z.number().int(),
223
+ uncappedDays: z.number().int(),
224
+ lockedDays: z.number().int(),
225
+ openDays: z.number().int(),
226
+ paidLeaveDays: z.number(),
227
+ unpaidLeaveDays: z.number(),
228
+ })
229
+ export type PayrollExportTotals = z.infer<typeof PayrollExportTotals>
230
+
231
+ /**
232
+ * Why this export will not be written.
233
+ *
234
+ * `payroll.export.preview` returns these so a screen can show them **before** anybody downloads
235
+ * anything; `payroll.export.v1` throws the first of them. `hr.period.not_locked` mirrors the spelling
236
+ * of `hr.period.locked`, which `PolicyService.assertOpen` throws pointed the other way.
237
+ */
238
+ export const PayrollExportRefusalCode = z.enum([
239
+ /** The period is open, and `draft` was not asked for. Tonight's `reconcile-days` may move it. */
240
+ 'hr.period.not_locked',
241
+ /** Nobody was employed by this entity on any day of the period. */
242
+ 'hr.payroll.empty',
243
+ /** Somebody in the population has no employment row covering their days here. */
244
+ 'hr.payroll.no_employment',
245
+ ])
246
+ export type PayrollExportRefusalCode = z.infer<typeof PayrollExportRefusalCode>
247
+
248
+ export const PayrollExportRefusal = z.object({
249
+ code: PayrollExportRefusalCode,
250
+ /** A sentence naming the fix, not a code a reader has to look up. */
251
+ message: z.string(),
252
+ /** Whose rows caused it, where that is a fact about people. Empty otherwise. */
253
+ personIds: z.array(z.uuid()),
254
+ })
255
+ export type PayrollExportRefusal = z.infer<typeof PayrollExportRefusal>
256
+
257
+ /**
258
+ * How the bytes are written, restated in the manifest so a reader never has to infer it.
259
+ *
260
+ * UTF-8 **with a byte order mark**, because Excel on Windows mangles Turkish and Persian names
261
+ * without one and this module ships country packs for both. Comma, CRLF, RFC 4180 quoting, ISO dates,
262
+ * `.` decimal separator with two places on `fte` and on leave-day fractions. Every one of these is
263
+ * frozen for as long as v1 is published.
264
+ */
265
+ export const PayrollExportFormat = z.object({
266
+ encoding: z.literal('utf-8'),
267
+ byteOrderMark: z.literal(true),
268
+ delimiter: z.literal(','),
269
+ lineEnding: z.literal('crlf'),
270
+ quoting: z.literal('rfc4180'),
271
+ decimalSeparator: z.literal('.'),
272
+ decimalPlaces: z.literal(2),
273
+ dateFormat: z.literal('iso-8601'),
274
+ })
275
+ export type PayrollExportFormat = z.infer<typeof PayrollExportFormat>
276
+
277
+ export const PayrollExportManifest = z.object({
278
+ contract: z.literal(PAYROLL_EXPORT_CONTRACT),
279
+ generatedAt: Timestamp,
280
+ /** Provenance — the platform version that wrote the file. Never the contract identity. */
281
+ kernVersion: z.string(),
282
+ /**
283
+ * `draft` when the caller asked for an open period, `final` otherwise.
284
+ *
285
+ * Not a warning in a toast: the toast does not travel with the CSV, and the CSV is what reaches the
286
+ * provider. So the filename says `DRAFT` too, and every row carries a non-zero `open_days`.
287
+ */
288
+ finality: z.enum(['final', 'draft']),
289
+ draft: z.boolean(),
290
+ legalEntityId: z.uuid(),
291
+ legalEntityName: z.string(),
292
+ /** The fields a filing is made under, so the file states which authority it belongs to. */
293
+ country: z.string(),
294
+ currency: z.string().nullable(),
295
+ periodId: z.uuid(),
296
+ periodStart: IsoDate,
297
+ periodEnd: IsoDate,
298
+ periodStatus: z.enum(['open', 'locked']),
299
+ /** Everybody the entity employed over the period — the denominator, and never omitted. */
300
+ population: z.number().int(),
301
+ /** How many of them have a day sheet or an approved leave day behind the figures. */
302
+ counted: z.number().int(),
303
+ /** Which grants produced this population. Two managers must not read one title over two sets. */
304
+ scope: ReportScope,
305
+ /** Locked against open day sheets. A locked period can still contain an unlocked day. */
306
+ attendance: ReportFinality,
307
+ /** 480. Published so a reader converting days to minutes uses the module's day, not their own. */
308
+ dayLengthMinutes: z.number().int(),
309
+ format: PayrollExportFormat,
310
+ files: z.array(z.object({ name: z.string(), columns: z.array(z.string()), rows: z.number().int() })),
311
+ })
312
+ export type PayrollExportManifest = z.infer<typeof PayrollExportManifest>
313
+
314
+ export const PayrollExportFile = z.object({
315
+ name: z.string(),
316
+ contentType: z.string(),
317
+ /** The whole file as text. The CSVs begin with a byte order mark and end every line with CRLF. */
318
+ content: z.string(),
319
+ })
320
+ export type PayrollExportFile = z.infer<typeof PayrollExportFile>
321
+
322
+ /**
323
+ * What `payroll.export.v1` hands back: the manifest, and the three files beside each other.
324
+ *
325
+ * Synchronous and streamed into the response rather than delivered as a job, and that is a checked
326
+ * constraint rather than a preference. Core exposes exactly one file procedure over the broker —
327
+ * `files.get` — so a module cannot mint a `FileObject`; `createUpload` requires a user principal and
328
+ * a background job has none. Writing bytes straight into `kernel.storage` would produce an object
329
+ * invisible to `core.files.*`, absent from the workspace file list, uncounted by the `storageBytes`
330
+ * entitlement and deleted by nothing — orphans by design. Async delivery becomes possible the day
331
+ * core grows a procedure that mints a file for a service principal, and that is a change to core.
332
+ */
333
+ export const PayrollExport = z.object({
334
+ manifest: PayrollExportManifest,
335
+ /** `hours.csv`, `leave.csv`, `manifest.json`. Three, always, for as long as v1 exists. */
336
+ files: z.array(PayrollExportFile).length(3),
337
+ })
338
+ export type PayrollExport = z.infer<typeof PayrollExport>
339
+
340
+ /**
341
+ * The same rows as JSON, with no file and no refusal thrown.
342
+ *
343
+ * So a screen can show the totals and the reasons it would be refused before anybody downloads
344
+ * anything. `exportable` is `refusals.length === 0`.
345
+ */
346
+ export const PayrollExportPreview = z.object({
347
+ manifest: PayrollExportManifest,
348
+ refusals: z.array(PayrollExportRefusal),
349
+ exportable: z.boolean(),
350
+ totals: PayrollExportTotals,
351
+ hours: z.array(PayrollHoursRow),
352
+ leave: z.array(PayrollLeaveRow),
353
+ })
354
+ export type PayrollExportPreview = z.infer<typeof PayrollExportPreview>
@@ -10,11 +10,13 @@ export * from './approvals.js'
10
10
  export * from './attendance.js'
11
11
  export * from './capabilities.js'
12
12
  export * from './events.js'
13
+ export * from './exports.js'
13
14
  export * from './leave.js'
14
15
  export * from './models.js'
15
16
  export * from './permissions.js'
16
17
  export * from './policies.js'
17
18
  export * from './privacy.js'
18
19
  export * from './reports.js'
20
+ export * from './rosters.js'
19
21
  export * from './router.js'
20
22
  export * from './settings.js'
@@ -252,8 +252,11 @@ export const hrPermissions = definePermissions([
252
252
  },
253
253
  {
254
254
  key: 'hr.attendance.manage',
255
- label: 'Correct punches, schedules and day sheets',
256
- description: 'Voids punches and recomputes days. Every change leaves the original visible.',
255
+ label: 'Correct punches and set schedules, rosters and day sheets',
256
+ description:
257
+ 'Voids punches and recomputes days. Every change leaves the original visible. Also edits ' +
258
+ 'shifts and rotations and puts people on them, which decides what a shift worker is ' +
259
+ 'expected to turn up for.',
257
260
  scope: 'workspace',
258
261
  defaultRoles: ['owner', 'admin'],
259
262
  dangerous: true,
@@ -262,6 +265,14 @@ export const hrPermissions = definePermissions([
262
265
  // nothing asks a question these keys could answer — a role checkbox that gates nothing teaches an
263
266
  // administrator the same lesson a dead capability switch does. They come back with the approval
264
267
  // flow that needs them.
268
+ //
269
+ // No `hr.roster.*` either, for the same reason and after weighing it. Rostering is `manage`:
270
+ // deciding what somebody was meant to work is the same authority as correcting what they did, and
271
+ // both feed the same day sheet. Reading a roster is `hr.attendance.view` for your own and
272
+ // `hr.attendance.view_team` for anybody else's — the coverage grid asks for the second, which is
273
+ // already what `attendance.days.list` costs to read a whole office. Four new keys would gate
274
+ // nothing the three existing ones do not already gate, which is how `hr.overtime.*` came to be
275
+ // deleted. They arrive if a workspace ever needs a planner who may roster and may not correct.
265
276
 
266
277
  // ---------------------------------------------------------------- reports
267
278
  {
@@ -285,9 +296,39 @@ export const hrPermissions = definePermissions([
285
296
  // Why a key of its own at all, when the two above would do: a reports surface is the one place a
286
297
  // whole population's figures are put in front of somebody in a form that goes into a payroll or a
287
298
  // performance conversation, and a workspace has to be able to grant a manager their team's day
288
- // sheets without granting them that. There is deliberately **no** `hr.report.export`: nothing in
289
- // this module writes a file, and a key gating a button nobody built is the thing the removed
290
- // `hr.overtime.*` block below is a note about.
299
+ // sheets without granting them that. There is still no `hr.report.export` the reports write no
300
+ // file and the one thing in this module that does have its own key below.
301
+
302
+ // ---------------------------------------------------------------- payroll export
303
+ {
304
+ key: 'hr.payroll.export',
305
+ label: 'Export a payroll file',
306
+ description:
307
+ "Writes every employee's period, employment basis and hours out of Kern as CSV, for one " +
308
+ 'legal entity. The file leaves the building. Grant to whoever files payroll, not to a role.',
309
+ scope: 'workspace',
310
+ // Nobody by default, like `hr.person.view_sensitive` and `hr.privacy.manage`. An owner passes
311
+ // every check regardless; every other holder had to be given it deliberately.
312
+ defaultRoles: [],
313
+ dangerous: true,
314
+ },
315
+ // This is the key the note above says did not exist yet, and it exists now because something
316
+ // finally writes a file: `payroll.export.v1` and `payroll.export.preview` both ship gated on it in
317
+ // this same change, which is the rule — a capability, a permission key and an entitlement key are
318
+ // all lies until something enforces them.
319
+ //
320
+ // It is not `hr.report.export`, and the difference is not cosmetic. A report is a screen somebody
321
+ // reads inside Kern; this is a file that leaves it, addressed to an organisation that will pay
322
+ // people from it. The two audiences are different and so is the blast radius, so a workspace has to
323
+ // be able to grant every report without granting this.
324
+ //
325
+ // Like the reports, it is a **second** check rather than a replacement: both procedures also ask
326
+ // for `hr.attendance.view_team` (the hours file) and `hr.leave.view_team` (the leave file), because
327
+ // an export must not answer what the row-level procedure would refuse.
328
+ //
329
+ // It reads no sensitive field, so it writes no `sensitive_access_log` row. A later version that
330
+ // adds `iban` becomes a bulk sensitive read and owes one row per person with `via: 'export'` — the
331
+ // enum member already exists — and its own key on top of this one.
291
332
 
292
333
  // ---------------------------------------------------------------- policies and periods
293
334
  {
@@ -395,6 +436,7 @@ export const HR_PERMISSIONS = {
395
436
  attendanceViewTeam: 'hr.attendance.view_team',
396
437
  attendanceManage: 'hr.attendance.manage',
397
438
  reportView: 'hr.report.view',
439
+ payrollExport: 'hr.payroll.export',
398
440
  policyView: 'hr.policy.view',
399
441
  policyManage: 'hr.policy.manage',
400
442
  periodManage: 'hr.period.manage',