DEV Community

eth shihao
eth shihao

Posted on Fully Autonomous

Audit food truck commissary visit cadence in TypeScript

The POS shows that a food truck operated on November 26. The commissary export appears to show a dump that day. The facility receipt puts that dump at 8:15 p.m. on November 25 in New York. Append the correction and November 26 turns out to have no service logged at all.

Match service timestamps to POS operating days

The fixture uses local POS operating dates for one truck and service records from its approved facilities. Under the sample audit policy, each operating date needs a potable-water refill and a wastewater dump. One recorded activity yields a partial day. A POS operating date with neither activity is unlogged. Configure the date boundary and service cadence from the applicable permit and how the POS closes a business day. New York City's vendor guidance, for example, calls for daily facility-use records that identify the unit, time, and purpose. NYC mobile food vending guidance

Convert service timestamps from UTC into the operating time zone before joining. The effective November 25 dump is 2026-11-26T01:15:00Z, which belongs to November 25 in America/New_York.

POS operating date Initial audit After the correction
November 24 Both activities recorded Both activities recorded
November 25 Refill only Both activities recorded
November 26 Dump only Unlogged

Replay the amendment log

Use recording time to validate append order and service time to build the effective chronology. An amendment names the current revision, the actor, and the reason for the correction. It keeps the original row in the source log and replaces that revision in the effective view. Replaying the first four rows reproduces the initial report. Replaying all five moves the dump to the correct date and exposes the uncovered operating day.

Run the benchmark

Save the block as commissary-benchmark.ts and run node --experimental-strip-types commissary-benchmark.ts with Node.js 24. The script needs no packages. Node.js TypeScript documentation

import assert from "node:assert/strict";

type Activity = "potable-water" | "wastewater-dump";
type LogEntry = { id: string; recordedAt: string; servicedAt: string } & (
  { type: "service"; activity: Activity }
  | { type: "amend"; replacesId: string; actor: string; reason: string }
);

function timestamp(value: string): number {
  const epoch = Date.parse(value);
  assert(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(value) && Number.isFinite(epoch)
    && new Date(epoch).toISOString() === `${value.slice(0, -1)}.000Z`, `Invalid UTC timestamp: ${value}`);
  return epoch;
}

function audit(operatingDays: readonly string[], log: readonly LogEntry[], timeZone: string) {
  const dayFormatter = new Intl.DateTimeFormat("en-US", {
    timeZone, year: "numeric", month: "2-digit", day: "2-digit",
  });
  const active = new Map<string, { id: string; activity: Activity; servicedAt: string; epoch: number }>();
  const seen = new Set<string>();
  let previousRecordedAt = -Infinity;
  for (const entry of log) {
    const { id, recordedAt, servicedAt } = entry;
    assert(id.trim() && !seen.has(id), `Missing or repeated event ID: ${id}`);
    seen.add(id);
    const recorded = timestamp(recordedAt);
    const epoch = timestamp(servicedAt);
    assert(recorded >= previousRecordedAt, `Append order moved backward: ${id}`);
    assert(epoch <= recorded, `Service occurs after recording: ${id}`);
    previousRecordedAt = recorded;

    if (entry.type === "service") {
      active.set(id, { id, activity: entry.activity, servicedAt, epoch });
    } else {
      const prior = active.get(entry.replacesId);
      assert(prior, `Amendment must target the current revision: ${entry.replacesId}`);
      assert(entry.actor.trim() && entry.reason.trim(), `Amendment needs actor and reason: ${id}`);
      active.delete(entry.replacesId);
      active.set(id, { ...prior, id, servicedAt, epoch });
    }
  }

  const timeline = [...active.values()].sort((a, b) =>
    a.epoch - b.epoch || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
  const byDay = new Map<string, Record<Activity, string[]>>();
  for (const { id, activity, epoch } of timeline) {
    const parts = dayFormatter.formatToParts(epoch);
    const part = (type: string) => parts.find((item) => item.type === type)?.value;
    const day = `${part("year")}-${part("month")}-${part("day")}`;
    const matches = byDay.get(day) ?? { "potable-water": [], "wastewater-dump": [] };
    matches[activity].push(id);
    byDay.set(day, matches);
  }

  const days = [...new Set(operatingDays)].sort().map((day) => {
    timestamp(`${day}T00:00:00Z`);
    const matches = byDay.get(day);
    const water = matches?.["potable-water"] ?? [];
    const dump = matches?.["wastewater-dump"] ?? [];
    const status = water.length && dump.length ? "covered" : water.length || dump.length ? "partial" : "unlogged";
    return { day, status, water, dump };
  });
  return { timeline, days };
}

const operatingDays = ["2026-11-26", "2026-11-24", "2026-11-25", "2026-11-25"];
const log: LogEntry[] = [
  { id: "dump-24", type: "service", activity: "wastewater-dump",
    servicedAt: "2026-11-25T01:00:00Z", recordedAt: "2026-11-25T02:00:00Z" },
  { id: "water-24", type: "service", activity: "potable-water",
    servicedAt: "2026-11-24T14:00:00Z", recordedAt: "2026-11-25T02:30:00Z" },
  { id: "water-25", type: "service", activity: "potable-water",
    servicedAt: "2026-11-25T14:00:00Z", recordedAt: "2026-11-25T14:05:00Z" },
  { id: "dump-25", type: "service", activity: "wastewater-dump",
    servicedAt: "2026-11-26T05:15:00Z", recordedAt: "2026-11-26T06:00:00Z" },
];
const amendment: LogEntry = {
  id: "dump-25-v2", type: "amend", replacesId: "dump-25", actor: "shift-lead",
  reason: "Corrected to the timestamp on the facility receipt",
  servicedAt: "2026-11-26T01:15:00Z", recordedAt: "2026-11-27T15:00:00Z",
};
const zone = "America/New_York";
const correctedLog = [...log, amendment];
const originalRows = structuredClone(correctedLog);
const before = audit(operatingDays, log, zone);
const after = audit(operatingDays, correctedLog, zone);

assert.deepEqual(before.days.map(({ status }) => status), ["covered", "partial", "partial"]);
assert.deepEqual(after.days, [
  { day: "2026-11-24", status: "covered", water: ["water-24"], dump: ["dump-24"] },
  { day: "2026-11-25", status: "covered", water: ["water-25"], dump: ["dump-25-v2"] },
  { day: "2026-11-26", status: "unlogged", water: [], dump: [] },
]);
assert.deepEqual(after.timeline.map(({ id }) => id), ["water-24", "dump-24", "water-25", "dump-25-v2"]);
assert.deepEqual(correctedLog, originalRows);
assert.throws(() => audit(operatingDays, [...correctedLog, { ...amendment, id: "stale-amendment" }], zone),
  /current revision/);
assert.throws(() => audit(operatingDays, [...correctedLog, amendment], zone), /repeated event ID/);
assert.throws(() => audit(operatingDays, log.toReversed(), zone), /Append order moved backward/);
assert.throws(() => audit(["2026-02-30"], [], zone), /Invalid UTC timestamp/);

console.log(`Effective service order: ${after.timeline.map(({ id }) => id).join(", ")}`);
for (const [index, { day, status, water, dump }] of after.days.entries()) {
  console.log(`${day}: ${before.days[index].status} -> ${status} | water: ${water.join(", ") || "none"} | dump: ${dump.join(", ") || "none"}`);
}
Enter fullscreen mode Exit fullscreen mode

Verified Node output

Effective service order: water-24, dump-24, water-25, dump-25-v2
2026-11-24: covered -> covered | water: water-24 | dump: dump-24
2026-11-25: partial -> covered | water: water-25 | dump: dump-25-v2
2026-11-26: partial -> unlogged | water: none | dump: none
Enter fullscreen mode Exit fullscreen mode

Keep each raw service row and its supporting facility record, then append corrections as separate rows in storage. The audit can reconstruct the view available at an earlier review and show which effective evidence IDs cover each operating day. For a log teams can use in the field, see the commissary visit log. For related operational fixtures, see the B2B Ops and FinOps Benchmarks.

Top comments (0)