Chapter 1 · Sessions 1–2
What the old tools hold, and the tables that replace them
First you find out what your HR records and time-and-attendance tools hold and cost, from their own reports and invoices. Then Claude Code adds the nineteen hr_ tables to your platform, with history kept by effective date, punches that can never be edited, and pay visible to HR only, and you try them on the development project before anything real goes near them.
30 min4 stepsAbout 7 hours hands-on across six sessions
By the end of this chapter you can
- Inventory the HR, time and recruiting tools, the leave policies and the overtime rules, from their own reports, policies and invoices.
- Have Claude Code check the spine and write the nineteen hr_ tables with the tests for the three rules that matter most.
- Seed a fixed made-up workforce and try it on the development project yourself.
What the module replaces, and what stays with the payroll provider
A plant usually pays for three things here: an HR records system, a time-and-attendance tool (the clocks), and a recruiting tool. The module library names ADP Workforce Now, UKG Pro, BambooHR, Rippling, Gusto, Paychex, Paycom, Paylocity and Workday. The module rebuilds the records, the clock, leave, scheduling, hiring and the export to payroll, in tables whose names start with hr_.
| Built in this module | Stays elsewhere |
|---|---|
| Employment, positions, job and pay history by effective date | Payroll calculation, tax withholding and filing: the payroll provider |
| Time clock (kiosk, phone, web, badge), punch corrections, overtime rules, timesheet approval | Benefits carrier connections |
| Time-off policies, accruals, requests and balances | Training records and qualifications: module M07 (the scheduling check reads them) |
| Shift scheduling with a qualification check; requisition to hire with onboarding tasks | Performance review cycles: hr_review is created and left empty |
| An export of approved hours to the payroll provider, reconciled to the timesheets | Social Security, bank and card numbers: never stored anywhere in the module |
The specification names three mistakes [1][2]: overwriting job history instead of adding a dated row; editing a punch so the original time is lost, when the Fair Labor Standards Act requires accurate records of hours worked [1]; and calculating payroll tax in-house. Every step below is built so none of them can happen.
Session 1: Inventory the old tools, policies and overtime rules
40 minutesWhy
Time and leave rules live in people's heads as often as in the tool. If the new module is built from guesses, the first paycheque it feeds will be wrong, and wrong pay is the fastest way to lose the floor's trust. Reading the counts, policies and costs from the tools' own reports and invoices gives you a list the module is checked against in Session 6 and a saving you can prove.
Do this
Have open: a recent payroll register from the provider (headcount and hours only), each tool's user list and export page, your written leave policies, and the latest invoices. You record counts and rules, never a person's pay, Social Security number or leave reason.
cd ~/code/acme-platform && git switch main && git pull && claudeOn a new branch hr/inventory, write docs/hr-inventory.md for me to fill in by hand. Do not invent any number, price, rule or date: leave every value cell as "—".
Sections:
1. Tools: tool, what it does (HR records, time clock, leave, scheduling, recruiting, payroll), owner (a job, not a name), users, bill per year as printed on the invoice, renewal date, notice period, what it exports, how long we can export after cancelling.
2. The workforce, from the payroll register: headcount by status, total hours, overtime hours and time-off hours for the last full pay period. Counts only.
3. Leave policies: one row each with name, accrual method (per pay period, per hour worked, annual grant, none), rate, waiting period, cap, carryover, and which leave we treat as FMLA leave and who decides.
4. Overtime: the workweek's start day and hour; the federal weekly rule (over 40 hours, 1.5x); our state's daily, double-time and seventh-day rules with multipliers, or "none beyond federal". Leave a line for the payroll person's initials.
5. Whether the clock rounds punches, and who set that rule.
6. Where Form I-9 files are kept today, and who can open them.
7. Workarounds: one numbered line per thing people do around the tools (job, not name).
At the top, write: "Counts and rules only. No pay rates, identity numbers, bank details or leave reasons." Open a pull request titled "HR inventory" and show me the link.Fill in the cells on GitHub from the reports and policies. Ask the payroll person to read the overtime section and add their initials.
You will see recreated screen
- The federal rule is law; your state's rule and your workweek start are facts only you can supply.
Check it worked
docs/hr-inventory.md is merged with every tool, its bill and renewal date from the invoice, the payroll register's counts, every leave policy, your state's overtime rule initialled by the payroll person, and the workarounds.
Fastest path
The payroll provider's register already has headcount and hours by type for the period: copy the four totals from it rather than adding up timesheets.
If it goes wrong
Nobody is sure whether the state has a daily overtime rule
Do not guess and do not ask Claude Code to decide. Write "unknown: ask payroll or counsel" and find out before Session 4: the overtime engine is built from this line. The Department of Labor's state pages and your state's labour department say which rules apply.
The leave policy document and what supervisors actually do differ
Write both, and the difference under workarounds. Session 4 tests the accrual against the written policy; a practice that differs is a decision for HR, not for the code.
Claude Code filled in a state rule "typical for manufacturing"
Say: Remove every rule I did not give you. An invented overtime rule pays people wrongly.
The tables, and the three rules the database keeps
The module has nineteen tables, from the specification. Every table also has the spine's standard columns. Three rules matter more than any column, and each becomes a test in Step 2. The made-up workforce for every later hand count is a seed file Supabase runs after the migrations, in CI and on the development project [3].
| Rule | What it means | How the database keeps it |
|---|---|---|
| Effective dating | A job or pay change is a new row with a date; the old job row is closed, never overwritten | hr_job_assignment: effective_from, effective_to (inclusive); hr_compensation: insert only, the rate in force is the latest effective_from not after the date |
| Punches are never edited | A correction is a new punch with source manual_edit, the corrected time, the original time, who and why | A trigger refuses every update and delete on hr_time_punch |
| Restricted data | Pay, candidates and offers: HR only. The FMLA flag: HR and the employee who asked. Form I-9 scans: HR only | Row-level security from the matrix (Session 3); no column exists for Social Security, bank or card numbers |
| Group | Tables |
|---|---|
| Employment | hr_employment (employee_no unique; employment_type; flsa_status exempt or non_exempt; hire_date; status pre_hire, active, on_leave, terminated), hr_position, hr_job_assignment, hr_compensation (pay_basis hourly or salary; rate; reason) |
| Time off | hr_time_off_policy (accrual_method per_pay_period, per_hour_worked, annual_grant, none; accrual_rate; max_balance_hours; carryover_max_hours; waiting_period_days), hr_time_off_balance (balance_hours, as_of), hr_time_off_request (status pending, approved, denied, cancelled, taken; fmla_designated) |
| Time | hr_time_punch (punch_type in, out, break_start, break_end, job_change; source kiosk, mobile, web, badge, manual_edit; original_punched_at; edited_by; edit_reason), hr_overtime_rule, hr_timesheet (regular, ot, dt, pto hours; exceptions; status open, submitted, approved, exported, reopened), hr_payroll_batch |
| Scheduling | hr_schedule_shift (required_skill_ref, a soft link to M07's trn_skill; status draft, published, open, swapped, cancelled) |
| Hiring and onboarding | hr_requisition, hr_candidate (consent_at, retain_until), hr_application (stage applied … hired), hr_interview, hr_offer (rate; status draft … accepted), hr_onboarding_task |
| Performance | hr_review: created, left empty in this course |
Session 2: Check the spine, then write the nineteen tables and their tests
35 minutesWhy
The module needs the spine's people, sites and org units. If Claude Code cannot find them it invents a second people table, and the platform then has two answers to "who works here". Checking first and creating only what is missing keeps one truth. The tests arrive in the same pull request, so the three rules above are proved from the first day, before any screen could break them.
Do this
Read docs/SCHEMA-PLAN.md, docs/naming-standard.md, docs/hr-inventory.md and the migrations in supabase/migrations. Do not connect to any Supabase project.
On a new branch hr/tables:
1. The spine. The module needs core_person, core_site, core_reason_code, core_org_unit, core_job_role, core_cost_center, core_shift_definition, core_shift_instance, core_equipment, core_attachment, core_event_outbox, core_audit_log with core_audit_row(), core_current_tenant() and core_touch_row(). For each, tell me: exists under this name, exists under another name (for example sites, equipment, memberships), or missing. Never create a second copy of something that exists under another name: use it and write the mapping in the shared docs/spine-map.md, in its own section "M21 People (HR)" (never a separate spine-map file). Module tables carry site_id in place of the specification's tenant_id, so core_current_tenant() is not created; say so in the section. Create only what is missing, in its own migration (npx supabase migration new spine_for_hr), with row-level security on and no policies.
2. In the same section of docs/spine-map.md, list the nineteen tables from the "Data schema" section of spec/academy/module-library/modules/M21_hris.md if this repository has it (otherwise I will paste it), with the spine table each points at; no separate tables file. Mark the restricted data: all of hr_compensation, hr_offer.rate, hr_candidate, hr_time_off_request.fmla_designated, Form I-9 scans in core_attachment.
3. npx supabase migration new hr_tables: the nineteen tables with the standard columns (site_id not null references sites in place of tenant_id, index on it, core_touch_row() and core_audit_row() triggers); required means not null, allowed values are check constraints; required_skill_ref is a plain uuid with no foreign key; unique per site: employee_no, position_no, policy name, batch_no, req_no; and one hr_timesheet per employment and period_start. A trigger refuses every update and delete on hr_time_punch. No column anywhere for Social Security, bank or card numbers, and a check refusing a run of nine or more digits in ext and free-text columns. Row-level security on every table, no policies yet.
4. pgTAP tests in supabase/tests/hr.test.sql: bad employment_type, accrual_method and punch_type refused; a repeated policy name refused; updating or deleting a punch refused; a nine-digit number in ext refused; no hr_ column whose name contains ssn, social_security, bank or card.
Push, open a pull request titled "HR tables", wait for every check, and tell me the result and the spine findings in plain words. If a check fails, fix it and wait again before reporting.You will see recreated screen
- If a table already exists under another name, it is used. A second people table splits every person's history.
- The two rules the database will keep whatever any screen does.
Check it worked
Pull request HR tables is green, docs/spine-map.md says what was mapped and created, and the tests include a refused punch update and a refused nine-digit number.
Fastest path
If the repository does not have the specification, paste its "Data schema" section as your reply when Claude Code asks. One paste replaces a long run of questions about allowed values.
If it goes wrong
Claude Code adds an ssn or bank_account column "so payroll can use it later"
Say: Remove it. This module never stores Social Security, bank or card numbers; the payroll provider holds them. Add a test that fails if any such column appears.
CI fails with "relation core_org_unit does not exist" on a fresh database
The spine migration is missing or later than the module's. Say: Give spine_for_hr an earlier timestamp than hr_tables, rebuild from nothing and show the check green. We merged a change once that worked on one machine and failed everywhere else with "column does not exist".
It reports success but a check on GitHub is red
Say: The check is red. Run gh pr checks, read the failed log, fix it and wait for green before you report. Trust the check, never the summary.
Session 2: Seed a made-up workforce and try it on the development project
40 minutesWhy
Every later check in this module is a number you can work out on paper: 48 hours is 40 regular and 8 overtime. Those hand-worked weeks have fixed dates, so they are test fixtures that never change; the seed gives the development project a small made-up workforce with its dates shifted onto today, so the screens always show a current week. Trying the migration and seed on the development project, from your own terminal, shows you the tables before the deploy workflow applies the migration to the live project on merge, and keeps made-up people and pay out of production for good.
Do this
On the branch hr/tables, add supabase/seeds/hr.sql and list it under [db.seed] sql_paths in supabase/config.toml after the existing seed, so CI and the development project load it. Never append it to supabase/seed.sql. Check .github/workflows/deploy.yml never uses --include-seed and tell me.
The seed is marked SYNTHETIC and safe to run twice (fixed ids, inserted with on conflict do nothing). Its dates are worked out from current_date, so they are shifted onto today. Every name starts "SYNTHETIC · ", no real person, rate or number:
- 9 people with demo logins: 5 employees (3 on one crew whose manager is the seeded manager, 2 on another team; all non_exempt except one exempt), a supervisor, a manager, an HR manager and a payroll processor;
- for each employee: hr_employment, one hr_job_assignment, one hr_compensation row effective 90 days before today;
- three time-off policies (vacation, sick, personal) from docs/hr-inventory.md, with an opening balance row each, as_of the first day of this month;
- one hr_overtime_rule for federal (weekly 40, 1.5x) and one for our state from docs/hr-inventory.md (if none, only federal);
- punches for SYNTHETIC · Operator 01 for last week, Monday to Friday 08:00–16:00, dated from current_date.
Separately, as a test fixture and not seed rows: tests/fixtures/hr-punch-week.json, the hand-worked week with fixed dates (Monday to Friday 08:00–16:00, plus the Saturday of scenario e), which the Session 4 tests load.
Add a pgTAP test that counts these rows, and that running the seed twice leaves the same counts. Push, wait for the checks, and tell me.When it is green, you load it into the development project. The password is in the password manager as Supabase: acme-platform-dev database password.
cd ~/code/acme-platform && git fetch && git switch hr/tables && git pullnpx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase projects listnpx supabase db push --include-seedhttps://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
The development project's Table Editor: the hr_ tables with the made-up workforce.
Push the seed with the migrations only this first time. After that, to reload the made-up rows on the development project, you run npm run seed:dev yourself (Claude Code may not).
Owner two approves the pull request and you merge. The deploy workflow from Session 11 applies the migrations to the live project, without the seed.
You will see recreated screen
- The linked project is acme-platform-dev. If the dot is on acme-platform-prod, stop.
- Only this module's migrations. Anything else: answer n and ask why.
You will see recreated screen
| employee_no | person | flsa_status | status |
|---|---|---|---|
| E-0001 | SYNTHETIC · Operator 01 | non_exempt | active |
| E-0005 | SYNTHETIC · Planner 01 | exempt | active |
- Expected until Session 3: nothing is readable through the app yet.
Check it worked
The development project holds 9 made-up people, 5 employments, 3 policies, the overtime rules and last week's punches, every name starting SYNTHETIC; tests/fixtures/hr-punch-week.json is in the pull request; after merge the deploy workflow run is green and the live project has the hr_ tables with none of the made-up rows.
If it goes wrong
The dot is on the live project
Do not push. Link acme-platform-dev again and re-check. Made-up pay rows in production would sit beside real ones.
A later hand count does not match the seed
Fix the seed, not the check. Reviews of five Academy modules found later steps written against counts the seed never made.
The seed's leave balances or punches look out of date by Session 4
Run npm run seed:dev yourself: the seed works its dates out from today. The accrual and overtime tests in Session 4 use the fixed dates in tests/fixtures/, so they never age. We hit this with time-relative panels: seeded data aged and "this week" went blank.
Knowledge check
A worker is promoted. What happens in hr_job_assignment?
Knowledge check
Where are a worker's Social Security and bank numbers stored in the module?
References
- U.S. eCFR: 29 CFR Part 516, records to be kept by employers. https://www.ecfr.gov/current/title-29/part-516
- U.S. Department of Labor: Fact Sheet #21, recordkeeping requirements under the FLSA. https://www.dol.gov/agencies/whd/fact-sheets/21-flsa-recordkeeping
- Supabase Docs: Seeding your database. https://supabase.com/docs/guides/local-development/seeding-your-database
- NIST SP 800-122: Guide to protecting the confidentiality of PII. https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-122.pdf
Chapter 2 · Sessions 3–4
Who may see pay, and the week from punch to payroll
The access rules come from the role matrix, so pay is visible to HR only and no role can change a punch, enforced by the database. Then the clock, the overtime engine tested against a matrix you work out on paper, leave accruals tested against your written policy, timesheet approval, and a payroll export whose hours equal the approved timesheets to the minute.
40 min5 steps3 definition-of-done tests
By the end of this chapter you can
- Add the module's roles, tables and screens to docs/matrix.json and regenerate the access rules and their tests.
- Build the clock, the employee's time screen and the supervisor's timesheet screen, phone first.
- Prove the overtime engine against a hand-worked matrix, and the payroll export against the approved timesheets.
The rights, as a matrix
Two jobs are new to your Foundation roles: the HR manager and the payroll processor. Every signed-in person is also an employee of their own record. Nobody deletes, and nobody updates a punch. The FMLA flag on a leave request is medical-related [3], so even the supervisor who approves the leave does not see it. Postgres applies these rules to every query, so a screen cannot get round them [4].
| Table | Employee (own record) | Supervisor (own crew) | Manager (own team) | HR manager (new) | Payroll processor (new) |
|---|---|---|---|---|---|
| hr_employment, hr_job_assignment | Read own | Read | Read | Write (assignments: add, or close with effective_to) | Read employee_no |
| hr_compensation | No right | No right | No right | Insert; read | No right |
| hr_time_punch | Insert through the clock route; read own | Read; insert manual_edit corrections | Read | Read | Read (to check hours have punches) |
| hr_timesheet | Read own; submit | Approve; reopen | Approve; reopen | Read | Read; mark exported |
| hr_time_off_request | Request; read own, with the FMLA flag | Approve or deny, without the FMLA flag | Approve or deny, without the FMLA flag | Read; write; set the FMLA flag | No right |
| hr_time_off_balance, hr_time_off_policy | Read own; read policies | Read | Read | Insert balances; write policies | No right |
| hr_schedule_shift | Read own published | Write | Read | Write | No right |
| hr_payroll_batch | No right | No right | No right | Read | Write |
| hr_requisition … hr_offer, hr_candidate | No right | No right | Read own requisitions | Write | No right |
Session 3: Add the module to the role matrix and regenerate the access rules
35 minutesWhy
Pay hidden by a screen is pay one wrong query away from everyone. Writing the rights in docs/matrix.json makes the database refuse the row before any screen asks, so a new report, an import or an agent cannot leak a rate. Because scripts/gen-policies.mjs writes one allowed and one refused test per cell, a missing right shows up as a red test now, not as a supervisor who cannot approve on payroll day.
Do this
Read docs/matrix.json, scripts/gen-policies.mjs and the M21 section of docs/spine-map.md.
On a new branch hr/access:
1. Add roles hr_manager and payroll_processor to docs/matrix.json. Every signed-in role is also an employee of its own record. Add one cell per role and hr_ table exactly as in this table (element M21, chapter 2), and nothing more. Nobody deletes; nobody updates hr_time_punch.
<paste the matrix table from element M21, chapter 2 here>
2. Where a cell says "without the FMLA flag", use the matrix's column restriction if gen-policies.mjs supports one. If it does not, stop and tell me before doing anything else; do not hand-edit generated files.
3. Screens and routes with their roles: /app/my-time (every signed-in role), /hr/timesheets (supervisor, manager), /hr/employees (hr_manager), /hr/payroll (payroll_processor); /api/hr/punch, /api/hr/timesheet, /api/hr/leave, /api/hr/schedule, /api/hr/accrual, /api/hr/payroll/export with the same roles as their screens.
4. Run node scripts/gen-policies.mjs, and node scripts/gen-routes.mjs for lib/access/routes.ts.
5. Tests in supabase/tests/hr_access.test.sql: a supervisor, a manager, the payroll processor and an employee each read no row of hr_compensation, while the HR manager does; a supervisor reads a leave request without the FMLA flag and the employee who asked sees it; no role updates or deletes a punch; a supervisor inserts a manual_edit for their crew but not for another crew, and cannot correct their own punch; an employee cannot see another employee's punches; an employee can submit but not approve their own timesheet; a supervisor's approval really changes the row.
Push, open a pull request titled "HR access", wait for every check, and tell me in plain words who can see a pay rate.You will see recreated screen
- Check this sentence against the matrix: one role under hr_compensation.
Check it worked
Pull request HR access is green; docs/matrix.json shows hr_compensation with one role; the generated tests include a refusal for every other role; docs/access-review.md shows the two new roles.
If it goes wrong
The supervisor's Approve says success and the timesheet stays submitted
The read rule does not cover the row after the change. Say: Check each updating role's read policy covers the row before and after the change, and add a test that the status really changed. We hit this in three modules; a test of the response alone passes while nothing happened.
Claude Code proposes letting payroll read hr_compensation "to check the export"
No. The export carries hours, never a rate; the provider holds the rates for pay. Say: Keep hr_compensation for hr_manager only, as the matrix says.
Access tests pass in the SQL editor, yet the screen shows another crew's punches
The route uses a login that skips the rules. Say: Show me which login each /api/hr route uses. None may use service_role; the timesheet engine runs as a security-definer function instead.
Session 3: Build the clock and the time screens, phone first
40 minutesWhy
The clock is used by every person on every shift, often on a phone with gloves on, so it must be fast and must never take its time from the phone, which can be set to anything. Building the employee's, supervisor's and payroll screens in one pull request lets you test the rights from Step 4 against real pages before any hours are calculated.
Do this
Before writing any route or page, read the guide in node_modules/next/dist/docs/ for this version of Next.js (request middleware lives in proxy.ts). Read docs/matrix.json and lib/access/routes.ts.
On a new branch hr/screens, using the operator-surface components from Session 12:
1. /api/hr/punch as the signed-in employee: insert hr_time_punch with the server's time (never the browser's), the employee's employment taken from the session (never from the page), punch_type and source (web, kiosk, mobile, badge). Save the phone's location in geo only if the person allowed it. Refuse out without in, two ins in a row, and break_end without break_start. Return the saved punch and today's hours.
2. /app/my-time, phone first: a large Clock in / Clock out button, today's punches, this week's hours, leave balances (latest as_of per policy), published shifts, missed-punch exceptions, a time-off request form, and Submit week.
3. /hr/timesheets for supervisors and managers: the crew's weeks with regular, overtime, double-time and time-off hours and any exceptions; a correction form that adds a manual_edit punch with a reason.
4. /hr/payroll for the payroll processor: approved weeks, ready for export (export comes in Session 4).
5. /hr/employees for the HR manager: employment, job and pay history by effective date.
Tests: each screen at 360 and 390 px with no sideways scroll and 44 px targets; signed out, every /hr and /api/hr address lands on sign-in; an employee's request for another employee's punches is refused; a clock-in sent twice with the same id makes one punch.
Push, open "HR screens", wait for the checks, and give me the preview address.On the preview, on a phone, sign in as a made-up employee and clock in and out. Then sign in as the supervisor and find the punch.
You will see recreated screen
| Day | Hours |
|---|---|
| Mon | 8.0 |
| Tue | 8.0 |
| Wed | 4.2 so far |
- The time comes from the server, so a phone with the wrong clock cannot change it.
- The balance shows its date: balances are dated rows.
- The employee cannot fix it; they ask, and the correction keeps the original.
Check it worked
On a phone you clocked in and out on the preview, the supervisor sees the punch with its server time, the screen tests are green, and signed out every /hr address lands on sign-in.
Fastest path
Test the clock on a real phone over the plant's Wi-Fi first: a slow response at shift change, when everyone clocks at once, is what people will remember.
If it goes wrong
Punches are recorded under the wrong person
The route trusts the page. Say: Take the employment from the signed-in session on the server and ignore anything the page sends. We found every record credited to one person this way.
A punch sent on a weak signal appears twice
Say: Make the punch id on the phone with crypto.randomUUID() and insert with on conflict (id) do nothing; add a test that sends the same punch twice.
A link on /hr/timesheets opens a blank page
Say: Sign in as each role on the preview, visit every page and link under /hr and /app/my-time, and list every 404 or error. A link that compiles is not a link that works.
Knowledge check
Which role may read a worker's pay rate?
The week, worked by hand first
Federal law requires overtime at 1.5 times for every hour over 40 in a workweek [1]. Some states add daily overtime and double time; California, for example, pays 1.5 times over 8 hours in a day, 2 times over 12, and has a seventh-consecutive-day rule [2]. Each hour is paid once, at the highest rate any rule gives it. Exempt employees are not owed overtime. Work this matrix on paper before Claude Code writes a line; the engine must give exactly these answers.
| Scenario | Rules | Regular | OT 1.5x | DT 2x |
|---|---|---|---|---|
| a. Five 8-hour days | Federal | 40 | 0 | 0 |
| b. Five 9-hour days | Federal only | 40 | 5 | 0 |
| c. Five 10-hour days | Federal + California-style daily | 40 | 10 (not 20) | 0 |
| d. One 13-hour day | California-style daily | 8 | 4 | 1 |
| e. Six 8-hour days | Federal | 40 | 8 | 0 |
| f. Seven 8-hour days | California-style, seventh-day rule | 40 | 16 | 0 |
| g. The 48 hours of e, exempt employee | Any | 48 | 0 | 0 |
Session 4: Overtime, punch corrections and timesheet approval
30 minutesWhy
Overtime is where a time system is most often wrong and most expensive to be wrong. Writing the scenarios down first, with answers you worked out by hand, turns "looks right" into seven tests that either pass or fail. Approval and the punch rules belong in the same pull request because together they decide which hours payroll will ever see.
Do this
On a new branch hr/time, using docs/hr-inventory.md for our rules:
1. A trigger on hr_time_punch that calls a security-definer timesheet engine (set search_path = ''): for the punch's employee and workweek it finds or creates the open hr_timesheet, adds in-to-out time minus unpaid breaks, counts a manual_edit row in place of the punch whose time equals its original_punched_at, and writes a missed in or out into exceptions instead of guessing. No rounding.
2. A function calc_overtime(week of punches, hr_overtime_rule) returning regular, ot and dt hours: federal weekly over 40 at 1.5x; the state's daily and double-time thresholds and seventh-day rule if the rule row has them; each hour once, at the highest rate; exempt employees all regular. Tests for exactly these scenarios and answers:
<paste the scenario table from element M21, chapter 2>
3. Corrections: a supervisor adds a manual_edit punch with punched_at, original_punched_at (empty for a missed punch), edited_by and edit_reason; a supervisor cannot correct their own punch.
4. Approval: an employee submits; a supervisor or manager approves open, submitted or reopened weeks, never their own and never with an open exception; approval writes hr.timesheet.approved to core_event_outbox. A trigger refuses any punch dated inside an approved or exported week, and any change to an exported timesheet. Reopening leaves a trace.
The scenario and punch tests load tests/fixtures/hr-punch-week.json. For each new test, show it failing with its rule removed, then passing. Push, open "HR time and overtime", wait for the checks, and tell me the scenario results.On the preview, open SYNTHETIC · Operator 01's seeded week (last week, Monday to Friday, 08:00–16:00) and add a Saturday with an in and no out. As the supervisor, see approval refused, correct the Saturday out to 16:00 with a reason, and approve: 40 regular and 8 overtime.
You will see recreated screen
- Your hand matrix, as tests. If a number differs, the code is wrong, not the paper.
- Scenario c is the one most engines get wrong: an hour over 8 in a day and over 40 in the week is still one hour.
Check it worked
All seven scenarios pass with your hand answers; on the preview the seeded week with a corrected Saturday shows 40 regular and 8 overtime, the original Saturday punch is still in the table, and a punch into the approved week is refused.
If it goes wrong
Scenario c gives 20 overtime hours
Each hour is being paid twice. Say: Each hour is counted once at the highest rate any rule gives it. Fix calc_overtime; do not change the test.
Claude Code suggests updating the punch "because it is simpler"
Say: A punch is never edited. A correction is a new manual_edit row with the original time and a reason. The FLSA asks for accurate records of hours worked; the original is part of that record.
The tests pass and you are not sure they test anything
Say: Remove the rule each test guards, show me it fails, then restore it. One of our checks was green for weeks because it could only ever answer yes.
Session 4: Leave accruals tested against your written policy
20 minutesWhy
An accrual engine that is out by an hour a month is out by twelve hours a year for every employee, and nobody notices until someone leaves and is paid out. Two examples from your own written policy, worked by hand, become the tests. Balances are dated rows, never overwritten, so every balance can be explained from its history.
Do this
From your written policy, work two examples by hand. A pattern to copy: 1 hour per 30 hours worked, cap 40; a balance of 39.5 plus a 60-hour period earns 2 hours but ends at 40, not 41.5. Make the second test a waiting period or the year-end carryover.
On a new branch hr/leave:
1. accrue_time_off(employment_id, as_of), security definer: per_hour_worked accrues when a timesheet is approved; per_pay_period when the HR manager calls /api/hr/accrual; annual_grant on the policy's date; none never. Nothing before hire_date plus waiting_period_days; never above max_balance_hours; cut to carryover_max_hours at year end. Every result is a new hr_time_off_balance row; a balance is never updated.
2. Requests: the employee asks (pending); a supervisor or manager approves or denies, refused if more than the current balance; approved leave counts as pto_hours on the timesheet; when that week is approved the request becomes taken and one balance row deducts it, never twice. Only the HR manager sets fmla_designated.
3. Tests with my two examples and their hand answers:
<example 1, with the hand-worked answer>
<example 2, with the hand-worked answer>
Push, open "HR leave", wait for the checks, and tell me both results.You will see recreated screen
- If an example fails, read the policy again with HR before touching the code: the policy is the reference.
Check it worked
Both examples give your hand answers; on the preview a made-up employee requests 8 hours, the supervisor approves, and after the week is approved the balance has one new row 8 hours lower.
If it goes wrong
The engine and your hand answer differ by a small amount
Check whether the policy says hours worked or hours paid, and whether leave hours accrue. Write the answer in docs/hr-inventory.md, then fix the code.
The supervisor's screen shows the FMLA flag
The column restriction is missing. Say: The supervisor must read leave requests without fmla_designated. Fix it in docs/matrix.json, regenerate, and add a test.
Session 4: Export approved hours to payroll, reconciled
25 minutesWhy
The export is the one place the module's numbers turn into money. If the file's hours differ from the approved timesheets by a minute, someone is paid wrongly, and you will not find out until they complain. A batch that refuses to export unless its totals equal the approved timesheets, per person, makes that impossible. Pay itself stays with the provider, who is built and audited for tax.
Do this
Open your payroll provider's own help for importing hours, and note the column names it expects.
On a new branch hr/payroll, build the export for the payroll processor on /hr/payroll:
1. Create an hr_payroll_batch (batch_no, provider, period). Before exporting, check that every approved timesheet with worked hours has punches behind it and every time-off-only timesheet has a taken request.
2. Write a CSV in our provider's layout: <paste the column names from the provider's import help>. One line per approved employee with name, employee_no, period, regular, overtime, double-time and time-off hours. Never a pay rate, and never an identity, bank or card number.
3. Refuse to finish unless the sum of hours in the file equals the sum on the approved timesheets, in total and per employee. Then mark the timesheets exported, store the file in core_attachment (readable by the payroll processor and HR only), set exported_at, and write hr.payroll_batch.exported.
4. A query for overtime percentage: ot hours / (regular + ot + dt hours).
Tests: the reconciled fixture batch exports; a batch with one hand-altered line is refused; an exported timesheet cannot be reopened; the file has no rate column. Push, open "HR payroll export", wait for the checks, and tell me.You will see recreated screen
| Employee | Regular | OT | DT | Time off |
|---|---|---|---|---|
| E-0001 | 40.0 | 8.0 | 0.0 | 0.0 |
| E-0002 | 32.0 | 0.0 | 0.0 | 8.0 |
| E-0003 | 40.0 | 0.0 | 0.0 | 0.0 |
- The one number to check before you upload the file to the provider.
Check it worked
On the preview the batch for the seeded week exports with a matching control total, the CSV has no rate column, a batch with an altered line is refused, and overtime percentage for the 48-hour week reads 16.7% (8 / 48).
If it goes wrong
The file has a rate column because the provider's template has one
Leave it empty or remove it. The provider holds the rates; the module sends hours. Say: The file must never carry a rate, even empty-valued if the template insists; check with me.
The download says the file was sent to the provider, and the provider has nothing
The module only makes the file; a person uploads it. Say: Never report sent. Report "file ready" and let the processor set acknowledged when the provider accepts it. We had a button that claimed messages were sent while nothing left the building.
Someone asks for gross pay on the screen "to save a step"
No: that is payroll calculation, which stays with the provider. The specification lists calculating payroll tax in-house as a pitfall.
Knowledge check
Five 10-hour days under a California-style daily rule and the federal weekly rule. How many overtime hours?
Knowledge check
What must be true before a payroll batch is exported?
References
- U.S. Department of Labor: Fact Sheet #23, overtime pay requirements of the FLSA. https://www.dol.gov/whd/regs/compliance/whdfs23.htm
- California Department of Industrial Relations: overtime FAQ. https://www.dir.ca.gov/dlse/faq_overtime.htm
- U.S. eCFR: 29 CFR Part 825, the Family and Medical Leave Act. https://www.ecfr.gov/current/title-29/part-825
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
Chapter 3 · Sessions 5–6
Move the people in, and retire the old tools
Employees, job history, leave balances and open requisitions come across, with balances as dated opening entries checked against the old system. You rehearse on the development project with a copy IT has approved, walk one candidate to a hire, import into production through the pipeline, run a full pay period side by side, and cancel the old tools only when the hours agree.
35 min4 stepsEnds with the module gate
By the end of this chapter you can
- Write the import with Claude Code from column headings and made-up rows, and rehearse it on the development project.
- Walk a made-up candidate from requisition to hire with onboarding tasks.
- Import into production through the pipeline, run one pay period side by side, cut over and record the saving.
The rules for moving people's records
- Balances are dated opening entries. Each balance arrives as an hr_time_off_balance row with as_of the date of the old system's report, and is checked against that report before the first pay period.
- History stays history. Job and pay history arrive as effective-dated rows; nothing is collapsed into one current row.
- Never Social Security, bank or card numbers. The import refuses a file with such a column, and the database refuses long digit runs in free text [3].
- Nobody pastes a row into Claude Code. It gets headings and three made-up rows. The rehearsal on acme-platform-dev uses a copy IT approved in writing, redacted of names and pay, and is removed the same day, with the date recorded. Production is loaded only by
.github/workflows/import-hr.yml, started by a person from main, from an export in the private Storage bucket imports whose sha256 and counts are indocs/imports/hr-approved.md. - Keep what the law says to keep. Payroll records at least three years and time cards two under the FLSA [1][2]; Form I-9 under 8 CFR 274a.2 [4]; your state may require longer.
Session 5: Write the import and rehearse it on the development project
40 minutesWhy
People notice a wrong leave balance on the first day and a wrong hire date at their anniversary. Writing the import from headings keeps personal data out of Claude Code; rehearsing it on the development project with a copy IT approved, and checking balances against the old system's own report, finds every mismatch while nothing real can be harmed. The script refusing any target but the development project from your computer stops a slip of the keyboard.
Do this
HR exports employees, job and pay history, leave balances (with the report date) and open requisitions from the old system, in their own account, into an encrypted folder only they and you can open. Ask IT, in writing, to approve a copy for the rehearsal; it is redacted (names and rates replaced with the script's --redact). Copy only the first line (the headings) of each file.
On a new branch hr/import, write scripts/import-hr.mjs. You will never see the real export. Headings and three made-up rows per file:
<paste the heading line of each file and write three made-up rows under each>
The script:
1. Refuses any file with a column whose name looks like a Social Security, tax id, bank, routing or card number, and names the column.
2. Maps employees to hr_employment (employee_no unchanged, original hire date kept), history to effective-dated hr_job_assignment and hr_compensation rows, leave to hr_time_off_balance rows with as_of the report date, open requisitions to hr_requisition. Old ids in ext.source_id, ext.imported true, ext.batch.
3. Lists every person it cannot match to core_person and stops; the people administrator adds them first (former employees inactive).
4. Prints per file: read, imported, skipped with reasons, and three reconciliation reports: headcount by status, total balance hours per policy, open requisitions. Nothing of the data itself is printed or logged.
5. --target dev asks for the development connection string with hidden input and refuses any host but tsrqponmlkjihgfedcba; --redact replaces names and rates with made-up ones for the rehearsal; --target production refuses unless running in the import-hr workflow in GitHub Actions; --undo <batch> removes one batch, dev only.
Tests in CI with the made-up rows. Push, open "HR import", wait for the checks, and tell me.When it is green, run the rehearsal yourself. Paste the development connection string from its Connect page when asked, with the password from the password manager.
node scripts/import-hr.mjs --target dev --redact --file ~/secure/hr-export/Set the three reports beside the old system's own reports. When they agree, and the same day, remove the rehearsal batch and write the date you removed it in docs/hr-import.md:
node scripts/import-hr.mjs --target dev --undo <batch id it printed>You will see recreated screen
- Hidden input, and a refusal for any host but the development project.
- Set these totals beside the old system's report for the same date. They must be equal before the first pay period.
Check it worked
On the development project, imported plus skipped equals read for every file; headcount, balance totals per policy and open requisitions equal the old system's reports for the same date; the rehearsal batch was removed the same day, with the date recorded in docs/hr-import.md.
If it goes wrong
The script refuses the file because of a column named ssn
That is it working. Ask HR to export again without that column. Never remove the check.
Balance totals differ from the old system
Check the date first: the old report and as_of must be the same day. Then compare one policy person by person. Do not adjust balances by hand to make the totals agree.
IT will not approve a copy, even redacted
Rehearse with the made-up rows only, and check the first production import's reports line by line in Step 11. Write IT's decision in docs/hr-import.md.
Session 5: Walk a made-up candidate from requisition to hire
20 minutesWhy
Hiring is where a new person's record is born, so it is where duplicates and missing onboarding start. Walking one made-up candidate through every stage on the development project proves an application cannot become a hire without an accepted offer, and that the hire creates the employment, the first job and pay rows and the onboarding tasks in one go.
Do this
On a new branch hr/hire, on /hr/employees for the HR manager: a requisition moves draft → approved → open; a candidate (consent_at, retain_until from our written retention rule) applies; stages applied → screen → interview (hr_interview with scorecard) → offer (hr_offer draft → approved → sent → accepted). An application cannot become hired without an accepted offer. On hire, in one transaction: hr_employment (pre_hire), the first hr_job_assignment (change_reason hire), the first hr_compensation row from the offer, onboarding tasks for hr, manager, it, safety, training, facilities and employee, and hr.employment.hired in the outbox. Candidates past retain_until are archived by the daily job. Tests for each rule. Push, open "HR hiring", wait for the checks, and tell me.On the preview, as the HR manager, take SYNTHETIC · Candidate 01 from requisition to hire. Then sign in as the manager and tick the manager's onboarding task.
You will see recreated screen
| Task | Owner | Due |
|---|---|---|
| Badge and locker | facilities | 2027-01-15 |
| Lockout training | safety | 2027-01-18 |
| Accounts | it | 2027-01-15 |
- One transaction: if any part fails, nothing is created.
Check it worked
On the preview the made-up candidate becomes E-xxxx with one employment, one job row, one pay row and seven onboarding tasks; an application moved to hired without an accepted offer is refused.
If it goes wrong
Hiring creates a second core_person for someone already in the system
Say: Before creating a person, look for an existing core_person with the same work email or employee number, and use it. Two records for one person split their history.
Candidate data is visible to the hiring manager
Say: hr_candidate is for hr_manager only, as the matrix says. Regenerate and add a refused test for the manager.
Session 6: Import into production through the pipeline, and run a pay period side by side
30 minutes, then one pay periodWhy
Production holds real people's records. A pull request that adds only docs/imports/hr-approved.md (the export's sha256, the expected counts and totals, no data) is reviewed by owner two like any change; the import workflow, started by a person from main, refuses any export not listed there and fails if any count or balance total differs. A full pay period in both systems is then the only proof that hours match before anyone's pay depends on them.
Do this
Session 6 starts with the import and ends after one full pay period. Upload the export to a private storage bucket named imports in the live project (Public bucket off).
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
The live project's Storage: the private imports bucket.
On a new branch hr/import-prod:
1. Add docs/imports/hr-approved.md holding only the batch id, each export file name in the imports bucket with its sha256 (I give you the values; I worked them out with shasum -a 256), the expected row counts and the three reconciliation totals from the rehearsal (no data).
2. Add .github/workflows/import-hr.yml, started only by hand (workflow_dispatch) and refusing any branch but main: it downloads the export from the private Storage bucket imports, refuses it unless its sha256 and counts are in docs/imports/hr-approved.md on main, runs node scripts/import-hr.mjs --target production signed in as hr_import, and fails if any count or total differs. No GitHub environments or required reviewers: the reviewed pull request is the approval.
3. A migration creating the role hr_import: insert only on the tables the import writes, reading only core_person to match, never the service role key. I set its password myself and type it as the Actions secret HR_IMPORT_DB_PASSWORD; list it by name in docs/KEYS.md. If anything else needs a secret that does not exist yet, stop and tell me its name.
Push, open "HR import into production", wait for the checks.Set hr_import's password yourself in the live project and type it at the repository's secrets page. Owner two approves; merge. Start the import yourself: Actions → import-hr → Run workflow, branch main, and watch the run. Then, for one full pay period, everyone clocks on the platform and the old clock. At the end, set the platform's export beside the provider's register for the old system's hours.
https://github.com/acme-ops/acme-platform/actions
GitHub Actions: run import-hr from main, then read its counts and totals.
You will see recreated screen
export sha256 matches docs/imports/hr-approved.md employees.csv expected 212 imported 212 ok balances.csv expected 636 imported 636 ok balance hours vacation 7,412.5 = 7,412.5 ok SSN/bank/card columns: none
- Red means nothing was written: each file imports in one transaction.
Check it worked
The import-hr run, started from main, is green: the export's sha256 matched docs/imports/hr-approved.md and its counts and balance totals equal that file; after one pay period, hours per employee from the platform's export equal the old system's within the tolerance you set with payroll (this course uses 1%), and every difference for a person is explained.
If it goes wrong
The workflow fails with an empty secret
A secret that was never created reads as empty. Type it yourself at acme-ops/acme-platform/settings/secrets/actions" href="https://github.com/acme-ops/acme-platform/settings/secrets/actions" target="_blank" rel="noopener">the repository's secrets page (value only, no NAME=), list it in docs/KEYS.md, and re-run.
The run refuses the export: sha256 not approved
The file in the bucket is not the one owner two approved. Upload the approved file again, or open a new pull request with the new sha256 and counts. Never change the workflow to skip the check.
Hours differ by 2% for the period
Do not cut over. Find the people whose hours differ, compare their punches in both systems day by day, and fix the cause; often it is rounding in the old clock, which the module does not do.
Session 6: Cut over and cancel the old tools
30 minutesWhy
Writing the side-by-side results, the three module proofs, the cutover date, the rollback and the saving into one file means the decision to cancel can be checked by anyone, and nothing depends on memory. The records you must keep are settled before the vendor can delete them.
Do this
On a new branch hr/cutover, write docs/hr-cutover.md for me to fill in, with no number invented:
1. The pay period side by side: headcount; per employee and in total, regular, overtime, double-time and time-off hours from the old system and the platform; difference; explanation.
2. The three module proofs, each with the test and its result: the overtime scenario matrix passes; no role but hr_manager reads hr_compensation; the payroll export reconciles to the approved timesheets. Run them now and write the results.
3. Balances: the old system's report and the platform's for the cutover date, per policy.
4. The workarounds from docs/hr-inventory.md, each covered, not needed, or open.
5. Cutover: the date, who tells the floor, when the old clocks and apps are switched off, the rollback plan, and who keeps the old export and until when (the longest of the FLSA, Form I-9 and our state's rules).
6. The saving: the old tools' bills from their invoices, minus what the module adds to the services we already pay for.
7. A migration that sets hr_import to NOLOGIN at cut-over, applied by the deploy workflow on merge.
Open "HR cutover" and show me the link.Fill in the numbers. On the date, switch off the old clocks and remove the old app links. Read each tool's cancellation terms on your own account page, cancel (or record the date the plan ends), and mark each record type in docs/hr-inventory.md as replaced, retired or still on the old way.
You will see recreated screen
| Period 2027-01-11 – 01-24 | Old system | Platform | Explanation |
|---|---|---|---|
| Regular hours | 16,214.0 | 16,221.5 | 7.5 h: old clock rounded to the quarter hour |
| Overtime hours | 1,102.5 | 1,102.5 | — |
- A difference with a reason is fine; a difference without one means not ready.
- The three definition-of-done tests.
- From your invoices; the course gives no figure.
Check it worked
docs/hr-cutover.md is on main with the pay period compared and explained, the three proofs passing, balances agreeing, the cutover date, the rollback plan, the retention owner and date, and the saving from invoices; the old tools are cancelled or their end dates recorded.
If it goes wrong
Someone asks for the old export to be deleted to save space
No. Keep it for the longest period the FLSA, Form I-9 rules and your state require, with a named owner. The vendor may delete its copy once you cancel.
Cancelling early gives no refund
Leave the old tool read-only until the paid period ends, and record that date.
Knowledge check
Leave balances are imported. What must happen before the first pay period?
References
- U.S. eCFR: 29 CFR 516.5, records to be preserved for 3 years. https://www.ecfr.gov/current/title-29/section-516.5
- U.S. eCFR: 29 CFR 516.6, records to be preserved for 2 years. https://www.ecfr.gov/current/title-29/section-516.6
- NIST SP 800-122: Guide to protecting the confidentiality of PII. https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-122.pdf
- U.S. eCFR: 8 CFR 274a.2, verification of employment eligibility (Form I-9). https://www.ecfr.gov/current/title-8/section-274a.2
Chapter 4 · 12 questions · 80% passes
Final assessment
Twelve questions across the element. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.
15 min12 questions≈ 15 minutesRetake allowed
Your result
CivOps AI Academy
People, time and attendance: Employment, time clocks and payroll export
Element M21 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.