2019-03-13 16:49:03 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-03-13 17:48:35 +01:00
|
|
|
require 'checksum'
|
|
|
|
|
2019-03-13 16:49:03 +01:00
|
|
|
# A single line inside an invoice. Can be a subscription or a reservation
|
2020-03-25 10:16:47 +01:00
|
|
|
class InvoiceItem < ApplicationRecord
|
2020-12-21 17:37:58 +01:00
|
|
|
include Footprintable
|
|
|
|
|
2016-03-23 18:39:41 +01:00
|
|
|
belongs_to :invoice
|
|
|
|
belongs_to :subscription
|
|
|
|
|
2020-03-25 17:45:53 +01:00
|
|
|
has_one :invoice_item # associates invoice_items of an invoice to invoice_items of an Avoir
|
2019-02-12 14:45:21 +01:00
|
|
|
|
|
|
|
after_create :chain_record
|
2019-09-11 12:22:14 +02:00
|
|
|
after_update :log_changes
|
2019-02-12 14:45:21 +01:00
|
|
|
|
|
|
|
def chain_record
|
2019-02-12 16:00:36 +01:00
|
|
|
self.footprint = compute_footprint
|
2019-03-11 13:49:16 +01:00
|
|
|
save!
|
2020-07-21 19:25:21 +02:00
|
|
|
FootprintDebug.create!(
|
|
|
|
footprint: footprint,
|
|
|
|
data: FootprintService.footprint_data(InvoiceItem, self),
|
|
|
|
klass: InvoiceItem.name
|
|
|
|
)
|
2019-02-12 16:00:36 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def check_footprint
|
|
|
|
footprint == compute_footprint
|
|
|
|
end
|
|
|
|
|
2020-07-21 19:25:21 +02:00
|
|
|
def debug_footprint
|
|
|
|
FootprintService.debug_footprint(InvoiceItem, self)
|
|
|
|
end
|
|
|
|
|
2019-09-18 17:14:59 +02:00
|
|
|
def amount_after_coupon
|
|
|
|
# deduct coupon discount
|
|
|
|
coupon_service = CouponService.new
|
|
|
|
coupon_service.ventilate(invoice.total, amount, invoice.coupon)
|
|
|
|
end
|
|
|
|
|
|
|
|
# return the item amount, coupon discount deducted, if any, and VAT excluded, if applicable
|
|
|
|
def net_amount
|
|
|
|
# deduct VAT
|
|
|
|
vat_service = VatHistoryService.new
|
|
|
|
vat_rate = vat_service.invoice_vat(invoice)
|
|
|
|
Rational(amount_after_coupon / (vat_rate / 100.00 + 1)).round.to_f
|
|
|
|
end
|
|
|
|
|
|
|
|
# return the VAT amount for this item
|
|
|
|
def vat
|
|
|
|
amount_after_coupon - net_amount
|
|
|
|
end
|
|
|
|
|
2019-03-20 11:01:53 +01:00
|
|
|
private
|
2019-02-12 16:00:36 +01:00
|
|
|
|
|
|
|
def compute_footprint
|
2019-09-18 15:09:14 +02:00
|
|
|
FootprintService.compute_footprint(InvoiceItem, self)
|
2019-02-12 14:45:21 +01:00
|
|
|
end
|
2019-09-11 12:22:14 +02:00
|
|
|
|
|
|
|
def log_changes
|
2019-09-11 14:29:35 +02:00
|
|
|
return if Rails.env.test?
|
2019-09-11 12:22:14 +02:00
|
|
|
return unless changed?
|
|
|
|
|
|
|
|
puts "WARNING: InvoiceItem update triggered [ id: #{id}, invoice reference: #{invoice.reference} ]"
|
|
|
|
puts '---------- changes ----------'
|
|
|
|
puts changes
|
|
|
|
puts '---------------------------------'
|
|
|
|
end
|
2016-03-23 18:39:41 +01:00
|
|
|
end
|