BT San Technology

19 November 2026

Multi-level approval workflows: designing send-back, revision and delegated approvers

26 min read · Websites and web apps

Illustration: two people passing a blue document envelope across a desk, beside a tablet listing requests in sequence with one approved, one awaiting approval and one pending
AI-generated illustration

Suppose a 350,000 baht purchase request sits with a manager for three days, because the manager is on vacation and nobody knows who to pass it to. In another case, an employee changes the amount from 150,000 to 250,000 after the manager has already approved, yet the request still shows that it passed the first step. In the last case, two managers approve the same request in the same second, and the system records both without either knowing the other has acted. All three cases are made up for this article, but they are patterns that paper-based and spreadsheet-based approval systems run into often.

This article walks through writing a purchase-request approval workflow that handles all three problems and several that follow: choosing the approval chain by amount, sending a request back for changes, assigning a substitute approver, preventing duplicate approvals, and sending a reminder when a request has been waiting too long. It uses TypeScript, which Node 24 runs directly, with the SQLite database built into Node, so nothing needs to be installed. A manager can read the explanations and tables to get the picture, and an engineer can run the code alongside.

The amount limits (20,000 and 200,000 baht), the SLA hours and the 10 Dec 2026 holiday in this article are sample policy values we made up. They are not the rules of any company or law. In real use, you must use your own organization's policy and holiday calendar.

The real problems an approval workflow must answer

A working approval system must answer these five questions without asking a person. Who must approve this request, and in what order? Who can approve in place of the real approver when that person is away? Who is forbidden to approve? When two people click at the same time, who wins? And after a long time has passed, who must be reminded? The standards documents agree on one principle: no single person should hold enough privilege to misuse the system alone, and every request must have its permissions checked again each time. The table below summarizes what we read in the referenced documents.

TopicWhat the document saysEffect on the design
Separation of dutiesNIST definition: no single user should have enough privilege to misuse the system aloneThe requester cannot approve their own request, and one person cannot approve two levels of the same request
Deny by defaultOWASP Authorization Cheat Sheet: configure the system to deny by default, and check permissions on every requestEvery approval click re-checks whether this person currently has the right. A visible button does not mean they have it
Tamper-proof historyOWASP Logging Cheat Sheet: record when, where, who and what, and build a mechanism to detect edits or deletionsAn append-only history table that the database itself refuses to update or delete
Clicks that collideMDN describes ETag with If-Match to detect mid-air collisions and return 412; PostgreSQL under Read Committed re-evaluates the WHERE condition after another transaction commitsStore a version in the row and use UPDATE ... WHERE version = ?. If no row is updated, someone got there first
SQLite transactionsBEGIN IMMEDIATE starts a write right away and may get SQLITE_BUSY, while DEFERRED upgrades laterEvery state change runs inside a single BEGIN IMMEDIATE
Summary of the NIST, OWASP, MDN, PostgreSQL and SQLite documents as read on 2026-11-21. OWASP Authorization does not use the term separation of duties directly, so we cite it only for deny by default and checking every request.

Overview of the example

All the code is in the examples/multi-level-approval-workflow-delegation/ folder. It uses only Node 24 built-ins: node:sqlite, node:test and node:assert, with no npm install. The Node documentation says that every node:sqlite API is synchronous on a single connection, and as of the reading date it is at Stability 1.2 (release candidate), which means it can still change. We use it here to make the example easy to run. Your real system can use PostgreSQL or MySQL with the same ideas.

FileRole
policy.tsSample policy: approval chains by amount and type, SLA, and a working-hours counter
db.tsSQLite schema and the triggers that make history append-only
authz.tsWho may act on this step, and the separation-of-duties rules
engine.tsThe state machine: submit, approve, reject, return, change amount, escalate, and version checks
demo.ts / engine.test.tsA script that plays 5 made-up scenarios, and a node:test suite with 10 cases

A request has five statuses: draft, in_review, approved, rejected and returned. An approval is a row in the steps table, where each row is one level of the chain. Every change is written to the history table. We go through it one step at a time.

Step 1: the approval chain comes from rules, not from a person's choice

Letting the requester pick the approvers tends to go wrong in two ways: they pick someone who approves easily, or they skip a level that should be there. So the example has the system compute the chain from the amount and the type of the request, keeping the rules in one place.

policy.ts · lines 4–36

// ช่วงวงเงิน (บาท) -> บทบาทผู้อนุมัติเรียงตามลำดับ
const BANDS = [
  { upTo: 20_000, roles: ["manager"] },
  { upTo: 200_000, roles: ["manager", "dept_head"] },
  { upTo: Infinity, roles: ["manager", "dept_head", "md"] },
];

// บทบาทที่ไม่ผูกแผนก (ผู้อนุมัติทั้งบริษัท)
export const COMPANY_WIDE = new Set(["it_head", "md"]);

// ผู้รับแจ้งเมื่อขั้นนั้นค้างเกิน SLA
export const ESCALATE_TO: Record<string, string> = {
  manager: "dept_head",
  it_head: "dept_head",
  dept_head: "md",
  md: "md",
};

export const SLA_WORKING_HOURS = 8;

// วันหยุดตัวอย่าง (ของจริงต้องดึงจากปฏิทินวันหยุดที่บริษัทประกาศ)
export const HOLIDAYS = new Set(["2026-12-10"]);

export function chainFor(amount: number, category: Category): string[] {
  const band = BANDS.find((b) => amount <= b.upTo);
  const roles = [...(band ? band.roles : [])];
  // กฎตามประเภท: อุปกรณ์ไอทีต้องผ่านหัวหน้าไอทีต่อจากผู้จัดการ
  if (category === "it-equipment") roles.splice(1, 0, "it_head");
  return roles;
}

// นับชั่วโมงทำงาน จันทร์-ศุกร์ 09:00-17:00 (ตามเวลาในนาฬิกาจำลอง) ไม่รวมวันหยุด
policy.ts: the approval chain by amount range and type (the numbers are sample policy)
  • Up to 20,000 baht goes through the manager. Up to 200,000 baht goes through the manager and the department head. Above that, the managing director is added.
  • IT equipment adds the IT head as the second level, because the example assumes a compatibility check is needed first.
  • If the requester is a manager, the same chain still applies, but they cannot approve their own request (see Step 4).

Keeping the rules in a single function makes them easy to test and easy to change. But you need to think ahead about what happens when the policy changes while requests are pending: will the old requests use the old chain or the new one? The example stores the chain computed at submission in the steps table, so pending requests are not affected. This is a decision your organization must make for itself.

Step 2: the schema, and a history the database will not let anyone change

db.ts · lines 4–37
const SCHEMA = `
CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT NOT NULL, role TEXT NOT NULL, dept TEXT NOT NULL);
CREATE TABLE delegations (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  from_user TEXT NOT NULL, to_user TEXT NOT NULL,
  start_day TEXT NOT NULL, end_day TEXT NOT NULL,
  CHECK (from_user <> to_user AND start_day <= end_day)
);
CREATE TABLE requests (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  requester TEXT NOT NULL, dept TEXT NOT NULL, category TEXT NOT NULL,
  title TEXT NOT NULL, amount INTEGER NOT NULL CHECK (amount > 0),
  status TEXT NOT NULL CHECK (status IN ('draft','in_review','approved','rejected','returned')),
  current_step INTEGER NOT NULL DEFAULT 0,
  version INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE steps (
  request_id INTEGER NOT NULL, step_no INTEGER NOT NULL, role TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('waiting','approved')),
  approved_by TEXT, on_behalf_of TEXT, approved_at TEXT,
  entered_at TEXT, escalated_at TEXT,
  PRIMARY KEY (request_id, step_no)
);
CREATE TABLE history (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  request_id INTEGER NOT NULL, at TEXT NOT NULL, version INTEGER NOT NULL,
  actor TEXT NOT NULL, on_behalf_of TEXT, action TEXT NOT NULL,
  from_status TEXT, to_status TEXT, step_no INTEGER, note TEXT
);
CREATE TRIGGER history_no_update BEFORE UPDATE ON history
  BEGIN SELECT RAISE(ABORT, 'history is append-only'); END;
CREATE TRIGGER history_no_delete BEFORE DELETE ON history
  BEGIN SELECT RAISE(ABORT, 'history is append-only'); END;
`;
db.ts: the schema and the history triggers

Three points are worth reading. First, the requests table has a version column that increases every time the status changes. Second, the steps table has one row per level and stores both approved_by (the person who clicked) and on_behalf_of (the person who delegated). Third, the history table has BEFORE UPDATE and BEFORE DELETE triggers that call RAISE(ABORT). The SQLite documentation says the message in RAISE comes back as SQLITE_CONSTRAINT with that message.

The SQLite documentation recommends AFTER triggers over BEFORE triggers when the trigger needs to modify rows. Ours modifies nothing and only rejects, so BEFORE is fine. A trigger only stops people who reach the database through the normal path. Someone with database administrator rights can still drop the trigger. So a real system must use a separate application database account that has no DROP privilege, and consider shipping a copy of the history to storage outside the system, as OWASP recommends for detecting log tampering.

Step 3: the state machine: every state change goes through one path

Every function that changes state does three things in order: check the version, check permissions, then write both the change and the history line in a single transaction. The helper that checks the version, which is the heart of the simultaneous-click problem, is in this part.

engine.ts · lines 25–37
function conflict(req: Req, expected: number): ApprovalError {
  return new ApprovalError("CONFLICT",
    `คำขอ #${req.id} ถูกเปลี่ยนไปแล้ว (หน้าจอของคุณเป็น v${expected} ปัจจุบันเป็น v${req.version}) โหลดใหม่แล้วดูก่อนตัดสินใจ`);
}

// เลื่อน version ด้วยเงื่อนไข WHERE version = ? ถ้าไม่มีแถวถูกแก้ แปลว่ามีคนอื่นเข้ามาก่อน
function bump(c: Ctx, req: Req, expected: number, set: string, params: SQLInputValue[]): number {
  if (req.version !== expected) throw conflict(req, expected);
  const r = c.db.prepare(`UPDATE requests SET ${set}, version = version + 1 WHERE id = ? AND version = ?`)
    .run(...params, req.id, expected);
  if (Number(r.changes) !== 1) throw conflict(load(c, req.id), expected);
  return expected + 1;
}
engine.ts: conflict and bump, which advances the version with WHERE version = ?

bump checks the version first and then runs UPDATE ... WHERE id = ? AND version = ?. If changes is not equal to 1, someone edited the row first, so it throws CONFLICT. The condition must be inside the UPDATE itself because a separate check followed by a write leaves a gap for someone else to slip into. For PostgreSQL, the documentation says that under Read Committed, when a row has been modified by another transaction that has committed, the WHERE condition is re-evaluated against the latest version of the row, and if it no longer matches, the row is not updated. So the same pattern works there.

engine.ts · lines 89–104
export function approve(c: Ctx, id: number, userId: string, expected: number, note = ""): Req {
  return tx(c, () => {
    const req = load(c, id);
    if (req.version !== expected) throw conflict(req, expected);
    const step = currentStep(c, req);
    const who = resolveActor(c.db, req, step, userId, today(c));
    c.db.prepare("UPDATE steps SET state = 'approved', approved_by = ?, on_behalf_of = ?, approved_at = ? WHERE request_id = ? AND step_no = ?")
      .run(who.actor, who.onBehalfOf, iso(c), id, step.step_no);
    const last = step.step_no === steps(c, id).length;
    const to = last ? "approved" : "in_review";
    const v = bump(c, req, expected, "status = ?, current_step = ?", [to, last ? step.step_no : step.step_no + 1]);
    if (!last) c.db.prepare("UPDATE steps SET entered_at = ? WHERE request_id = ? AND step_no = ?").run(iso(c), id, step.step_no + 1);
    log(c, id, v, { ...who, action: "approved", from: "in_review", to, step: step.step_no, note });
    return load(c, id);
  });
}
engine.ts approve: check the status, check permissions, then move to the next step
  • Reject and return must come with a reason (NOTE_REQUIRED), because the requester needs to know what to fix.
  • After a return, the requester can resubmit. The chain is recomputed from the latest amount, and earlier approvals start counting again from zero.
  • approved and rejected are final statuses. The amount can no longer be changed (LOCKED). To change it, open a new request.

Step 4: who can approve, who can substitute, and the absolute prohibitions

The resolveActor function answers just one question: can this user act on this step, and if so, in their own name or on behalf of whom? It checks in this order. The requester cannot act, either directly or through a delegation. Then the user must hold the role for this step directly, or have a delegation that covers today (counting both the start and end dates). Finally, the same person, or the same delegator, must not have already approved another level of this request.

authz.ts · lines 31–64
// ตัดสินว่า userId ลงมืออนุมัติขั้น step ได้หรือไม่ และในนามใคร
export function resolveActor(db: DatabaseSync, req: Req, step: StepRow, userId: string, today: string): Who {
  // กฎ 1: ผู้ขอทำเองไม่ได้ ไม่ว่าจะเป็นตัวเองหรือผ่านการมอบหมาย
  if (userId === req.requester) {
    throw new ApprovalError("SOD_SELF", "ผู้ขอซื้ออนุมัติคำขอของตัวเองไม่ได้");
  }
  const getUser = db.prepare("SELECT id, role, dept FROM users WHERE id = ?");
  let onBehalfOf: string | null = null;
  if (!holdsRole(getUser.get(userId) as U | undefined, step.role, req.dept)) {
    // ไม่มีสิทธิ์ตรง: หาผู้มอบหมายที่มีผลอยู่วันนี้ (ช่วงวันที่รวมวันแรกและวันสุดท้าย)
    const rows = db.prepare(
      "SELECT from_user FROM delegations WHERE to_user = ? AND start_day <= ? AND ? <= end_day ORDER BY id",
    ).all(userId, today, today) as { from_user: string }[];
    const ok = rows.filter((r) => holdsRole(getUser.get(r.from_user) as U | undefined, step.role, req.dept));
    if (ok.length === 0) {
      throw new ApprovalError("NOT_APPROVER", `ผู้ใช้ ${userId} ไม่ใช่ผู้อนุมัติขั้น ${step.role} และไม่มีการมอบหมายที่มีผลวันนี้`);
    }
    const delegator = ok.find((r) => r.from_user !== req.requester);
    if (!delegator) {
      throw new ApprovalError("SOD_SELF", "ผู้มอบหมายคือผู้ขอซื้อเอง อนุมัติแทนไม่ได้");
    }
    onBehalfOf = delegator.from_user;
  }
  // กฎ 2: คนเดียวไม่อนุมัติสองระดับของคำขอเดียวกัน (นับทั้งตัวจริงและผู้มอบหมาย)
  const done = db.prepare(
    "SELECT approved_by, on_behalf_of FROM steps WHERE request_id = ? AND state = 'approved'",
  ).all(req.id) as { approved_by: string; on_behalf_of: string | null }[];
  const used = new Set<string>();
  for (const d of done) { used.add(d.approved_by); if (d.on_behalf_of) used.add(d.on_behalf_of); }
  if (used.has(userId) || (onBehalfOf && used.has(onBehalfOf))) {
    throw new ApprovalError("SOD_TWO_LEVELS", "คนเดียวกันอนุมัติสองระดับของคำขอเดียวกันไม่ได้ (รวมกรณีอนุมัติแทน)");
  }
  return { actor: userId, onBehalfOf };
}
authz.ts: resolveActor and the separation-of-duties rules

The example enforces two separation-of-duties rules.

  • SOD_SELF: the requester cannot approve their own request. This includes the case where the delegator is the requester. For example, if a manager raises a request and has a subordinate approve on their behalf, the system refuses.
  • SOD_TWO_LEVELS: one person cannot approve two levels of the same request. It counts both the person who clicked and the delegator. Otherwise, someone who received delegations from two people could approve two levels in one go.
  • A substitute approval is recorded as approved by X on behalf of Y, in both the steps table and the history, so you can later check who actually clicked.

We chose to re-check permissions on every click and not to trust the status shown on the screen. This matches OWASP's deny-by-default principle. If none of the conditions match, the request is refused (NOT_APPROVER). In a real system, adding a delegation should itself require permission and be logged. This example does not yet record the adding and cancelling of delegations in the per-request history.

Step 5: changing the amount while waiting for approval, and simultaneous clicks

engine.ts · lines 122–141
// ผู้ขอแก้ยอด: ยอดเพิ่มระหว่างรออนุมัติ = สายอนุมัติคำนวณใหม่และการอนุมัติเดิมใช้ไม่ได้
export function editAmount(c: Ctx, id: number, userId: string, expected: number, amount: number): Req {
  return tx(c, () => {
    const req = load(c, id);
    if (userId !== req.requester) throw new ApprovalError("NOT_REQUESTER", "เฉพาะผู้ขอซื้อเท่านั้นที่แก้ยอดได้");
    if (req.version !== expected) throw conflict(req, expected);
    if (req.status === "approved" || req.status === "rejected") throw new ApprovalError("LOCKED", `คำขอสถานะ ${req.status} แก้ไม่ได้ ต้องเปิดคำขอใหม่`);
    if (req.status === "in_review" && amount > req.amount) {
      const had = steps(c, id).filter((s) => s.state === "approved").length;
      buildChain(c, req, amount);
      const v = bump(c, req, expected, "amount = ?, current_step = 1", [amount]);
      log(c, id, v, { actor: userId, action: "amount_raised", from: "in_review", to: "in_review", step: 1,
        note: `${req.amount} -> ${amount} บาท ล้างการอนุมัติเดิม ${had} ขั้น เริ่มสายใหม่` });
    } else {
      const v = bump(c, req, expected, "amount = ?", [amount]);
      log(c, id, v, { actor: userId, action: "amount_edited", from: req.status, to: req.status, note: `${req.amount} -> ${amount} บาท` });
    }
    return load(c, id);
  });
}
engine.ts editAmount: a higher amount must start a new chain

The example's rule is this: if the requester raises the amount while the request is waiting for approval, the system recomputes the chain, clears the earlier approvals and starts again from the first step, because what the approver saw when they clicked is no longer the number that will be used. If the amount is lowered, the earlier approvals stay. This is the example's own decision, and some organizations may prefer to restart every time the amount is edited.

For simultaneous clicks, every function takes as a parameter the version the person saw on screen. If it does not match the current one, they get a CONFLICT with a message saying which version the screen showed and which is current. In a real web app, this value is sent through a form or the If-Match header, as MDN describes.

A limit we should state plainly: node:sqlite is synchronous and the example runs in a single process, so there is no true simultaneity. The example simulates it with two approvers holding the same old version. The first click passes and the second is refused. The mechanism being tested is the version condition, which works the same way on a database with many connections, but this example does not prove behavior under real load.

Step 6: overdue requests: the SLA counts working hours only

A request that has waited from Wednesday afternoon to Monday morning should not count as five full days. The example counts only Monday to Friday, 09:00 to 17:00, skips the listed holidays, and counts only the hours that have fully elapsed within each slot.

policy.ts · lines 37–49
// นับเฉพาะชั่วโมงที่ผ่านไปครบทั้งช่อง เศษชั่วโมงต้นทางปัดขึ้น (ไม่นับเกิน)
export function workingHoursBetween(from: Date, to: Date): number {
  const H = 3600_000;
  let n = 0;
  for (let t = Math.ceil(from.getTime() / H) * H; t + H <= to.getTime(); t += H) {
    const d = new Date(t);
    const dow = d.getUTCDay();
    const hour = d.getUTCHours();
    const day = d.toISOString().slice(0, 10);
    if (dow >= 1 && dow <= 5 && hour >= 9 && hour < 17 && !HOLIDAYS.has(day)) n++;
  }
  return n;
}
policy.ts workingHoursBetween (uses the UTC time fields of the simulated clock)
engine.ts · lines 143–163
// งานตามเวลา: ขั้นที่ค้างเกิน SLA (ชั่วโมงทำงาน) แจ้งเตือนผู้ระดับถัดไปครั้งเดียวต่อขั้น ไม่เปลี่ยน version
export function escalateOverdue(c: Ctx): number[] {
  return tx(c, () => {
    const hit: number[] = [];
    const open = c.db.prepare("SELECT * FROM requests WHERE status = 'in_review'").all() as unknown as Req[];
    for (const req of open) {
      const s = currentStep(c, req);
      if (s.escalated_at || !s.entered_at) continue;
      const hrs = workingHoursBetween(new Date(s.entered_at), c.clock.now);
      if (hrs < SLA_WORKING_HOURS) continue;
      const role = ESCALATE_TO[s.role] ?? "md";
      const to = c.db.prepare("SELECT id FROM users WHERE role = ? AND (dept = ? OR ? = 1) LIMIT 1")
        .get(role, req.dept, COMPANY_WIDE.has(role) ? 1 : 0) as { id: string } | undefined;
      c.db.prepare("UPDATE steps SET escalated_at = ? WHERE request_id = ? AND step_no = ?").run(iso(c), req.id, s.step_no);
      log(c, req.id, req.version, { actor: "system", action: "escalated", from: "in_review", to: "in_review", step: s.step_no,
        note: `ค้างขั้น ${s.role} ${hrs} ชม.ทำงาน (SLA ${SLA_WORKING_HOURS}) แจ้ง ${to?.id ?? "-"} (${role})` });
      hit.push(req.id);
    }
    return hit;
  });
}
engine.ts escalateOverdue: notifies the next level once per step and does not change the version
  • Escalation happens once per step (the time is stored in steps.escalated_at), so running it again does not notify again.
  • It is recorded with the actor system and does not increase the version, so that someone about to click does not hit a CONFLICT when nobody has changed anything.
  • The example only sends a notification. It does not approve on anyone's behalf. Giving a higher level the right to approve and skip a step is a separate policy decision.

A real run: five made-up scenarios and an attempt to edit the history

demo.ts uses a simulated clock that we set ourselves. Everything runs in memory, and the users have made-up names. The output below comes from a real run, stdout only.

output.txt
== เรื่องที่ 1: 350,000 บาท ผ่านสามระดับ ==
  DENY  พลอย (ผู้ขอ) อนุมัติเอง
        -> SOD_SELF: ผู้ขอซื้ออนุมัติคำขอของตัวเองไม่ได้
  ok    อนันต์ (ผู้จัดการ) อนุมัติ
  ok    บุญ (หัวหน้าแผนก) อนุมัติ
  ok    ชัย (MD) อนุมัติ
  ประวัติคำขอ #1 (append-only)
    v1 2026-12-07T09:00 created     พลอย [- -> draft] 350000 บาท (general)
    v2 2026-12-07T09:00 submitted   พลอย [draft -> in_review] ขั้น 1 สายอนุมัติ manager > dept_head > md
    v3 2026-12-07T10:00 approved    อนันต์ [in_review -> in_review] ขั้น 1 
    v4 2026-12-07T11:00 approved    บุญ [in_review -> in_review] ขั้น 2 
    v5 2026-12-07T14:00 approved    ชัย [in_review -> approved] ขั้น 3 

== เรื่องที่ 2: อุปกรณ์ไอที 45,000 บาท ผู้จัดการลา มอบหมายให้ดาว ==
  ok    ดาวอนุมัติแทนอนันต์ (ขั้นผู้จัดการ)
  ok    อีฟ (หัวหน้าไอที) อนุมัติ
  DENY  ดาวอนุมัติแทนบุญ (ขั้นหัวหน้าแผนก) ซ้ำอีกระดับ
        -> SOD_TWO_LEVELS: คนเดียวกันอนุมัติสองระดับของคำขอเดียวกันไม่ได้ (รวมกรณีอนุมัติแทน)
  DENY  ดาวลองอนุมัติแทนบุญหลังช่วงมอบหมายสิ้นสุด (21 ธ.ค.)
        -> NOT_APPROVER: ผู้ใช้ dao ไม่ใช่ผู้อนุมัติขั้น dept_head และไม่มีการมอบหมายที่มีผลวันนี้
  ok    บุญกลับมา อนุมัติเอง
  ประวัติคำขอ #2 (append-only)
    v1 2026-12-14T09:00 created     พลอย [- -> draft] 45000 บาท (it-equipment)
    v2 2026-12-14T09:00 submitted   พลอย [draft -> in_review] ขั้น 1 สายอนุมัติ manager > it_head > dept_head
    v3 2026-12-14T10:00 approved    ดาว แทน อนันต์ [in_review -> in_review] ขั้น 1 อนันต์ลาพักร้อน
    v4 2026-12-14T11:00 approved    อีฟ [in_review -> in_review] ขั้น 2 
    v5 2026-12-21T09:00 approved    บุญ [in_review -> approved] ขั้น 3 

== เรื่องที่ 3: ผู้จัดการเป็นผู้ขอเอง ==
  DENY  อนันต์อนุมัติคำขอของตัวเอง
        -> SOD_SELF: ผู้ขอซื้ออนุมัติคำขอของตัวเองไม่ได้
  DENY  ดาวอนุมัติแทนอนันต์ (ผู้มอบหมายคือผู้ขอ)
        -> SOD_SELF: ผู้มอบหมายคือผู้ขอซื้อเอง อนุมัติแทนไม่ได้
  ok    ฝน (ผู้จัดการอีกคน) ส่งกลับให้แก้
  ok    อนันต์ส่งใหม่
  DENY  ฝนปฏิเสธโดยไม่ระบุเหตุผล
        -> NOTE_REQUIRED: ต้องระบุเหตุผล
  ok    ฝนปฏิเสธ
  ประวัติคำขอ #3 (append-only)
    v1 2026-12-15T09:00 created     อนันต์ [- -> draft] 12000 บาท (general)
    v2 2026-12-15T09:00 submitted   อนันต์ [draft -> in_review] ขั้น 1 สายอนุมัติ manager
    v3 2026-12-15T10:00 returned    ฝน [in_review -> returned] ขั้น 1 ขอใบเสนอราคา 2 ราย
    v4 2026-12-15T10:00 resubmitted อนันต์ [returned -> in_review] ขั้น 1 สายอนุมัติ manager
    v5 2026-12-15T10:00 rejected    ฝน [in_review -> rejected] ขั้น 1 งบอบรมหมดแล้ว

== เรื่องที่ 4: แก้ยอดขึ้นหลังอนุมัติไปแล้วหนึ่งขั้น ==
  ok    อนันต์อนุมัติขั้นที่ 1
  ok    พลอยแก้ยอดเป็น 250,000
  DENY  บุญลองอนุมัติ (สายใหม่ยังรอขั้นผู้จัดการ)
        -> NOT_APPROVER: ผู้ใช้ boon ไม่ใช่ผู้อนุมัติขั้น manager และไม่มีการมอบหมายที่มีผลวันนี้
  ok    อนันต์อนุมัติใหม่
  ประวัติคำขอ #4 (append-only)
    v1 2026-12-16T09:00 created     พลอย [- -> draft] 150000 บาท (general)
    v2 2026-12-16T09:00 submitted   พลอย [draft -> in_review] ขั้น 1 สายอนุมัติ manager > dept_head
    v3 2026-12-16T10:00 approved    อนันต์ [in_review -> in_review] ขั้น 1 
    v4 2026-12-16T11:00 amount_raised พลอย [in_review -> in_review] ขั้น 1 150000 -> 250000 บาท ล้างการอนุมัติเดิม 1 ขั้น เริ่มสายใหม่
    v5 2026-12-16T11:00 approved    อนันต์ [in_review -> in_review] ขั้น 1 

== เรื่องที่ 5: อนุมัติพร้อมกัน และ SLA ข้ามวันหยุด ==
  นาฬิกา 2026-12-09T16:00: อนันต์และฝนเปิดหน้าเดียวกันที่ v2
  ok    อนันต์กดอนุมัติก่อน
  DENY  ฝนกดอนุมัติด้วยหน้าจอเก่า
        -> CONFLICT: คำขอ #5 ถูกเปลี่ยนไปแล้ว (หน้าจอของคุณเป็น v2 ปัจจุบันเป็น v3) โหลดใหม่แล้วดูก่อนตัดสินใจ
  วันหยุดตัวอย่าง 10 ธ.ค. escalated=[]
  ศุกร์ 12:00 (ชั่วโมงทำงานสะสม 4) escalated=[]
  ศุกร์ 17:00 (สะสม 9) escalated=[5]
  รันซ้ำ escalated=[]
  ประวัติคำขอ #5 (append-only)
    v1 2026-12-09T15:00 created     พลอย [- -> draft] 60000 บาท (general)
    v2 2026-12-09T15:00 submitted   พลอย [draft -> in_review] ขั้น 1 สายอนุมัติ manager > dept_head
    v3 2026-12-09T16:00 approved    อนันต์ [in_review -> in_review] ขั้น 1 
    v3 2026-12-11T17:00 escalated   system [in_review -> in_review] ขั้น 2 ค้างขั้น dept_head 9 ชม.ทำงาน (SLA 8) แจ้ง chai (md)

== ลองแก้ประวัติ ==
  DENY  UPDATE history
        -> ERR_SQLITE_ERROR: history is append-only
  DENY  DELETE history
        -> ERR_SQLITE_ERROR: history is append-only
Actual output, run on 2026-11-21 with node demo.ts (Node 24). Stdout only; the MODULE_TYPELESS_PACKAGE_JSON warning goes to stderr, so it is not in the file
  1. Scenario 1: a 350,000 baht request passes three levels. Ploy tries to approve her own request and is refused with SOD_SELF. Then Anan, Boon and Chai approve in order. The history has five lines, v1 to v5.
  2. Scenario 2: 45,000 baht of IT equipment. Dao approves in place of Anan, who is on vacation, but is refused when she tries to approve in place of Boon at the other level (SOD_TWO_LEVELS), and is refused again when she tries after the delegation end date (NOT_APPROVER). Boon comes back and approves himself.
  3. Scenario 3: a manager is the requester. Both approving their own request and having Dao act for them are refused. Fon sends it back. Anan resubmits. Fon's rejection without a reason is refused, and then she rejects with a reason.
  4. Scenario 4: the amount is changed from 150,000 to 250,000 after Anan has approved. The system clears the approval and starts a new chain. Boon cannot skip a level. Anan must approve again.
  5. Scenario 5: Anan and Fon both hold v2. Anan clicks first and passes. Fon gets a CONFLICT. Then the clock advances. At Friday 12:00, 4 working hours have accumulated and there is no reminder. At 17:00, 9 hours have accumulated and a reminder is sent. Running it again sends no second reminder. All of this skips the sample holiday of 10 Dec.
  6. Finally, UPDATE and DELETE on history are refused by the database with the message history is append-only.

Test suite

engine.test.ts has 10 cases and runs with node --test engine.test.ts, giving 10 passes. It covers chains by amount and type, working hours across weekends and holidays, delegation by date range, both separation-of-duties rules, raising and lowering the amount, simultaneous clicks that leave no half-written history, a return that requires a reason, escalation happening once, and an immutable history. If anyone edits the code and breaks one of these mechanisms, the test suite fails.

What to add before real use

  • Notify approvers by email or LINE with a link that opens the request directly, and a mobile screen where they can approve, because most approvers are not sitting at a computer.
  • The company's real working calendar, including Thai public holidays and special days off, and a clearly defined time zone. The example uses UTC and a single made-up holiday.
  • A policy for when the rules change while requests are pending, and storing the policy version with each request.
  • A real login and authentication system. The example accepts the user id directly.
  • Reports: the longest-waiting requests, the average time per level, and how often substitutes approve.
  • A database that supports many connections (for example PostgreSQL), with an application account that cannot drop triggers, and backups of the history.

Adapting it to other work

  • Leave requests: the chain is the direct supervisor and then HR, and a substitute approver is normal during long leaves, but the rule against approving your own leave request stays the same.
  • Contracts and special pricing: the chain depends on the discount or the contract value. Changing the price after approval must start a new chain, in the same way as Step 5.
  • On-site expense requests: add attachments, and decide that attached files cannot be changed after approval. Otherwise, what was approved and what was paid will not match.

Common mistakes

  • Hiding the approve button but not checking permissions on the server. Anyone who sends the request directly gets through.
  • Checking permissions when the page opens but not when the click actually happens, which may be hours apart.
  • Not storing a version, so someone who sees old data approves over the new data.
  • Letting the delegator and the delegate be the same person approving two levels.
  • Allowing the amount to be changed after approval without clearing the approvals.
  • Letting an administrator edit the history table directly to fix wrong data, instead of adding a new correction line.
  • Counting the SLA in calendar hours, so that someone gets a reminder on Monday morning for a request that only arrived on Friday evening.

Checklist before launch

  1. Write the statuses and the events that can change them on a single sheet of paper, and have the process owner review it.
  2. Agree the amount limits, chains and substitute approvers with the finance team and management, and keep them in one place that can be changed by editing values, not code.
  3. Test the cases where the requester is also an approver, where one person holds two levels through delegation, where a delegation period has expired, and where an approver has left the company.
  4. Test simultaneous clicks on a real database with several connections, not just in memory.
  5. Check that the application's database account cannot edit or delete history.
  6. Rehearse the case where the policy changes midway and the case where the approver for a whole chain is missing.

Caution: the example is a learning tool, not a production system. It uses an in-memory database, a simulated clock, made-up users and no login. Do not use it to approve real money without further design and testing.

References

  1. NIST CSRC Glossary — separation of duty (accessed 2026-11-21)
  2. OWASP — Authorization Cheat Sheet (deny by default, validate on every request) (accessed 2026-11-21)
  3. OWASP — Logging Cheat Sheet (when, where, who, what; tamper detection) (accessed 2026-11-21)
  4. SQLite — CREATE TRIGGER (RAISE, BEFORE vs AFTER) (accessed 2026-11-21)
  5. SQLite — Transactions (BEGIN IMMEDIATE) (accessed 2026-11-21)
  6. Node.js v24 — node:sqlite (DatabaseSync, stability) (accessed 2026-11-21)
  7. PostgreSQL — Transaction Isolation (Read Committed re-evaluates WHERE) (accessed 2026-11-21)
  8. MDN — ETag (If-Match, mid-air collisions, 412) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer