Skip to content

Commit

Permalink
fix(invoice): Add missing unique index on invoice organization_sequen…
Browse files Browse the repository at this point in the history
…tial ids
  • Loading branch information
vincent-pochet committed Dec 14, 2023
1 parent f6dcfe4 commit 8badf85
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 4 deletions.
5 changes: 4 additions & 1 deletion app/models/invoice.rb
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,10 @@ def ensure_organization_sequential_id
end

def generate_organization_sequential_id
organization_sequence_scope = organization.invoices.where(created_at: Time.now.utc.all_month)
organization_sequence_scope = organization.invoices.where(
"date_trunc('month', created_at)::date = ?",
Time.now.utc.beginning_of_month.to_date,
)

result = Invoice.with_advisory_lock(
organization_id,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

class AddUniqueIndexOnInvoiceOrganizationSequentialId < ActiveRecord::Migration[7.0]
disable_ddl_transaction!

def change
add_index :invoices,
"organization_id, organization_sequential_id, date_trunc('month'::text, created_at)",
name: 'unique_organization_sequential_id',
unique: true
end
end
3 changes: 2 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions spec/factories/invoices.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
payment_status { 'pending' }
currency { 'EUR' }

organization_sequential_id { rand(1_000_000) }

trait :draft do
status { :draft }
end
Expand Down
4 changes: 2 additions & 2 deletions spec/models/invoice_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

describe 'sequential_id' do
let(:customer) { create(:customer, organization:) }
let(:invoice) { build(:invoice, customer:, organization:) }
let(:invoice) { build(:invoice, customer:, organization:, organization_sequential_id: nil) }

it 'assigns a sequential id and organization sequential id to a new invoice' do
invoice.save
Expand Down Expand Up @@ -98,7 +98,7 @@
let(:organization) { create(:organization, name: 'LAGO') }
let(:customer) { create(:customer, organization:) }
let(:subscription) { create(:subscription, organization:, customer:) }
let(:invoice) { build(:invoice, customer:, organization:) }
let(:invoice) { build(:invoice, customer:, organization:, organization_sequential_id: nil) }

it 'generates the invoice number' do
invoice.save
Expand Down

0 comments on commit 8badf85

Please sign in to comment.