000004_risk.up.sql33 lines, 1.5 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- A new state: the money is held while a person reviews the transfer. This |
| 4 | -- is why state was a CHECK, and not an enum: the saga grows. |
| 5 | ALTER TABLE transfers DROP CONSTRAINT transfers_state_check; |
| 6 | ALTER TABLE transfers ADD CONSTRAINT transfers_state_check CHECK (state IN |
| 7 | ('pending', 'in_review', 'funds_held', 'completed', 'compensating', 'failed', 'reversed')); |
| 8 | |
| 9 | -- A transfer in review is due when its review times out. |
| 10 | DROP INDEX transfers_due_idx; |
| 11 | CREATE INDEX transfers_due_idx ON transfers (next_attempt_at) |
| 12 | WHERE state IN ('pending', 'in_review', 'funds_held', 'compensating'); |
| 13 | |
| 14 | -- Has this user paid this wallet before? |
| 15 | CREATE INDEX transfers_paid_idx ON transfers (user_id, to_wallet_id) |
| 16 | WHERE state = 'completed'; |
| 17 | |
| 18 | -- Every risk decision, the engine's and the reviewers': why a transfer went |
| 19 | -- through, waited, or didn't. Rows are only ever added. |
| 20 | CREATE TABLE risk_decisions ( |
| 21 | id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, |
| 22 | transfer_id uuid NOT NULL REFERENCES transfers (id), |
| 23 | decision text NOT NULL CHECK (decision IN |
| 24 | ('allow', 'review', 'deny', 'approve', 'reject')), |
| 25 | reasons text[] NOT NULL DEFAULT '{}', |
| 26 | decided_by text NOT NULL, -- the risk engine, or a reviewer |
| 27 | note text NOT NULL DEFAULT '', |
| 28 | created_at timestamptz NOT NULL DEFAULT now() |
| 29 | ); |
| 30 | |
| 31 | CREATE INDEX risk_decisions_transfer_id_idx ON risk_decisions (transfer_id, id); |
| 32 | |
| 33 | COMMIT; |