feat(workers): unify water + time worker tables into field_workers (cycle 10)
Deploy to route.crispygoat.com / deploy (push) Successful in 4m12s
Deploy to route.crispygoat.com / deploy (push) Successful in 4m12s
The two per-domain worker tables (water_irrigators, time_tracking_workers)
both carried a pin_hash, a brand, a role, and almost-identical columns.
Migrating a Tuxedo worker from one app to the other meant a duplicate
PIN. Field and admin staff complained; ops got inconsistent identity
records per domain.
Unify into a single field_workers table. Cycle 10 migration
0097_field_workers.sql:
- creates field_workers (id, brand_id, name, pin_hash, role with CHECK
IN ('worker','time_admin','irrigator','water_admin'),
language_preference, phone, notes, active, last_used_at, …)
- adds brand-scoped RLS, brand index, active index
- nullable field_worker_id on downstream tables, backfilled via
UPDATE … FROM, NULL count verified with RAISE EXCEPTION before
SET NOT NULL
- drops the two old tables and renames FK columns
(irrigator_id → field_worker_id, worker_id → field_worker_id)
- reissues the one-open-clock-in partial unique index against
field_worker_id
Application surface:
- All actions/services now read/write fieldWorkers. Drizzle's enum
literal infers tighter role types than the prior ad-hoc casts.
- The verify paths still filter to their respective domain roles so a
water-only worker can't be matched against a time-tracking PIN.
- API surface preserved: action function names didn't change.
- Seed file updated so QA reseeds work post-deploy.
Verified:
- npx tsc --noEmit clean
- npx vitest: 218 pass; 29 failures are pre-existing on main
- npm run lint: exit 0 (no new violations from cycle 10)
- npm run build: exit 0
- /water and /tuxedo/time-clock both 200 on dev
- DB verified via direct query: 20 field_workers, 200 water entries
with zero NULL field_worker_id, index rebuilt.
PR-reviewer: APPROVED.
This commit is contained in:
@@ -0,0 +1,322 @@
|
||||
-- ============================================================================
|
||||
-- 0097_field_workers.sql
|
||||
--
|
||||
-- Cycle 10 — unify `water_irrigators` and `time_tracking_workers` into a
|
||||
-- single `field_workers` table. One row per person, one `pin_hash`, one
|
||||
-- role vocabulary. Permanent fix for the silent-desync class of bugs
|
||||
-- (a worker changing their water PIN while their time PIN stays the same,
|
||||
-- or vice versa) and unlocks future domains (harvest reports, equipment
|
||||
-- logs) without yet another `*_workers` table.
|
||||
--
|
||||
-- Why one table:
|
||||
-- - Today two tables store the same person twice with separate PIN
|
||||
-- hashes and disjoint role vocabularies (`irrigator`/`water_admin` vs
|
||||
-- `worker`/`time_admin`). The Tuxedo worker PWA at `/water` already
|
||||
-- shows ONE PIN entry screen but under the hood has to look up the
|
||||
-- right row in the right table depending on which tab the worker
|
||||
-- hits (Cycle 4 attempted unification via a best-effort cross-call
|
||||
-- in `MobileWaterApp.handlePinSubmit`).
|
||||
-- - Phase 2 (separate cycle) collapses the two session cookies and
|
||||
-- replaces the dual verify actions with a single `verifyFieldWorkerPin`.
|
||||
-- This cycle ships the schema + action layer; UI behavior is preserved.
|
||||
--
|
||||
-- Schema:
|
||||
-- id UUID PK (new — old worker IDs are not reused)
|
||||
-- brand_id UUID NOT NULL → brands(id) ON DELETE CASCADE
|
||||
-- name TEXT NOT NULL
|
||||
-- pin_hash TEXT NOT NULL — scrypt self-describing format
|
||||
-- from `@/lib/water-log-pin`
|
||||
-- role TEXT NOT NULL DEFAULT 'worker'
|
||||
-- — union of all four old role values
|
||||
-- language_preference TEXT NOT NULL DEFAULT 'en'
|
||||
-- phone TEXT NULL (water-only; null for time-only workers)
|
||||
-- notes TEXT NULL (water-only)
|
||||
-- active BOOLEAN NOT NULL DEFAULT true
|
||||
-- last_used_at TIMESTAMPTZ NULL
|
||||
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
-- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
--
|
||||
-- Migration behavior (idempotent — safe to re-run):
|
||||
-- 1. Create field_workers + brand-scoped RLS.
|
||||
-- 2. Add nullable `field_worker_id` columns on the four downstream
|
||||
-- tables that currently FK into the old worker tables.
|
||||
-- 3. Backfill: collapse water + time rows that share a (brand_id,
|
||||
-- lower(trim(name))) key. PIN conflicts → water's wins (water is
|
||||
-- the older surface, preserves existing auth). Names unique to
|
||||
-- one side → copy verbatim.
|
||||
-- 4. Verify every downstream FK row got a field_worker_id (must be 0
|
||||
-- NULL before we make the column NOT NULL).
|
||||
-- 5. Drop the old worker tables; CASCADE drops the OLD FK columns
|
||||
-- (irrigator_id, worker_id) entirely. We do not preserve them —
|
||||
-- the new `field_worker_id` columns are populated and become the
|
||||
-- canonical reference.
|
||||
-- 6. Reissue the partial unique index
|
||||
-- `time_tracking_logs_one_open_per_worker_idx` against
|
||||
-- `field_worker_id` (DB-level invariant: at most one open
|
||||
-- clock-in per worker; preserved).
|
||||
--
|
||||
-- DESTRUCTIVE: drops `water_irrigators` and `time_tracking_workers`
|
||||
-- entirely. The pin hashes are preserved verbatim into field_workers,
|
||||
-- so no worker has to re-learn their PIN after deploy. Old IDs are not
|
||||
-- preserved — every downstream FK is re-pointed to the new IDs. This
|
||||
-- matters for any external system that referenced the old UUIDs; none
|
||||
-- of our surfaces do.
|
||||
--
|
||||
-- Customer impact (Tuxedo has 10 water + 10 time workers today, no name
|
||||
-- overlap):
|
||||
-- - After deploy: 20 `field_workers` rows, every entry/log row
|
||||
-- re-pointed at the right new UUID. Workers do NOT need to re-enter
|
||||
-- a PIN. The water PIN entry screen continues to work; the time
|
||||
-- PIN entry screen continues to work. The cross-call best-effort
|
||||
-- in `MobileWaterApp` continues to work.
|
||||
-- - The role select in `/admin/water-log/users/[id]` will be tightened
|
||||
-- to drop `time_admin` (water-only workers shouldn't get time powers).
|
||||
-- The role select in `/admin/time-tracking` will be tightened to drop
|
||||
-- the silently-rejected `supervisor`/`admin` values that the explore
|
||||
-- audit caught.
|
||||
-- ============================================================================
|
||||
|
||||
-- ── 1. Create field_workers ────────────────────────────────────────────────
|
||||
|
||||
CREATE TABLE IF NOT EXISTS field_workers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
brand_id UUID NOT NULL REFERENCES brands(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
pin_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'worker'
|
||||
CHECK (role IN ('worker', 'time_admin', 'irrigator', 'water_admin')),
|
||||
language_preference TEXT NOT NULL DEFAULT 'en',
|
||||
phone TEXT,
|
||||
notes TEXT,
|
||||
active BOOLEAN NOT NULL DEFAULT true,
|
||||
last_used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS field_workers_brand_idx
|
||||
ON field_workers(brand_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS field_workers_brand_active_idx
|
||||
ON field_workers(brand_id, active)
|
||||
WHERE active = true;
|
||||
|
||||
COMMENT ON TABLE field_workers IS
|
||||
'Cycle 10 — unified worker table replacing water_irrigators + time_tracking_workers. '
|
||||
'One row per person, one pin_hash. Role vocabulary: worker, time_admin, irrigator, water_admin. '
|
||||
'See db/migrations/0097_field_workers.sql for the unification rationale.';
|
||||
|
||||
DROP TRIGGER IF EXISTS field_workers_set_updated_at ON field_workers;
|
||||
CREATE TRIGGER field_workers_set_updated_at
|
||||
BEFORE UPDATE ON field_workers
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
|
||||
-- Brand-scoped RLS (mirrors 0096's smartsheet_workspace pattern).
|
||||
ALTER TABLE field_workers ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
DROP POLICY IF EXISTS tenant_isolation ON field_workers;
|
||||
CREATE POLICY tenant_isolation ON field_workers FOR ALL
|
||||
USING (brand_id = current_brand_id() OR is_platform_admin())
|
||||
WITH CHECK (brand_id = current_brand_id() OR is_platform_admin());
|
||||
|
||||
-- ── 2. Add nullable field_worker_id columns on the four downstream tables ─
|
||||
|
||||
ALTER TABLE water_log_entries
|
||||
ADD COLUMN IF NOT EXISTS field_worker_id UUID
|
||||
REFERENCES field_workers(id) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE water_sessions
|
||||
ADD COLUMN IF NOT EXISTS field_worker_id UUID
|
||||
REFERENCES field_workers(id) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE time_tracking_logs
|
||||
ADD COLUMN IF NOT EXISTS field_worker_id UUID
|
||||
REFERENCES field_workers(id) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE time_tracking_notification_log
|
||||
ADD COLUMN IF NOT EXISTS field_worker_id UUID
|
||||
REFERENCES field_workers(id) ON DELETE SET NULL;
|
||||
|
||||
-- ── 3. Backfill field_workers from the two old tables ─────────────────────
|
||||
--
|
||||
-- Insertion order is intentional: WATER first so its rows win on the
|
||||
-- (brand_id, lower(trim(name))) key (we use ON CONFLICT DO NOTHING).
|
||||
-- Time-tracking rows are inserted second; if the (brand_id, name) key
|
||||
-- already has a water row, the time row is dropped (water's PIN wins).
|
||||
|
||||
INSERT INTO field_workers (
|
||||
id, brand_id, name, pin_hash, role, language_preference,
|
||||
phone, notes, active, last_used_at, created_at
|
||||
)
|
||||
SELECT
|
||||
wi.id,
|
||||
wi.brand_id,
|
||||
wi.name,
|
||||
wi.pin_hash,
|
||||
wi.role,
|
||||
wi.language_preference,
|
||||
wi.phone,
|
||||
wi.notes,
|
||||
wi.active,
|
||||
wi.last_used_at,
|
||||
wi.created_at
|
||||
FROM water_irrigators wi
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM field_workers fw
|
||||
WHERE fw.brand_id = wi.brand_id
|
||||
AND lower(trim(fw.name)) = lower(trim(wi.name))
|
||||
);
|
||||
|
||||
INSERT INTO field_workers (
|
||||
id, brand_id, name, pin_hash, role, language_preference,
|
||||
phone, notes, active, last_used_at, created_at
|
||||
)
|
||||
SELECT
|
||||
tw.id,
|
||||
tw.brand_id,
|
||||
tw.name,
|
||||
tw.pin AS pin_hash,
|
||||
tw.role,
|
||||
tw.lang AS language_preference,
|
||||
NULL AS phone,
|
||||
NULL AS notes,
|
||||
tw.active,
|
||||
tw.last_used_at,
|
||||
tw.created_at
|
||||
FROM time_tracking_workers tw
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM field_workers fw
|
||||
WHERE fw.brand_id = tw.brand_id
|
||||
AND lower(trim(fw.name)) = lower(trim(tw.name))
|
||||
);
|
||||
|
||||
-- If a (brand, name) pair was in BOTH tables, the time-tracking row was
|
||||
-- skipped above. Re-insert only the conflicting rows using water's pin_hash
|
||||
-- is unnecessary (we already have water's row); this block is a no-op
|
||||
-- safety check.
|
||||
|
||||
-- ── 4. Backfill field_worker_id on downstream tables ──────────────────────
|
||||
--
|
||||
-- Join key: (brand_id, lower(trim(name))). The water side uses
|
||||
-- water_log_entries.irrigator_id → water_irrigators; the time side uses
|
||||
-- time_tracking_logs.worker_id → time_tracking_workers.
|
||||
|
||||
UPDATE water_log_entries wle
|
||||
SET field_worker_id = fw.id
|
||||
FROM water_irrigators wi, field_workers fw
|
||||
WHERE wle.irrigator_id = wi.id
|
||||
AND fw.brand_id = wi.brand_id
|
||||
AND lower(trim(fw.name)) = lower(trim(wi.name))
|
||||
AND wle.field_worker_id IS NULL;
|
||||
|
||||
UPDATE water_sessions ws
|
||||
SET field_worker_id = fw.id
|
||||
FROM water_irrigators wi, field_workers fw
|
||||
WHERE ws.irrigator_id = wi.id
|
||||
AND fw.brand_id = wi.brand_id
|
||||
AND lower(trim(fw.name)) = lower(trim(wi.name))
|
||||
AND ws.field_worker_id IS NULL;
|
||||
|
||||
UPDATE time_tracking_logs ttl
|
||||
SET field_worker_id = fw.id
|
||||
FROM time_tracking_workers tw, field_workers fw
|
||||
WHERE ttl.worker_id = tw.id
|
||||
AND fw.brand_id = tw.brand_id
|
||||
AND lower(trim(fw.name)) = lower(trim(tw.name))
|
||||
AND ttl.field_worker_id IS NULL;
|
||||
|
||||
UPDATE time_tracking_notification_log tnl
|
||||
SET field_worker_id = fw.id
|
||||
FROM time_tracking_workers tw, field_workers fw
|
||||
WHERE tnl.worker_id = tw.id
|
||||
AND fw.brand_id = tw.brand_id
|
||||
AND lower(trim(fw.name)) = lower(trim(tw.name))
|
||||
AND tnl.field_worker_id IS NULL;
|
||||
|
||||
-- ── 5. Verification: every downstream row must have a field_worker_id ────
|
||||
--
|
||||
-- If any of these SELECTs returns a non-zero count, the migration will
|
||||
-- leave NULL FKs. The CHECK ensures the migration FAILS LOUDLY in that
|
||||
-- case rather than silently dropping data on the cascade in step 7.
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
water_entries_null INTEGER;
|
||||
water_sessions_null INTEGER;
|
||||
time_logs_null INTEGER;
|
||||
time_notif_null INTEGER;
|
||||
BEGIN
|
||||
SELECT count(*) INTO water_entries_null FROM water_log_entries WHERE field_worker_id IS NULL;
|
||||
SELECT count(*) INTO water_sessions_null FROM water_sessions WHERE field_worker_id IS NULL;
|
||||
SELECT count(*) INTO time_logs_null FROM time_tracking_logs WHERE field_worker_id IS NULL;
|
||||
SELECT count(*) INTO time_notif_null FROM time_tracking_notification_log WHERE field_worker_id IS NULL;
|
||||
|
||||
IF water_entries_null > 0 THEN
|
||||
RAISE EXCEPTION 'water_log_entries has % rows with NULL field_worker_id after backfill', water_entries_null;
|
||||
END IF;
|
||||
IF water_sessions_null > 0 THEN
|
||||
RAISE EXCEPTION 'water_sessions has % rows with NULL field_worker_id after backfill', water_sessions_null;
|
||||
END IF;
|
||||
IF time_logs_null > 0 THEN
|
||||
RAISE EXCEPTION 'time_tracking_logs has % rows with NULL field_worker_id after backfill', time_logs_null;
|
||||
END IF;
|
||||
IF time_notif_null > 0 THEN
|
||||
RAISE EXCEPTION 'time_tracking_notification_log has % rows with NULL field_worker_id after backfill', time_notif_null;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ── 6. Make field_worker_id NOT NULL (we've verified backfill is complete)
|
||||
|
||||
ALTER TABLE water_log_entries
|
||||
ALTER COLUMN field_worker_id SET NOT NULL;
|
||||
|
||||
ALTER TABLE water_sessions
|
||||
ALTER COLUMN field_worker_id SET NOT NULL;
|
||||
|
||||
ALTER TABLE time_tracking_logs
|
||||
ALTER COLUMN field_worker_id SET NOT NULL;
|
||||
|
||||
-- time_tracking_notification_log.worker_id was originally nullable
|
||||
-- (ON DELETE SET NULL on the old FK); preserve that contract.
|
||||
|
||||
-- ── 7. Drop the old worker tables ────────────────────────────────────────
|
||||
--
|
||||
-- CASCADE removes FK constraints and dependent indexes/triggers, but does
|
||||
-- NOT drop the foreign-key columns from unrelated tables. Drop those
|
||||
-- explicitly so downstream tables carry only the new `field_worker_id`.
|
||||
|
||||
DROP TABLE IF EXISTS water_irrigators CASCADE;
|
||||
DROP TABLE IF EXISTS time_tracking_workers CASCADE;
|
||||
|
||||
ALTER TABLE water_log_entries DROP COLUMN IF EXISTS irrigator_id;
|
||||
ALTER TABLE water_sessions DROP COLUMN IF EXISTS irrigator_id;
|
||||
ALTER TABLE time_tracking_logs DROP COLUMN IF EXISTS worker_id;
|
||||
-- time_tracking_notification_log.worker_id was originally nullable
|
||||
-- (ON DELETE SET NULL); we keep the column shape and just drop the old FK
|
||||
-- constraint. The new `field_worker_id` column was added above and
|
||||
-- backfilled. We drop the old column only if the new one is populated.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM time_tracking_notification_log WHERE field_worker_id IS NULL
|
||||
) THEN
|
||||
ALTER TABLE time_tracking_notification_log DROP COLUMN worker_id;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ── 8. Reissue the partial unique index on the new column ─────────────────
|
||||
--
|
||||
-- DB-level invariant preserved: at most one open clock-in per worker.
|
||||
|
||||
DROP INDEX IF EXISTS time_tracking_logs_one_open_per_worker_idx;
|
||||
|
||||
CREATE UNIQUE INDEX time_tracking_logs_one_open_per_worker_idx
|
||||
ON time_tracking_logs (field_worker_id)
|
||||
WHERE clock_out IS NULL;
|
||||
|
||||
-- ── 9. Summary of row counts after migration (for the audit log) ─────────
|
||||
--
|
||||
-- Run this manually after the migration completes if you want to confirm:
|
||||
-- SELECT (SELECT count(*) FROM field_workers) AS field_workers,
|
||||
-- (SELECT count(*) FROM water_log_entries WHERE field_worker_id IS NULL) AS wle_null,
|
||||
-- (SELECT count(*) FROM time_tracking_logs WHERE field_worker_id IS NULL) AS ttl_null;
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Cycle 10 — Unified field worker table.
|
||||
*
|
||||
* Replaces `water_irrigators` + `time_tracking_workers` (one row per
|
||||
* person with two independent PIN hashes) with one row, one PIN hash,
|
||||
* one role vocabulary.
|
||||
*
|
||||
* Role vocabulary (matches the CHECK constraint in
|
||||
* `db/migrations/0097_field_workers.sql`):
|
||||
* - `worker` — default; can submit water entries + clock in/out
|
||||
* - `time_admin` — can manage time-tracking tasks, settings, and
|
||||
* other time workers
|
||||
* - `irrigator` — legacy role from `water_irrigators`; same powers
|
||||
* as `worker` but kept distinct for UI filtering
|
||||
* (the water admin UI shows this label)
|
||||
* - `water_admin` — can manage headgates, water workers, and water
|
||||
* entries
|
||||
*
|
||||
* The PIN is a scrypt self-describing hash from `@/lib/water-log-pin`
|
||||
* (column name `pin_hash`, NOT `pin` — see cycle 10 migration for the
|
||||
* rename).
|
||||
*/
|
||||
import { boolean, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||
import { brands } from "./brands";
|
||||
|
||||
export const fieldWorkers = pgTable(
|
||||
"field_workers",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
brandId: uuid("brand_id")
|
||||
.notNull()
|
||||
.references(() => brands.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
pinHash: text("pin_hash").notNull(),
|
||||
role: text("role", {
|
||||
enum: ["worker", "time_admin", "irrigator", "water_admin"],
|
||||
})
|
||||
.notNull()
|
||||
.default("worker"),
|
||||
languagePreference: text("language_preference").notNull().default("en"),
|
||||
phone: text("phone"),
|
||||
notes: text("notes"),
|
||||
active: boolean("active").notNull().default(true),
|
||||
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(t) => ({
|
||||
brandIdx: index("field_workers_brand_idx").on(t.brandId),
|
||||
}),
|
||||
);
|
||||
|
||||
export type FieldWorker = typeof fieldWorkers.$inferSelect;
|
||||
export type NewFieldWorker = typeof fieldWorkers.$inferInsert;
|
||||
export type FieldWorkerRole = FieldWorker["role"];
|
||||
@@ -14,6 +14,7 @@ export * from "./water-log";
|
||||
export * from "./communications";
|
||||
export * from "./marketing";
|
||||
export * from "./time-tracking";
|
||||
export * from "./field-workers";
|
||||
export * from "./shipping";
|
||||
export * from "./support";
|
||||
export * from "./files";
|
||||
+26
-29
@@ -5,6 +5,13 @@
|
||||
* Cycle 7: the encrypted token columns on
|
||||
* `time_tracking_smartsheet_config` moved to `smartsheet_workspace`
|
||||
* (see `db/schema/smartsheet-workspace.ts`).
|
||||
*
|
||||
* Cycle 10: the `time_tracking_workers` table was DROPPED in
|
||||
* `db/migrations/0097_field_workers.sql`. Worker records now live
|
||||
* in `field_workers` (see `db/schema/field-workers.ts`). The
|
||||
* `worker_id` column on the downstream tables
|
||||
* (`time_tracking_logs`, `time_tracking_notification_log`) was
|
||||
* renamed to `field_worker_id` and the FK repointed.
|
||||
*/
|
||||
import {
|
||||
pgTable,
|
||||
@@ -18,6 +25,7 @@ import {
|
||||
jsonb,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { brands } from "./brands";
|
||||
import { fieldWorkers } from "./field-workers";
|
||||
|
||||
export const timeTrackingSettings = pgTable(
|
||||
"time_tracking_settings",
|
||||
@@ -55,29 +63,12 @@ export const timeTrackingSettings = pgTable(
|
||||
},
|
||||
);
|
||||
|
||||
export const timeTrackingWorkers = pgTable(
|
||||
"time_tracking_workers",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
brandId: uuid("brand_id")
|
||||
.notNull()
|
||||
.references(() => brands.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
role: text("role", { enum: ["worker", "time_admin"] })
|
||||
.notNull()
|
||||
.default("worker"),
|
||||
lang: text("lang").notNull().default("en"),
|
||||
pin: text("pin").notNull(),
|
||||
active: boolean("active").notNull().default(true),
|
||||
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(t) => ({
|
||||
brandIdx: index("time_tracking_workers_brand_idx").on(t.brandId),
|
||||
}),
|
||||
);
|
||||
// Cycle 10: `time_tracking_workers` table was DROPPED in
|
||||
// 0097_field_workers.sql. Worker records now live in `field_workers`
|
||||
// (see `db/schema/field-workers.ts`). Any code that previously read
|
||||
// from timeTrackingWorkers should now read from fieldWorkers and
|
||||
// filter by role = 'worker' or 'time_admin' if it needs time-only
|
||||
// workers.
|
||||
|
||||
export const timeTrackingTasks = pgTable(
|
||||
"time_tracking_tasks",
|
||||
@@ -109,9 +100,10 @@ export const timeTrackingLogs = pgTable(
|
||||
brandId: uuid("brand_id")
|
||||
.notNull()
|
||||
.references(() => brands.id, { onDelete: "cascade" }),
|
||||
workerId: uuid("worker_id")
|
||||
/** Cycle 10: was `worker_id` (FK → time_tracking_workers); now unified. */
|
||||
fieldWorkerId: uuid("field_worker_id")
|
||||
.notNull()
|
||||
.references(() => timeTrackingWorkers.id, { onDelete: "cascade" }),
|
||||
.references(() => fieldWorkers.id, { onDelete: "cascade" }),
|
||||
taskId: uuid("task_id").references(() => timeTrackingTasks.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
@@ -129,7 +121,9 @@ export const timeTrackingLogs = pgTable(
|
||||
},
|
||||
(t) => ({
|
||||
brandIdx: index("time_tracking_logs_brand_idx").on(t.brandId),
|
||||
workerIdx: index("time_tracking_logs_worker_idx").on(t.workerId),
|
||||
fieldWorkerIdx: index("time_tracking_logs_field_worker_idx").on(
|
||||
t.fieldWorkerId,
|
||||
),
|
||||
clockInIdx: index("time_tracking_logs_clock_in_idx").on(t.clockIn),
|
||||
}),
|
||||
);
|
||||
@@ -141,8 +135,9 @@ export const timeTrackingNotificationLog = pgTable(
|
||||
brandId: uuid("brand_id")
|
||||
.notNull()
|
||||
.references(() => brands.id, { onDelete: "cascade" }),
|
||||
workerId: uuid("worker_id").references(
|
||||
() => timeTrackingWorkers.id,
|
||||
/** Cycle 10: was `worker_id` (FK → time_tracking_workers); now unified. */
|
||||
fieldWorkerId: uuid("field_worker_id").references(
|
||||
() => fieldWorkers.id,
|
||||
{ onDelete: "set null" },
|
||||
),
|
||||
notificationType: text("notification_type").notNull(),
|
||||
@@ -160,7 +155,9 @@ export const timeTrackingNotificationLog = pgTable(
|
||||
);
|
||||
|
||||
export type TimeTrackingSettings = typeof timeTrackingSettings.$inferSelect;
|
||||
export type TimeTrackingWorker = typeof timeTrackingWorkers.$inferSelect;
|
||||
// Cycle 10: `TimeTrackingWorker` was removed. Use `FieldWorker` from
|
||||
// `./field-workers` instead; filter by role = 'worker' or 'time_admin'
|
||||
// if you need time-only workers.
|
||||
export type TimeTrackingTask = typeof timeTrackingTasks.$inferSelect;
|
||||
export type TimeTrackingLog = typeof timeTrackingLogs.$inferSelect;
|
||||
export type TimeTrackingNotificationLog =
|
||||
|
||||
+20
-35
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* Six tables, all brand-scoped with RLS:
|
||||
* - water_headgates — physical gates a measurement is tied to
|
||||
* - water_irrigators — PIN-authenticated field workers
|
||||
* - field_workers — unified worker table (cycle 10; replaces
|
||||
* water_irrigators + time_tracking_workers)
|
||||
* - water_sessions — short-lived PIN sessions for irrigators
|
||||
* - water_log_entries — the actual reading logs
|
||||
* - water_alert_log — high/low threshold alert history
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { brands } from "./brands";
|
||||
import { adminUsers } from "./brands";
|
||||
import { fieldWorkers } from "./field-workers";
|
||||
|
||||
// Cycle 7: the `bytea` customType used to live here for the
|
||||
// encrypted Smartsheet token columns. Those columns moved to
|
||||
@@ -66,40 +68,21 @@ export const waterHeadgates = pgTable(
|
||||
}),
|
||||
);
|
||||
|
||||
export const waterIrrigators = pgTable(
|
||||
"water_irrigators",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
brandId: uuid("brand_id")
|
||||
.notNull()
|
||||
.references(() => brands.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
pinHash: text("pin_hash").notNull(),
|
||||
languagePreference: text("language_preference")
|
||||
.notNull()
|
||||
.default("en"),
|
||||
/** "irrigator" submits entries only, "water_admin" can manage the brand. */
|
||||
role: text("role").notNull().default("irrigator"),
|
||||
phone: text("phone"),
|
||||
notes: text("notes"),
|
||||
active: boolean("active").notNull().default(true),
|
||||
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(t) => ({
|
||||
brandIdx: index("water_irrigators_brand_idx").on(t.brandId),
|
||||
}),
|
||||
);
|
||||
// Cycle 10: water_irrigators table was DROPPED in
|
||||
// 0097_field_workers.sql. Worker records now live in
|
||||
// `field_workers` (see `db/schema/field-workers.ts`).
|
||||
// Any code that previously read from waterIrrigators should now
|
||||
// read from fieldWorkers and filter by role = 'irrigator' or
|
||||
// 'water_admin' if it needs water-only workers.
|
||||
|
||||
export const waterSessions = pgTable(
|
||||
"water_sessions",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
irrigatorId: uuid("irrigator_id")
|
||||
/** Cycle 10: was `irrigator_id` (FK → water_irrigators); now unified. */
|
||||
fieldWorkerId: uuid("field_worker_id")
|
||||
.notNull()
|
||||
.references(() => waterIrrigators.id, { onDelete: "cascade" }),
|
||||
.references(() => fieldWorkers.id, { onDelete: "cascade" }),
|
||||
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
@@ -117,9 +100,10 @@ export const waterLogEntries = pgTable(
|
||||
headgateId: uuid("headgate_id")
|
||||
.notNull()
|
||||
.references(() => waterHeadgates.id, { onDelete: "cascade" }),
|
||||
irrigatorId: uuid("irrigator_id")
|
||||
/** Cycle 10: was `irrigator_id` (FK → water_irrigators); now unified. */
|
||||
fieldWorkerId: uuid("field_worker_id")
|
||||
.notNull()
|
||||
.references(() => waterIrrigators.id, { onDelete: "cascade" }),
|
||||
.references(() => fieldWorkers.id, { onDelete: "cascade" }),
|
||||
/** Raw measurement value, in the entry's `unit`. */
|
||||
measurement: numeric("measurement").notNull(),
|
||||
unit: text("unit").notNull(),
|
||||
@@ -146,8 +130,8 @@ export const waterLogEntries = pgTable(
|
||||
t.brandId,
|
||||
t.loggedDate,
|
||||
),
|
||||
irrigatorIdx: index("water_log_entries_irrigator_idx").on(
|
||||
t.irrigatorId,
|
||||
fieldWorkerIdx: index("water_log_entries_field_worker_idx").on(
|
||||
t.fieldWorkerId,
|
||||
t.loggedAt,
|
||||
),
|
||||
}),
|
||||
@@ -248,8 +232,9 @@ export const waterAuditLog = pgTable(
|
||||
export type WaterHeadgate = typeof waterHeadgates.$inferSelect;
|
||||
export type WaterHeadgateInsert = typeof waterHeadgates.$inferInsert;
|
||||
|
||||
export type WaterIrrigator = typeof waterIrrigators.$inferSelect;
|
||||
export type WaterIrrigatorInsert = typeof waterIrrigators.$inferInsert;
|
||||
// Cycle 10: `WaterIrrigator` / `WaterIrrigatorInsert` were removed.
|
||||
// Use `FieldWorker` from `./field-workers` instead; filter by role =
|
||||
// 'irrigator' or 'water_admin' if you need water-only workers.
|
||||
|
||||
export type WaterSession = typeof waterSessions.$inferSelect;
|
||||
export type WaterLogEntry = typeof waterLogEntries.$inferSelect;
|
||||
|
||||
@@ -307,13 +307,23 @@ ON CONFLICT DO NOTHING;
|
||||
-- ============================================================================
|
||||
-- 11. Time tracking infrastructure + logs
|
||||
-- ============================================================================
|
||||
INSERT INTO time_tracking_workers (id, brand_id, name, role, pin, lang, active)
|
||||
-- Cycle 10: workers are unified into `field_workers`. We seed both the
|
||||
-- former `time_tracking_workers` (role worker|time_admin) and the former
|
||||
-- `water_irrigators` (role irrigator|water_admin) into the same table.
|
||||
INSERT INTO field_workers (id, brand_id, name, role, pin_hash, language_preference, active)
|
||||
SELECT gen_random_uuid(), b.id, 'Worker ' || i, CASE (i%2) WHEN 0 THEN 'worker' ELSE 'time_admin' END, lpad((1000+i)::text, 4, '0'), 'en', true
|
||||
FROM brands b
|
||||
CROSS JOIN generate_series(1, 5) AS i
|
||||
WHERE b.id IN ('11111111-1111-1111-1111-111111111111','22222222-2222-2222-2222-222222222222')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO field_workers (id, brand_id, name, role, pin_hash, language_preference, phone, active)
|
||||
SELECT gen_random_uuid(), b.id, 'Irrigator ' || i, 'irrigator', 'placeholder-pin-hash', 'en', '+15550100000', true
|
||||
FROM brands b
|
||||
CROSS JOIN generate_series(1, 5) AS i
|
||||
WHERE b.id IN ('11111111-1111-1111-1111-111111111111','22222222-2222-2222-2222-222222222222')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO time_tracking_tasks (id, brand_id, name, unit, sort_order, active)
|
||||
SELECT gen_random_uuid(), b.id, 'Task ' || i, CASE (i%3) WHEN 0 THEN 'hours' WHEN 1 THEN 'pieces' ELSE 'units' END, i, true
|
||||
FROM brands b
|
||||
@@ -321,10 +331,10 @@ CROSS JOIN generate_series(1, 8) AS i
|
||||
WHERE b.id IN ('11111111-1111-1111-1111-111111111111','22222222-2222-2222-2222-222222222222')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO time_tracking_logs (brand_id, worker_id, task_id, task_name, clock_in, clock_out, lunch_break_minutes, notes)
|
||||
INSERT INTO time_tracking_logs (brand_id, field_worker_id, task_id, task_name, clock_in, clock_out, lunch_break_minutes, notes)
|
||||
SELECT
|
||||
b.id,
|
||||
(SELECT id FROM time_tracking_workers WHERE brand_id = b.id ORDER BY random() LIMIT 1),
|
||||
(SELECT id FROM field_workers WHERE brand_id = b.id AND role IN ('worker','time_admin') ORDER BY random() LIMIT 1),
|
||||
(SELECT id FROM time_tracking_tasks WHERE brand_id = b.id ORDER BY random() LIMIT 1),
|
||||
'Task ' || (1 + (i % 8)),
|
||||
(NOW() - ((i % 30) || ' days')::interval - ((i % 8) || ' hours')::interval),
|
||||
@@ -346,18 +356,11 @@ CROSS JOIN generate_series(1, 5) AS i
|
||||
WHERE b.id IN ('11111111-1111-1111-1111-111111111111','22222222-2222-2222-2222-222222222222')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO water_irrigators (id, brand_id, name, pin_hash, language_preference, role, phone, active)
|
||||
SELECT gen_random_uuid(), b.id, 'Irrigator ' || i, 'placeholder-pin-hash', 'en', 'irrigator', '+15550100000', true
|
||||
FROM brands b
|
||||
CROSS JOIN generate_series(1, 5) AS i
|
||||
WHERE b.id IN ('11111111-1111-1111-1111-111111111111','22222222-2222-2222-2222-222222222222')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO water_log_entries (brand_id, headgate_id, irrigator_id, measurement, unit, logged_at, logged_by, method, total_gallons, notes)
|
||||
INSERT INTO water_log_entries (brand_id, headgate_id, field_worker_id, measurement, unit, logged_at, logged_by, method, total_gallons, notes)
|
||||
SELECT
|
||||
b.id,
|
||||
(SELECT id FROM water_headgates WHERE brand_id = b.id ORDER BY random() LIMIT 1),
|
||||
(SELECT id FROM water_irrigators WHERE brand_id = b.id ORDER BY random() LIMIT 1),
|
||||
(SELECT id FROM field_workers WHERE brand_id = b.id AND role IN ('irrigator','water_admin') ORDER BY random() LIMIT 1),
|
||||
(50 + (i * 7) % 200)::numeric,
|
||||
'GPM',
|
||||
NOW() - ((i % 14) || ' days')::interval,
|
||||
|
||||
Reference in New Issue
Block a user