Skip to content

Commit 0b50560

Browse files
committed
feat(payment_terms): Backfill customers and billing_entities
1 parent f8f852e commit 0b50560

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# frozen_string_literal: true
2+
3+
class BackfillPaymentTerms < ActiveRecord::Migration[8.0]
4+
disable_ddl_transaction!
5+
6+
# Plain AR class detached from app/models/customer.rb so the migration
7+
# does not depend on the model's current enums and validations.
8+
class MigrationCustomer < ActiveRecord::Base
9+
self.table_name = "customers"
10+
end
11+
12+
def up
13+
safety_assured do
14+
backfill_customers
15+
backfill_billing_entities
16+
end
17+
end
18+
19+
def down
20+
raise ActiveRecord::IrreversibleMigration, "backfilled payment terms cannot be distinguished from user values"
21+
end
22+
23+
private
24+
25+
def backfill_customers
26+
MigrationCustomer
27+
.where(payment_term: nil).where.not(net_payment_term: nil)
28+
.in_batches(of: 10_000) do |batch|
29+
batch.update_all("payment_term = jsonb_build_object('term_type', 'net', 'days', net_payment_term)") # rubocop:disable Rails/SkipsModelValidations
30+
end
31+
end
32+
33+
def backfill_billing_entities
34+
execute <<~SQL
35+
UPDATE billing_entities
36+
SET payment_term = jsonb_build_object('term_type', 'net', 'days', net_payment_term)
37+
WHERE payment_term IS NULL AND net_payment_term IS NOT NULL
38+
SQL
39+
end
40+
end

db/structure.sql

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14215,6 +14215,7 @@ ALTER TABLE ONLY public.membership_roles
1421514215
SET search_path TO "$user", public;
1421614216

1421714217
INSERT INTO "schema_migrations" (version) VALUES
14218+
('20260819134021'),
1421814219
('20260819111435'),
1421914220
('20260819111434'),
1422014221
('20260819000710'),

0 commit comments

Comments
 (0)