From 969101600d26be1ea631daed792b633cdb673d6d Mon Sep 17 00:00:00 2001 From: Sergei Poljanski Date: Tue, 26 May 2026 19:09:33 +0300 Subject: [PATCH] db: scope invoices to owner, add void + snapshot columns - owner_id (FK users, ON DELETE RESTRICT) + index on (owner_id, created_at DESC) - client_id (nullable FK clients, ON DELETE RESTRICT) for client back-references - issuer_snapshot jsonb + snapshot_version: invoices freeze the issuer's legal-entity fields at issue time so historical PDFs render unchanged when the user later edits their profile - voided_at + voided_reason: soft-void instead of delete, since invoices are retained indefinitely - swap unique(number) for unique(owner_id, number): numbers are now per-user, not global DROP CONSTRAINT uses IF EXISTS so the migration is resilient to the auto-generated constraint name differing across Postgres versions. --- db/migrations/004_scope_invoices_to_owner.rb | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 db/migrations/004_scope_invoices_to_owner.rb diff --git a/db/migrations/004_scope_invoices_to_owner.rb b/db/migrations/004_scope_invoices_to_owner.rb new file mode 100644 index 0000000..17e9484 --- /dev/null +++ b/db/migrations/004_scope_invoices_to_owner.rb @@ -0,0 +1,23 @@ +Sequel.migration do + change do + alter_table(:invoices) do + add_foreign_key :owner_id, :users, type: :Bignum, on_delete: :restrict + add_foreign_key :client_id, :clients, type: :Bignum, on_delete: :restrict + add_column :issuer_snapshot, :jsonb + add_column :snapshot_version, Integer, null: false, default: 1 + add_column :voided_at, DateTime + add_column :voided_reason, String, text: true + + add_unique_constraint [:owner_id, :number], name: :invoices_owner_number_uniq + end + + # Drop the original global-unique constraint on (number). Postgres names + # unique constraints from `unique: true` as `__key`. Use raw + # SQL with IF EXISTS so this no-ops if the name ever differs. + run "ALTER TABLE invoices DROP CONSTRAINT IF EXISTS invoices_number_key" + + alter_table(:invoices) do + add_index [:owner_id, Sequel.desc(:created_at)], name: :invoices_owner_created_idx + end + end +end