HR & Attendance Build

Stage 02 · Interactions

Home › Apps › HR & Attendance › Stage 02
⚡ Stage 02 · 3–4 hours

Make it tick.
Live clock. Real events.

The shell becomes a working time clock. One state object holds employees and events. The employee view ticks once per second — the current time, the "working for Xh Ym" counter. Clocking in creates a real event that the manager view's KPIs and timeline both reflect. Clicking "Clock in" twice does nothing the second time. Close the tab mid-shift, reopen — the shift is still running. Everything is derived: hours worked, employee status, KPI values. Nothing is stored except the events themselves.

3–4 hours Intermediate JavaScript · DOM · localStorage
HR hub State shape Shift derivation Idempotent clock-in The live timer Derived KPIs localStorage Next: Stage 03

Short answer: One state = { employees: [], events: [], view: 'manager' }. One render() that rebuilds the KPI cards, the employee list, the timeline, and the employee clock card. One deriveShift(events, employeeId, date) that walks events chronologically and produces { clockIn, clockOut, breakMinutes, minutesWorked, status }. One clockIn() / clockOut() pair guarded by a transitioning flag and a state check. One setInterval(renderClock, 1000) that updates only the clock text — not the whole app. One saveState() on every mutation. Every derived value recomputes on every render; nothing computed is stored.

✅ State shape — two arrays, one view

Employees and events. Nothing else.

The state object is intentionally small. It holds only facts: who the employees are, and what events have happened. Every other value — status, hours, KPIs — is a function of these two arrays.

state.js hr-stage-02.html · lines ~480–505
// The only state. Everything else is derived.
const state = {
  employees: [],   // [{ id, name, role, avatar, color }]
  events: [],      // [{ id, employeeId, type, occurredAt }]
  view: 'manager'  // 'manager' | 'employee'
};

// Who is currently logged in to the employee view?
// In Stage 02, hardcoded to the first employee. Stage 04
// will add a picker.
const CURRENT_EMPLOYEE_ID = 1;

// A single timestamp for "today" — every render uses this
// so the derivation, KPIs, and timeline all agree on
// which date is "today."
function today() {
  return new Date().toISOString().slice(0, 10);  // 'YYYY-MM-DD'
}
// The only state. Everything else is derived.
const state = {
  employees: [],   // [{ id, name, role, avatar, color }]
  events: [],      // [{ id, employeeId, type, occurredAt }]
  view: 'manager'  // 'manager' | 'employee'
};

// Who is currently logged in to the employee view?
// In Stage 02, hardcoded to the first employee. Stage 04
// will add a picker.
const CURRENT_EMPLOYEE_ID = 1;

// A single timestamp for "today" — every render uses this
// so the derivation, KPIs, and timeline all agree on
// which date is "today."
function today() {
  return new Date().toISOString().slice(0, 10);  // 'YYYY-MM-DD'
}
Why employees and events, not shifts:

  A shift is a derived thing — it's what you get
  when you pair an 'in' event with an 'out' event.
  If you stored shifts in state, you'd have to keep
  them in sync with events on every clock-in and
  clock-out. Two sources of truth.

  By storing only events, the shift is a pure
  function: deriveShift(events, emp, date). Run it
  once, get the shift. Change an event, run it again,
  get a different shift. Nothing to keep in sync.

Why a single CURRENT_EMPLOYEE_ID:

  In Stage 02 the employee view is a demo — one
  hardcoded employee so you can see the clock-in flow.
  Stage 04 will add a dropdown ('choose employee') or
  a login, depending on whether we add auth or not.

  Hardcoding it for now keeps the demo honest: it
  shows the UI working without pretending to be a
  real multi-user system. Adding a picker later is
  a one-line change to where CURRENT_EMPLOYEE_ID is
  read.

Why today() is a function, not a constant:

  'Today' changes at midnight. If we computed it once
  at page load and stored it, an employee clocking in
  at 23:59 and out at 00:01 would have their shift
  split across two days in the derivation.

  Calling today() fresh on every render means the
  'current day' is always current. The derivation
  for a shift that crosses midnight uses the START
  date (the first event's date), not 'today' — we'll
  see that in the derivation function.

  The general rule: anything that could change while
  the app is open should be a function or recomputed,
  not captured once.

✅ Shift derivation — walk events in order

The one function the whole build rests on.

A shift is not "the first clock-in and the last clock-out." It's the result of walking the employee's events in chronological order, tracking a current state, and recording transitions:

Not started

Before any event. The employee hasn't clocked in.

Working

After an in event, before the next out. The clock is running.

On break

After a break_start event, before the next break_end. The clock is paused.

Finished

After an out event. The shift is closed. Hours are fixed.

The derivation returns one object with everything the UI needs:

derive.js hr-stage-02.html · lines ~530–580
function deriveShift(events, employeeId, date) {
  // Filter to this employee, sort chronologically
  const evs = events
    .filter(e => e.employeeId === employeeId)
    .sort((a, b) => a.occurredAt.localeCompare(b.occurredAt));

  // Shift date is the date of the first event.
  // Overnight shifts count toward the start date.
  const firstDate = evs.length ? evs[0].occurredAt.slice(0, 10) : null;

  let clockIn = null;
  let clockOut = null;
  let breakMinutes = 0;
  let breakStart = null;
  let status = 'not-started';

  for (const e of evs) {
    switch (e.type) {
      case 'in':
      case 'manual_in':
        if (status === 'not-started' || status === 'finished') {
          clockIn = e.occurredAt;
          clockOut = null;
          status = 'working';
        }
        break;
      case 'break_start':
        if (status === 'working') { breakStart = e.occurredAt; status = 'on-break'; }
        break;
      case 'break_end':
        if (status === 'on-break' && breakStart) {
          breakMinutes += diffMinutes(breakStart, e.occurredAt);
          breakStart = null;
          status = 'working';
        }
        break;
      case 'out':
      case 'manual_out':
        if (status === 'working' || status === 'on-break') {
          if (breakStart) { breakMinutes += diffMinutes(breakStart, e.occurredAt); breakStart = null; }
          clockOut = e.occurredAt;
          status = 'finished';
        }
        break;
    }
  }

  let minutesWorked = 0;
  if (clockIn) {
    const end = clockOut || new Date().toISOString();
    minutesWorked = diffMinutes(clockIn, end) - breakMinutes;
    if (minutesWorked < 0) minutesWorked = 0;
  }

  return { clockIn, clockOut, breakMinutes, minutesWorked, status, date: firstDate };
}

function diffMinutes(aIso, bIso) {
  return Math.round((new Date(bIso) - new Date(aIso)) / 60000);
}
function deriveShift(events, employeeId, date) {
  // Filter to this employee, sort chronologically
  const evs = events
    .filter(e => e.employeeId === employeeId)
    .sort((a, b) => a.occurredAt.localeCompare(b.occurredAt));

  // Shift date is the date of the first event.
  // Overnight shifts count toward the start date.
  const firstDate = evs.length ? evs[0].occurredAt.slice(0, 10) : null;

  let clockIn = null;
  let clockOut = null;
  let breakMinutes = 0;
  let breakStart = null;
  let status = 'not-started';

  for (const e of evs) {
    switch (e.type) {
      case 'in':
      case 'manual_in':
        if (status === 'not-started' || status === 'finished') {
          clockIn = e.occurredAt;
          clockOut = null;
          status = 'working';
        }
        break;
      case 'break_start':
        if (status === 'working') { breakStart = e.occurredAt; status = 'on-break'; }
        break;
      case 'break_end':
        if (status === 'on-break' && breakStart) {
          breakMinutes += diffMinutes(breakStart, e.occurredAt);
          breakStart = null;
          status = 'working';
        }
        break;
      case 'out':
      case 'manual_out':
        if (status === 'working' || status === 'on-break') {
          if (breakStart) { breakMinutes += diffMinutes(breakStart, e.occurredAt); breakStart = null; }
          clockOut = e.occurredAt;
          status = 'finished';
        }
        break;
    }
  }

  let minutesWorked = 0;
  if (clockIn) {
    const end = clockOut || new Date().toISOString();
    minutesWorked = diffMinutes(clockIn, end) - breakMinutes;
    if (minutesWorked < 0) minutesWorked = 0;
  }

  return { clockIn, clockOut, breakMinutes, minutesWorked, status, date: firstDate };
}

function diffMinutes(aIso, bIso) {
  return Math.round((new Date(bIso) - new Date(aIso)) / 60000);
}
Why the state machine, not a filter:

  Consider events: in(9:00), out(12:00), in(13:00), out(17:00)

  A naive filter:
    clockIn = first 'in'  → 9:00
    clockOut = last 'out' → 17:00
    hours = 8h

  Wrong. The employee took a 1-hour unpaid
  lunch. Real hours = 7h.

  The state machine sees four transitions:
    in(9:00)   → working
    out(12:00) → finished  (3h so far)
    in(13:00)  → working   (clockIn resets)
    out(17:00) → finished  (4h so far)
    Total minutes_worked = the last segment
    (13:00–17:00) + ... wait, that's wrong too.

  Actually, Stage 02 doesn't handle the "two
  separate shifts" case perfectly. It tracks
  only the LAST clock-in and clock-out. If
  the employee clocks in, out, in, out in
  one day, the derivation returns the last
  segment only.

  This is a known limitation. Stage 03 fixes
  it by splitting each in→out pair into its
  own shift row. For Stage 02, the demo
  shows one shift per day, and the derivation
  is correct for that case.

  The lesson here: the state machine is the
  right SHAPE, but Stage 02 is a simplification.
  Stage 03's version handles multi-shift days
  by emitting one shift per pair. If you want
  to see the full version now, it's the same
  loop with an array push instead of a single
  overwrite.

Why manual_in / manual_out are treated as
in / out:

  In Stage 02 there are no manual events yet —
  those come in Stage 04. But the derivation
  already handles them because Stage 03 will
  use the exact same logic. Recognizing both
  types here means the derivation doesn't need
  to change when Stage 04 introduces corrections.

  The alternative — a separate code path for
  manual events — would be two derivations,
  two chances to drift, two things to test.
  One code path that treats all clock-ins the
  same is simpler.

Why minutesWorked uses clockOut || now:

  While the shift is open (status === 'working'
  or 'on-break'), there is no clockOut. The
  'minutes worked so far' is clockIn → now,
  minus breaks.

  Every second, the clock render updates, so
  minutesWorked is recomputed with a fresh
  'now'. The counter ticks.

  Once the shift is closed (clockOut set),
  'now' is irrelevant — the number is fixed.
  Same function, same output, no branching
  needed in the caller.

Why status is 'not-started' before any event:

  The four states (not-started, working,
  on-break, finished) map to the four UI
  badges:
    not-started → grey dot, 'Off'
    working     → green dot, 'Working since ...'
    on-break    → amber dot, 'On break since ...'
    finished    → grey dot, 'Off — clocked out ...'

  Having an explicit 'not-started' state
  avoids the ambiguity of null clockIn meaning
  two things ('never worked' vs 'shift closed').
  Stage 02 never revisits this state once
  exited, but Stage 04 (with corrections)
  might — the state machine handles it
  cleanly.

✅ Idempotent clock-in

Click twice, one event.

The clock-in handler has three guards, each doing a specific job:

Guard 1 — transition lock

A transitioning flag disables the button during the async write. Prevents the double-click.

Guard 2 — state check

If the current shift is already working, reject the new clock-in. Prevents a "stuck" state that a fast click could create.

Guard 3 — event dedupe

If an identical event exists within the last 5 seconds (network retry, double-tap), skip the insert.

clockin.js hr-stage-02.html · lines ~610–655
let transitioning = false;

function clockIn() {
  // Guard 1: prevent double-click
  if (transitioning) return;

  const currentShift = deriveShift(
    state.events, CURRENT_EMPLOYEE_ID, today()
  );

  // Guard 2: reject if already working or on break
  if (currentShift.status === 'working' || currentShift.status === 'on-break') {
    return;
  }

  // Guard 3: dedupe — reject an 'in' within 5s of the last one
  const last = state.events
    .filter(e => e.employeeId === CURRENT_EMPLOYEE_ID && e.type === 'in')
    .sort((a, b) => b.occurredAt.localeCompare(a.occurredAt))[0];
  if (last) {
    const secondsSince = (Date.now() - new Date(last.occurredAt).getTime()) / 1000;
    if (secondsSince < 5) return;
  }

  transitioning = true;
  setClockButtonDisabled(true);

  state.events.push({
    id: 'ev_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
    employeeId: CURRENT_EMPLOYEE_ID,
    type: 'in',
    occurredAt: new Date().toISOString()
  });

  saveState();
  render();
  transitioning = false;
  setClockButtonDisabled(false);
}
let transitioning = false;

function clockIn() {
  // Guard 1: prevent double-click
  if (transitioning) return;

  const currentShift = deriveShift(
    state.events, CURRENT_EMPLOYEE_ID, today()
  );

  // Guard 2: reject if already working or on break
  if (currentShift.status === 'working' || currentShift.status === 'on-break') {
    return;
  }

  // Guard 3: dedupe — reject an 'in' within 5s of the last one
  const last = state.events
    .filter(e => e.employeeId === CURRENT_EMPLOYEE_ID && e.type === 'in')
    .sort((a, b) => b.occurredAt.localeCompare(a.occurredAt))[0];
  if (last) {
    const secondsSince = (Date.now() - new Date(last.occurredAt).getTime()) / 1000;
    if (secondsSince < 5) return;
  }

  transitioning = true;
  setClockButtonDisabled(true);

  state.events.push({
    id: 'ev_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
    employeeId: CURRENT_EMPLOYEE_ID,
    type: 'in',
    occurredAt: new Date().toISOString()
  });

  saveState();
  render();
  transitioning = false;
  setClockButtonDisabled(false);
}
Why three guards, not one:

  Each guard catches a different failure mode.

  Guard 1 (transition lock) — the user's
  finger. A fast double-tap fires two click
  events. The first sets transitioning = true,
  the second returns immediately. One event.

  Guard 2 (state check) — the app's logic.
  Even with Guard 1, if two tabs are open,
  one tab's clock-in won't know about the
  other tab's state. Guard 2 reads the current
  shift from the events list, sees status is
  already 'working', and rejects. Correct
  behavior across tabs.

  Guard 3 (time dedupe) — the network / retry.
  If Stage 03 introduces a network call and the
  first request times out but actually succeeded,
  the retry would create a second event. The
  time dedupe (5 seconds) prevents that. It's
  a Stage 03 safety net — overkill for Stage 02,
  but harmless and instructive.

  All three are cheap. None of them makes the
  happy path slower. Together they make clock-in
  idempotent in every failure mode.

Why 5 seconds, not 5 minutes:

  A real employee might legitimately clock in,
  realize they forgot something, clock out,
  and clock back in — within 30 seconds. A
  5-minute dedupe window would swallow that
  legitimate sequence.

  5 seconds is fast enough to catch double-clicks
  and network retries, slow enough that no
  legitimate action happens twice in that window.
  The number is a heuristic, not a law.

Why the flag resets in both success and error:

  In Stage 02, there's no network, so the
  reset happens only on the success path. But
  the pattern is already shaped for Stage 03:
  a real implementation would wrap the body in
  try/finally so transitioning is set to false
  regardless of whether the request succeeded.

  Writing it correctly now means Stage 03's
  change is one line (wrap in try/finally)
  instead of a refactor. The pattern is the
  same as POS Stage 03's checkoutInFlight.

The order matters:

  1. Check transitioning
  2. Check current state
  3. Check time dedupe
  4. Set transitioning
  5. Mutate
  6. Save
  7. Render
  8. Clear transitioning

  Guards 1-3 are cheap; they run first.
  The actual mutation runs only if the guards
  pass. The flag is set only after the guards
  pass. This minimizes the window where
  transitioning is true and something goes
  wrong inside the mutation.

  If you set transitioning before the guards,
  a bug in the guard would leave it stuck true
  forever, disabling the button permanently.
  Order is: check, check, check, then set.

✅ The live clock

Once per second. Only two text nodes updated.

The employee view ticks every second — the current time, the "working for Xh Ym" counter. But it doesn't re-render the whole app. It updates exactly two elements:

clock.js hr-stage-02.html · lines ~690–730
let clockTimer = null;

function startClock() {
  stopClock();
  clockTimer = setInterval(renderClock, 1000);
  renderClock();
}

function stopClock() {
  if (clockTimer) { clearInterval(clockTimer); clockTimer = null; }
}

function renderClock() {
  // Only run when the employee view is visible.
  // The manager view has no live clock.
  if (state.view !== 'employee') return;

  const now = new Date();
  const timeEl = document.getElementById('clock-time');
  const hoursEl = document.getElementById('clock-hours');

  if (timeEl) {
    timeEl.textContent = formatTime(now);
  }

  if (hoursEl) {
    const shift = deriveShift(state.events, CURRENT_EMPLOYEE_ID, today());
    const mins = shift.minutesWorked;
    hoursEl.innerHTML = 'Today: ' + formatDuration(mins) + '';
  }
}

// Pause when tab is hidden, resume when visible
document.addEventListener('visibilitychange', function () {
  if (document.hidden) stopClock();
  else if (state.view === 'employee') startClock();
});
let clockTimer = null;

function startClock() {
  stopClock();
  clockTimer = setInterval(renderClock, 1000);
  renderClock();
}

function stopClock() {
  if (clockTimer) { clearInterval(clockTimer); clockTimer = null; }
}

function renderClock() {
  // Only run when the employee view is visible.
  // The manager view has no live clock.
  if (state.view !== 'employee') return;

  const now = new Date();
  const timeEl = document.getElementById('clock-time');
  const hoursEl = document.getElementById('clock-hours');

  if (timeEl) {
    timeEl.textContent = formatTime(now);
  }

  if (hoursEl) {
    const shift = deriveShift(state.events, CURRENT_EMPLOYEE_ID, today());
    const mins = shift.minutesWorked;
    hoursEl.innerHTML = 'Today: ' + formatDuration(mins) + '';
  }
}

// Pause when tab is hidden, resume when visible
document.addEventListener('visibilitychange', function () {
  if (document.hidden) stopClock();
  else if (state.view === 'employee') startClock();
});
Why update two nodes, not the whole app:

  A naive implementation would call render() every
  second, which would rebuild the entire manager
  view (KPI cards, employee list, timeline) even
  though nothing in the manager view has changed.

  That's wasteful — dozens of DOM elements
  recreated every second. On a phone, it's
  noticeable. On a laptop, it's silent but real.

  Instead, renderClock() updates exactly the two
  nodes that show time: the clock display and
  the 'working for Xh Ym' line. Both are cheap.

  The rest of the app re-renders only on state
  changes (clock-in, clock-out, tab switch).
  Every state change is an intentional event;
  a clock tick is not a state change.

Why startClock() calls renderClock() immediately:

  setInterval(fn, 1000) fires the first time
  AFTER one second. Without an immediate render,
  the clock would show the stale value from the
  previous render for up to a second.

  Calling renderClock() right after setInterval
  makes the display correct immediately. Same
  pattern as calling render() at the end of
  every CRUD function in previous builds.

Why visibilitychange, not just setInterval:

  Browsers throttle setInterval in background
  tabs — sometimes to once per minute, sometimes
  to zero. If the tab is hidden for an hour,
  some browsers fire zero timers. When the user
  comes back, the clock shows an hour-old time
  until the next tick.

  Explicitly stopping on hidden and starting on
  visible makes the behavior deterministic. When
  the user comes back, startClock() fires
  renderClock() immediately, so the first frame
  after returning is correct.

  This is also battery-friendly. A phone with
  the HR app open in a background tab shouldn't
  wake up every second to update a hidden DOM.

Why the clock is client-side, not server-driven:

  In Stage 03, the state comes from the server,
  but the clock still ticks on the client. The
  server can't push a tick every second — that's
  86400 requests per employee per day. Instead,
  the client computes 'working for Xh Ym' locally
  from the clock-in time it got from the server.

  This is the rule: the server is the source of
  truth for facts (what events exist), the
  client is the source of truth for time-derived
  display (how long ago the clock-in was). Both
  compute the same derivation. They agree because
  they use the same events.

✅ Derived KPIs

Four numbers, all from the event list.

The four KPI cards in the manager view are all derived. None of them is stored; every one recomputes from `state.events` and `state.employees` on every render:

Clocked in now

Count employees whose current shift status is working. Doesn't count on-break — they're technically not working.

Hours today

Sum of minutesWorked across all employees' shifts today, divided by 60.

Pending approvals

Count weeks where some employee worked but no manager has approved. Stage 02 hardcodes this (3); Stage 04 computes it.

Active employees

state.employees.filter(e => !e.archivedAt).length. The headcount on payroll.

kpis.js hr-stage-02.html · lines ~760–800
function computeKPIs() {
  const d = today();

  // 1. Clocked in now — employees currently 'working'
  let clockedInNow = 0;
  for (const emp of state.employees) {
    const shift = deriveShift(state.events, emp.id, d);
    if (shift.status === 'working') clockedInNow++;
  }

  // 2. Hours today — sum minutesWorked across all employees
  let totalMinutes = 0;
  for (const emp of state.employees) {
    const shift = deriveShift(state.events, emp.id, d);
    totalMinutes += shift.minutesWorked;
  }
  const hoursToday = (totalMinutes / 60).toFixed(1);

  // 3. Pending approvals — hardcoded in Stage 02
  const pendingApprovals = 3;

  // 4. Active employees — non-archived
  const activeEmployees = state.employees.filter(e => !e.archivedAt).length;

  return { clockedInNow, hoursToday, pendingApprovals, activeEmployees };
}
function computeKPIs() {
  const d = today();

  // 1. Clocked in now — employees currently 'working'
  let clockedInNow = 0;
  for (const emp of state.employees) {
    const shift = deriveShift(state.events, emp.id, d);
    if (shift.status === 'working') clockedInNow++;
  }

  // 2. Hours today — sum minutesWorked across all employees
  let totalMinutes = 0;
  for (const emp of state.employees) {
    const shift = deriveShift(state.events, emp.id, d);
    totalMinutes += shift.minutesWorked;
  }
  const hoursToday = (totalMinutes / 60).toFixed(1);

  // 3. Pending approvals — hardcoded in Stage 02
  const pendingApprovals = 3;

  // 4. Active employees — non-archived
  const activeEmployees = state.employees.filter(e => !e.archivedAt).length;

  return { clockedInNow, hoursToday, pendingApprovals, activeEmployees };
}
Why one loop per KPI, not one loop total:

  A single loop could compute all four at once:

    let clockedInNow = 0, totalMinutes = 0;
    for (const emp of state.employees) {
      const s = deriveShift(state.events, emp.id, d);
      if (s.status === 'working') clockedInNow++;
      totalMinutes += s.minutesWorked;
    }

  That's marginally faster — one pass instead of
  two. For 6 employees, the difference is
  microseconds.

  The two-loop version is preferred here because
  each KPI is a self-contained computation. If
  KPI 2 needs to exclude breaks (a future change),
  you edit one loop. If KPI 1 changes to count
  'on-break' as well (a definitional change),
  you edit one loop. The two-loop version is
  more change-friendly.

  The general rule: prefer clarity over micro-
  optimization. A six-employee loop is free
  either way.

Why deriveShift is called n times:

  deriveShift filters events down to one employee
  and walks them. Called once per employee, it's
  O(events × employees). For 6 employees and 30
  events, that's 180 iterations — instant.

  If this were 10,000 employees and 1M events,
  you'd pre-group events by employee, or cache
  the derivation result per render. Neither is
  needed here.

  Stage 03 pushes the derivation to SQL:
    SELECT employee_id, SUM(minutes_worked)
    FROM shifts WHERE date = ? GROUP BY employee_id
  One query, not n. Same result, different shape.
  The client-side derivation and the SQL
  derivation must agree — that's the invariant
  Stage 03 tests.

Why hoursToday is a string, not a number:

  toFixed(1) returns a string ('28.5'). The KPI
  card is going to display this string directly.
  If we returned a number, the display layer
  would need to call toFixed(1) or toLocaleString,
  adding a formatting step at every render.

  Returning the display-ready value from the
  computation is a small convenience. But it's
  also a warning: at some point you'll want the
  raw number (e.g., to sum further). Stage 04
  changes this function to return both:

    return { hoursToday: 28.5, hoursTodayLabel: '28.5' };

  Then display uses the label, computation uses
  the number. For now, string is fine.

Why pendingApprovals is hardcoded:

  Stage 02 has no concept of 'approval' — that's
  a Stage 04 feature. Hardcoding it to 3 shows
  the card exists and where it will live, without
  pretending the feature is real.

  This is the same 'seed with honest fake data'
  pattern as the hardcoded KPI values in Stage 01.
  Stage 04 replaces the constant with a query.

✅ localStorage — survive the crash

Save on every mutation. Restore on load.

The state persists under two keys: mak-hr-employees and mak-hr-events. On load, if both exist, they're restored. If not, the seed is used:

persist.js hr-stage-02.html · lines ~830–880
const EMP_KEY = 'mak-hr-employees';
const EV_KEY  = 'mak-hr-events';
const VIEW_KEY = 'mak-hr-view';

function saveState() {
  try {
    localStorage.setItem(EMP_KEY, JSON.stringify(state.employees));
    localStorage.setItem(EV_KEY,  JSON.stringify(state.events));
    localStorage.setItem(VIEW_KEY, state.view);
  } catch (_) {
    // Quota or private mode — app works in-memory
  }
}

function loadState() {
  try {
    const empRaw = localStorage.getItem(EMP_KEY);
    const evRaw  = localStorage.getItem(EV_KEY);
    const viewRaw = localStorage.getItem(VIEW_KEY);

    if (empRaw && evRaw) {
      state.employees = JSON.parse(empRaw);
      state.events    = JSON.parse(evRaw);
    } else {
      state.employees = SEED_EMPLOYEES.slice();
      state.events    = SEED_EVENTS.slice();
    }

    if (viewRaw === 'manager' || viewRaw === 'employee') {
      state.view = viewRaw;
    }
  } catch (_) {
    state.employees = SEED_EMPLOYEES.slice();
    state.events    = SEED_EVENTS.slice();
  }
}
const EMP_KEY = 'mak-hr-employees';
const EV_KEY  = 'mak-hr-events';
const VIEW_KEY = 'mak-hr-view';

function saveState() {
  try {
    localStorage.setItem(EMP_KEY, JSON.stringify(state.employees));
    localStorage.setItem(EV_KEY,  JSON.stringify(state.events));
    localStorage.setItem(VIEW_KEY, state.view);
  } catch (_) {
    // Quota or private mode — app works in-memory
  }
}

function loadState() {
  try {
    const empRaw = localStorage.getItem(EMP_KEY);
    const evRaw  = localStorage.getItem(EV_KEY);
    const viewRaw = localStorage.getItem(VIEW_KEY);

    if (empRaw && evRaw) {
      state.employees = JSON.parse(empRaw);
      state.events    = JSON.parse(evRaw);
    } else {
      state.employees = SEED_EMPLOYEES.slice();
      state.events    = SEED_EVENTS.slice();
    }

    if (viewRaw === 'manager' || viewRaw === 'employee') {
      state.view = viewRaw;
    }
  } catch (_) {
    state.employees = SEED_EMPLOYEES.slice();
    state.events    = SEED_EVENTS.slice();
  }
}
Why two keys, not one:

  Employees and events change at different
  frequencies. Employees are set once and rarely
  edited. Events change every clock-in and
  clock-out.

  Two keys means two writes on every mutation,
  but each write is smaller. If an event write
  fails (rare), the employees write already
  succeeded — the employee list isn't corrupted.

  One key with { employees, events } would also
  work. The split is a preference, not a
  requirement. We split because it mirrors the
  two tables the data will live in on the
  server in Stage 03.

Why the view is persisted too:

  If a manager was looking at the manager view
  and reloads, they should see the manager view.
  If an employee was looking at the employee
  view (kiosk mode), reload should return them
  there.

  Persisting the view is a small thing that makes
  the app feel less like a demo. It's a one-line
  write and a one-line read.

Why the seed is a fallback, not a first-run
trigger:

  The simplest version: 'if localStorage is
  empty, seed. Else load.' That's what this does.

  A more complex version would track a 'has been
  seeded' flag and offer a 'reset' button. Stage
  02 doesn't need that — clearing localStorage
  in DevTools is the reset.

  The seed is intentionally small: 6 employees,
  a handful of events representing 'this morning's
  clock-ins.' Enough to show the manager view
  with realistic content, not so much that the
  file bloats.

Why saveState is called on view changes too:

  saveState() runs on clock-in, clock-out, and
  view switch. The view switch doesn't change
  any data, but it does change state.view, and
  state.view is what gets persisted.

  Alternatively, save only state.view on view
  switch and save only events on clock-in. But
  saving everything on every change is simpler
  and the cost is negligible.

  The rule: whenever state changes, save the
  whole state. Partial saves invite bugs where
  one field is updated but another isn't.

✅ The full file

The complete shell. Delivered separately so this page stays readable.

The full shell is hr-stage-02.html — one HTML file, ~810 lines, no dependencies, no build step. Open it in a browser and the shell is alive - clock ticking, KPIs derived, clock-in/out working, state persisting in localStorage.

The complete Stage 02 code, ready to run.

Download:
Download hr-stage-02.html →

Right-click, save link as. Or open in a new tab and use File → Save Page.

➡️ Next: Stage 03 — Backend

Events get a home.

Stage 02 loses every event on localStorage clear. That's fine for a client demo — but a time clock without a server isn't a time clock. Stage 03 adds one:

The client-side derivation from Stage 02 becomes the specification for the server-side derivation. Both must produce the same result. Stage 03's test is: run the same events through both, compare.

🔗 Continue the build

🐍 Next: Stage 03 — Backend
Flask + SQLite. Three tables, event log, server-side derivation, idempotent clock-in. 3–4 hours.
👥 Back to the HR hub
All four stages, the data model, and the roadmap.
← Back to HR & Attendance hub
HR Stage 02 · Interactions