From c1e3b2495ca315110be8cc5c7ff092bb8564430a Mon Sep 17 00:00:00 2001 From: Toon Willems Date: Mon, 4 Nov 2024 10:31:27 +0100 Subject: [PATCH] feat(InvoiceError) - Improve create_for handling (#2770) ## description If an invoice already has an invoice error, and still fails to generate. We'd have a duplicate primary key violation. we'd rather simply update the existing error object. --- app/models/invoice_error.rb | 8 +++++--- spec/models/invoice_error_spec.rb | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/app/models/invoice_error.rb b/app/models/invoice_error.rb index 35bf30fd1fe..72856b891a8 100644 --- a/app/models/invoice_error.rb +++ b/app/models/invoice_error.rb @@ -4,12 +4,14 @@ class InvoiceError < ApplicationRecord # NOTE! Invoice errors will have the same id as the invoice they belong to. def self.create_for(invoice:, error:) return unless invoice - - create(id: invoice.id, + instance = find_or_create_by(id: invoice.id) + instance.update( backtrace: error.backtrace, error: error.inspect.to_json, invoice: invoice.to_json(except: :file), - subscriptions: invoice.subscriptions.to_json) + subscriptions: invoice.subscriptions.to_json + ) + instance end end diff --git a/spec/models/invoice_error_spec.rb b/spec/models/invoice_error_spec.rb index 2b234c763b5..b4dbc97160c 100644 --- a/spec/models/invoice_error_spec.rb +++ b/spec/models/invoice_error_spec.rb @@ -38,5 +38,13 @@ invoice_error = described_class.create_for(invoice:, error:) expect(invoice_error.subscriptions).to eq("[]") end + + it "updates when create_for is called with the same invoice" do + invoice_error = described_class.create_for(invoice:, error:) + expect(invoice_error.id).to eq(invoice.id) + + invoice_error = described_class.create_for(invoice:, error:) + expect(invoice_error.id).to eq(invoice.id) + end end end