Skip to content

Playbook (Staff Task Engine)

Recurring and event-driven daily tasks for store managers, with scheduling, reminders, escalation, owner digests, compliance reporting and a Today screen.

13 min read

Overview

Playbook turns an owner's standard operating routine ("open the cash drawer by 09:30, bill everything before close") into task instances that appear on each store manager's Today screen, get reminded and escalated if missed, complete themselves when the matching action happens elsewhere in Kagami, and roll up into owner digests and a compliance dashboard.

Kagami standard operating procedures SOP playbook editor and branch compliance dashboard

It is a pilot feature: the feature key is playbook (tier pro, pilot: true in web/src/lib/features/registry.ts). Code lives in web/src/lib/playbook/; see also Staff Operations, Communications and Roles & Permissions.

Piece What it does Main file
Scheduler Generates today's/tomorrow's task instances, advances status, reassigns on leave scheduler.ts
Triggers Event-driven tasks (low stock, SLA chats...) triggers.ts
Auto-complete Marks tasks done when the underlying action happens auto-complete.ts, completion-rules.ts
Escalation ladder Who is told, on which channel, when escalation.ts
Channels Push, WhatsApp, email (and bell for escalation alerts) dispatcher.ts, whatsapp-channel.ts, email-channel.ts
Owner digest / weekly summary Daily and Monday summaries owner-digest.ts, weekly-summary.ts
Onboarding playbook 9 one-off setup tasks for new orgs onboarding-playbook.ts, seed-onboarding.ts
Editor, compliance, prefs Owner UI server actions editor-actions.ts, compliance-actions.ts, preferences-actions.ts

How it runs (cron)

Job Mechanism Cadence Endpoint
Scheduler tick VM crontab on the prod host (scripts-vm/crontab) calling scripts-vm/cron-endpoint.sh */10 * * * * (UTC clock, every 10 minutes) /api/cron/playbook-scheduler
Weekly compliance summary No schedule found in the repo (not in scripts-vm/crontab, not in pg_cron migrations) Route comment says Mondays 08:00 /api/cron/playbook-weekly-summary
  • Other recurring Kagami jobs run on Supabase pg_cron (migration 0176_pg_cron_recurring_jobs.sql); Playbook is not among them.
  • Both routes accept GET or POST and authenticate with the CRON_SECRET env var, sent as x-cron-secret or Authorization: Bearer ... (web/src/lib/cron-auth.ts). Wrong secret returns 401; a thrown error returns 500 with the real message and is logged via captureError (tags cron.playbook_scheduler, cron.playbook_weekly_summary).
  • The scheduler tick is idempotent: instances are upserted on (template_id, location_id, due_date) with ignoreDuplicates, and notifications are de-duplicated through task_events.

What one scheduler tick does (in order)

  1. Load active task_templates joined to active playbooks; load active locations.
  2. Per location (errors are isolated per location and returned in errors[]): skip it if Playbook is off (isPlaybookEnabled), work out whether the store is closed today, build the staff list and approved leave, generate instances, advance statuses, reassign tasks of staff on leave.
  3. Evaluate count_zero completion rules (evaluateCountZeroRules).
  4. Sync onboarding tasks (syncAllOnboardingTasks).
  5. Evaluate trigger tasks (evaluatePlaybookTriggers).
  6. Run notifications and escalation (runPlaybookEscalations).
  7. Dispatch owner digests (dispatchDailyOwnerDigests).

Steps 3 to 7 swallow exceptions into console.error only; the HTTP response still says success: true. Check server logs, not just the JSON body.

Scheduler

Schedule shapes (task_templates.schedule)

frequency Matches
daily Every day
weekdays Monday to Friday
weekly days_of_week (1=Mon ... 7=Sun, 0 also accepted for Sunday); default Monday when empty
monthly day_of_month (default 1); a day beyond month length falls to the last day
once Matches every day in the current code
  • Candidate days are today and tomorrow in the location's timezone (locations.timezone, default Asia/Kolkata). due_at = due_time (default 10:00:00) in that zone, converted to UTC, and must fall within the next 24 h.
  • scope_location_ids (when non-empty) limits a template to those locations; this is how pilot locations are scoped.
  • A location is closed for the day if location_hours.is_closed is true for today's weekday or the holiday calendar (@/lib/closures) says so. Closed means no new instances, and open instances for today are set to skipped with skip_reason = 'store_closed', completion_source = 'auto'.

Status lifecycle (task_instances.status)

scheduled to due (within 60 min before due_at) to overdue (past due_at + grace_min, default grace 30) to terminal done or skipped. Advancement runs only for instances whose due_date is today.

Assignee resolution

  1. template.assignee_user_id if that person is not on approved leave.
  2. Otherwise the first member of memberships (org, location-scoped or org-wide) whose role equals template.role (a location_manager task also matches brand_manager) and who is not on leave.
  3. Otherwise the area manager / owner fallback (first org_owner, brand_manager or super_admin), with suggested_action = { reassigned_reason, required_role }.

Leave comes from time_off (approved, overlapping today) and staff_leave (approved). Open tasks of someone who goes on leave later are reassigned to an eligible substitute or the fallback, and a task_events row of type reassigned (channel system) is written.

Triggers (event-driven tasks)

A template with trigger_type set is checked every tick per location. If the condition fires, an instance for today is upserted as due with a suggested_action card (title, summary, button label, deep_link). When the condition clears, the open instance is set to done (completion_source = 'auto', suggested_action.auto_resolved = true).

trigger_type Fires when Defaults Card links to
low_stock stock_levels.qty_on_hand <= products.reorder_qty threshold 0 /dashboard/inventory
unreplied_chats_sla inbound_messages.read_at is null past SLA SLA = template grace_min or 60 min /dashboard/inbox
lapsed_clients Clients with a phone and no appointment in N days 60 days, 10 clients /dashboard/clients
unbilled_appointments_close Within 120 min of closing, completed appointments lack a paid invoice window 120 min /dashboard/billing
cash_count_missing Past opening time + grace and no shift opened today grace = grace_min or 30 /dashboard/cash
negative_audit_score A floor audit in the last 7 days scored below 80% 80% /dashboard/audit

buildDefaultTriggerTemplates() (triggers.ts) and TRIGGER_TEMPLATES_CATALOG (editor-schema.ts) define ready-made trigger templates in en/ta/hi. No production code path that inserts them was found (see below).

Completion and auto-complete

completion_rule.type decides how a task finishes:

Rule Completed by
cash_open, cash_close, day_opened, audit_submitted, stock_count_submitted markTaskDone() called from cash (lib/cash/actions.ts), salon day (lib/salon-day/actions.ts, auto-close.ts), floor audit (lib/audit/actions.ts) and inventory (lib/inventory/admin-actions.ts). Early completion is allowed. floor_audit and audit_submitted are interchangeable.
unreplied_chats_zero, unbilled_appointments_zero Scheduler tick, once the count is zero. A failed query never completes a task.
screen_ack, view_ack acknowledgeTaskViewAction exists but no caller was found outside lib/playbook, so in practice staff complete these manually.
manual Staff tap Complete on Today.

markTaskDone never throws and never fails the calling action (cash, billing and so on); it returns a reason (no_open_instance, location_mismatch, unauthorized, ...). It looks at open instances due today or earlier.

Notifications, escalation and caps

Default ladder (DEFAULT_ESCALATION_LADDER)

Used when a template has no ladder (escalation.ladder or legacy escalation.steps). A copy is frozen onto each instance as escalation_snapshot, so later template edits do not change in-flight tasks.

Step Offset from due_at Channels Recipient
assigned any time while scheduled or due push assignee
due_soon -30 min until due push assignee
overdue after grace_min (or status overdue) push, WhatsApp location manager
escalation +120 min WhatsApp area manager (brand/area manager, else owner)

Recipient fallbacks: assignee falls back to location manager then owner; area manager falls back to owner. Done or skipped tasks stop all steps.

Rules applied to every send

Rule Behaviour
De-duplication One send per (type, channel, recipient) per instance, from task_events
Quiet hours Default 21:00 to 08:00 in the store's timezone, per-user override in notification_prefs. Deferred sends are not recorded, so they go out on the first tick after quiet hours if the task is still open. Locked categories are not exempt from quiet hours
Opt-out notification_prefs.channels and category_channels are honoured, except categories in playbooks.locked_categories (default overdue, escalation)
Daily cap Per recipient: 5 individual sends, then 1 batched "N Playbook Updates" push (to /dashboard/today), then suppressed (task_events.status = 'suppressed')
Alert settings The owner's playbook_escalation alert (alert_settings, web/src/lib/alerts/registry.ts) can turn escalation steps off, restrict channels, add the in-app bell, or replace recipients by role or by name. Default channels push, WhatsApp, email

Channels

Channel Behaviour
Push notifyUsers (FCM); needs a registered device token
WhatsApp Staff phone from staff_members.phone (normalised, 10-digit Indian numbers get 91); needs messaging_settings.is_whatsapp_enabled for the brand; respects STOP opt-out. Uses a Meta template for scheduled sends, free text inside a 24 h inbound window. Missing phone is logged as failed_no_phone
Email Resend via RESEND_API_KEY, sender EMAIL_FROM; recipient email from auth.users. Missing address is failed_no_email. Without the key a mock id is returned and nothing is sent
Bell Only added by the escalation alert settings; creates a playbook_escalation notification

WhatsApp template names (UTILITY)

playbook_task_assigned, playbook_task_due_soon, playbook_task_overdue, playbook_owner_escalation, playbook_daily_digest, plus _ta and _hi variants (web/src/lib/messaging/templates.ts). Variables are first name, task title, store name and due time. Approval map DEFAULT_PLAYBOOK_TEMPLATE_APPROVALS: English and Tamil approved, Hindi pending. A pending or rejected localised template falls back to English (fallbackReason: not_approved); a Meta 132001 error at send time retries in English (runtime_api_fallback). Both are recorded in task_events.metadata. Status and sample text: vault/playbook/whatsapp-meta-templates.md.

Owner digest and weekly summary

Daily owner digest Weekly compliance summary
Code owner-digest.ts, called from every scheduler tick weekly-summary.ts, called by its own route
Covers Yesterday's instances for every location of the org Last 7 days (inclusive of both end dates), Asia/Kolkata dates
Content Per-store done/total/%, overdue items, skipped items with reasons On-time %, done/overdue/skipped, top and bottom store, top 3 overdue items, one suggested action
Skipped when Nothing scheduled; or all clear and not a Monday; or alert turned off No instances (unless force); or alert turned off
Controlled by Alert owner_daily_digest (owners only, default email) Alert weekly_compliance_summary (owners only, default email)
Languages Email en, ta, hi from orgs.default_language Same

Email carries the full report; other selected channels (bell, push, WhatsApp) get a short summary with a link, through sendDigestSummary. Configure under the owner alert settings (see Settings).

Onboarding playbook

ONBOARDING_PLAYBOOK_NAME = "Salon Onboarding" holds 9 one-off tasks (keys add_staff, set_hours, add_services, connect_whatsapp, first_cash_open, first_booking, first_invoice, first_floor_audit, invite_manager), with en, ta and hi copy. Role org_owner, due 18:00, grace 720 min, rule manual.

  • Seeded when an org younger than 14 days (ONBOARDING_WINDOW_DAYS) first loads Today (getOnboardingProgressAction); seedOnboardingPlaybook(..., force) can override the age check. Older orgs without it never see it.
  • Completion mirrors getSetupStatus() (lib/setup-status) plus operational milestones (first cash shift, booking, invoice, audit, extra manager) in onboarding-rules.ts; the scheduler re-syncs it each tick for the org's first active location.
  • The owner can dismiss the card (cookie), which hides it for that browser only.

Default "Standard Salon Day" playbook

seedDefaultPlaybook(orgId) (pilot.ts) creates playbook "Standard Salon Day" (is_default = true) with 10 templates, and tops up missing ones on re-run without overwriting edits. All role location_manager, channel push.

# Task Due Rule
1 Opening cash count opening time (default 09:30) cash_open
2 Open the day 10:00 day_opened
3 Review today's bookings 10:00 screen_ack
4 Reply to unanswered chats (optional) 14:00 unreplied_chats_zero
5 Bill all completed appointments 20:30 unbilled_appointments_zero
6 Closing cash count and close the day closing time (default 21:00) cash_close
7 Floor audit (weekly Mon) 10:00 audit_submitted
8 Weekly stock count (Sun) 19:00 stock_count_submitted
9 Review staff attendance and leave (weekly Mon, optional) 11:00 screen_ack
10 Monthly payroll check (day 25) 11:00 screen_ack

Enabling: a super admin turns on the Playbook pilot card in the admin console (app/(control)/admin/orgs/[orgId]), which calls enablePlaybookPilot (sets org_feature_overrides for playbook, seeds, runs the scheduler once; optional pilot location list sets scope_location_ids). Disabling keeps all data. isPlaybookEnabled checks the org override (or subscription via hasFeature), then requires an active default playbook and, if any template is location-scoped, that the location is in scope.

Localisation

Surface How the language is chosen
Today screen titles/descriptions resolveTaskI18n: user locale, then org default, then English, then any non-empty text. A small badge shows the language when it is a fallback
Task copy storage task_templates.title_i18n / description_i18n JSON keyed by language; empty or whitespace-only text counts as missing. The editor warns about missing en/ta/hi translations and offers suggestTaskTranslationAction
WhatsApp template staff_members.preferred_language (or metadata.locale), then English; Tamil and Hindi variants only if approved
Email Recipient locale, org default for digests
Push / bell text English only (built from title_i18n.en)

App locales are en, ta, hi (lib/i18n/types.ts); the notification_prefs.language CHECK and SupportedLocale in types.ts also list te, kn, ml, which nothing renders yet.

Today screen (/dashboard/today)

  • Page: app/(tenant)/dashboard/today/page.tsx. Visible to MANAGER_ROLES only (super admin, org owner, brand manager, location manager); stylists and front desk do not get it. It redirects to /dashboard when Playbook is off for the active store.
  • Shows tasks for the active store (not just the viewer's): Now (due/overdue, plus up to 10 open tasks from earlier days), Later today, This week (next 7 days), Done today with a progress bar. The screen switches from day to end-of-day mode EOD_LEAD_MIN = 60 minutes before the earliest open closing task (cash_close or unbilled_appointments_zero) is due; side panels show today's sales, exceptions and open/close state (today-overview.ts).
  • Per task: Start (opens deep_link?task_id=...), Complete, Skip, Reassign.

Completing, skipping, reassigning (lib/playbook/actions.ts)

Action Rule Audit
Complete If completion_rule.proof_required a photo is uploaded first (via /api/audits/photo); if gps_required the browser location is required. Errors are shown with the real reason task_events type completed, channel web
Skip A reason is mandatory. The UI offers STANDARD_SKIP_REASONS (e.g. "Not applicable today", "Staff shortage / emergency", "Will do tomorrow", "Other"); the server only checks it is non-empty type skipped
Reassign Owners/brand managers anywhere in the org; a location manager only within their store. Target must be an org member type reassigned with previous and new assignee

Data model

Migrations 0249 to 0253. All tables have RLS enabled, but the app reads and writes through the service-role client, so authorization is enforced in server-action code, not by RLS.

Table Key columns
playbooks org_id, brand_id, name, is_default, active, locked_categories (default {overdue,escalation})
task_templates playbook_id, title_i18n, description_i18n, role, assignee_user_id, schedule, due_time, grace_min, required, completion_rule, deep_link, channels, escalation, scope_location_ids, trigger_type, active, sort_order
task_instances template_id, org_id, brand_id, location_id, assignee_id, due_date, due_at, status (scheduled, due, done, overdue, skipped), completed_at, completed_by, completion_source (auto, manual), skip_reason, proof_url, proof_gps, suggested_action, escalation_snapshot. Unique on (template_id, location_id, due_date)
task_events instance_id (required), type, channel, recipient_id, status (pending, sent, delivered, read, failed, failed_no_phone, failed_no_email, suppressed, deferred), provider_message_id, metadata. Doubles as audit log and notification de-dupe
notification_prefs user_id, channels, quiet_start, quiet_end, language, category_channels, max_daily_cap

Related: alert_settings (owner alert config), org_feature_overrides, location_hours, time_off, staff_leave, staff_members.preferred_language, orgs.default_language.

Roles and permissions

Who Can
Super admin Everything below, plus enable/disable the pilot per org
Org owner Edit playbook, view compliance, lock notification categories, receive digests, reassign anywhere
Brand manager Edit playbook (PLAYBOOK_EDITOR_ROLES), view compliance (their brand), reassign anywhere in the org
Location manager Use Today, complete/skip, reassign within their store, view compliance for their store (COMPLIANCE_VIEWER_ROLES)
Anyone signed in Set their own quiet hours, channels and language at /dashboard/settings/notifications

Owner screens: /dashboard/settings/playbook (task editor: create, edit, toggle, clone, delete; deep link must come from a fixed list of 12 screens; daily-task soft cap warning at 12 per role; a 10-task library) and /dashboard/settings/playbook/compliance (on-time = done within due_at + grace; on-time % = on-time / (done + overdue), skipped excluded; streak = days at 80% or better). Template edits apply to future occurrences only.

Troubleshooting / where to look

Symptom Check
No tasks on Today Pilot enabled (org_feature_overrides), active default playbook, location in scope, store not closed today, scheduler logs in logs/cron.log on the VM, JSON response errors[]
Tasks never reminded task_events rows for the instance; assignee set; quiet hours; daily cap (suppressed); failed_no_phone / failed_no_email; WhatsApp enabled for the brand
Task did not auto-complete Template completion_rule.type; task_events type auto_completed; the calling action's location matches the task's location
Wrong language title_i18n has that language; staff_members.preferred_language; template approval map
No digest Alert owner_daily_digest enabled with channels; recipients by role; RESEND_API_KEY set