/ Cases / Restaurants / Finance
Chain of custody for cash from the register to the vault: closeouts matched against the point of sale, expenses with photos, signed handoffs and a chained ledger that exposes any tampering.
≈32
server functions
4
links in the chain of custody
/ The problem
Cash passed through several hands between the register, the pickup route, finance and the vault. When something didn't add up, there was no way to know where it went missing.
/ What we built
/ How it works
/ By the numbers
■ Real production data · counts per week, no amounts or personal data · Current week excluded.
/ Real code
-- 9.3 Hash encadenado POR CUSTODIO.
-- Por custodio y no global porque con la cola sin señal los movimientos de
-- distintas personas llegan desordenados; dentro de una billetera el orden
-- de inserción sí es único. El lock por custodio evita que dos inserts
-- concurrentes lean el mismo hash previo y bifurquen la cadena.
create or replace function private.cash_encadenar()
returns trigger language plpgsql as $$
declare
v_prev text;
begin
perform pg_advisory_xact_lock(hashtext('cash_mov_' || new.custodio_id::text));
select m.hash into v_prev
from public.cash_movimientos m
where m.custodio_id = new.custodio_id
order by m.seq desc
limit 1;
new.hash_prev := v_prev;
new.hash := encode(sha256(convert_to(
coalesce(v_prev, '') || '|' ||
new.custodio_id::text || '|' ||
to_char(new.monto, 'FM99999999990.00') || '|' ||
new.tipo || '|' ||
-- …
new.idempotency_key::text
, 'UTF8')), 'hex');
return new;
end $$;
■ Every cash movement stores the SHA-256 of the previous one; changing an old row breaks the chain and the daily check flags it.
/ Stack