2019-01-08 17:32:45 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-01-31 12:19:50 +01:00
|
|
|
require 'checksum'
|
|
|
|
require 'version'
|
|
|
|
|
2019-01-08 17:32:45 +01:00
|
|
|
# AccountingPeriod is a period of N days (N > 0) which as been closed by an admin
|
|
|
|
# to prevent writing new accounting lines (invoices & refunds) during this period of time.
|
2019-01-07 12:29:52 +01:00
|
|
|
class AccountingPeriod < ActiveRecord::Base
|
|
|
|
before_destroy { false }
|
|
|
|
before_update { false }
|
2019-01-10 10:52:29 +01:00
|
|
|
after_create :archive_closed_data
|
2019-01-07 12:29:52 +01:00
|
|
|
|
2019-01-08 17:32:45 +01:00
|
|
|
validates :start_at, :end_at, :closed_at, :closed_by, presence: true
|
|
|
|
validates_with DateRangeValidator
|
|
|
|
validates_with PeriodOverlapValidator
|
|
|
|
|
2019-01-07 12:29:52 +01:00
|
|
|
def delete
|
|
|
|
false
|
|
|
|
end
|
2019-01-10 10:52:29 +01:00
|
|
|
|
|
|
|
def archive_file
|
|
|
|
dir = 'accounting'
|
|
|
|
|
|
|
|
# create directory if it doesn't exists (accounting)
|
|
|
|
FileUtils.mkdir_p dir
|
|
|
|
"#{dir}/#{start_at.iso8601}_#{end_at.iso8601}.json"
|
|
|
|
end
|
|
|
|
|
2019-01-10 15:12:22 +01:00
|
|
|
private
|
|
|
|
|
2019-01-10 10:52:29 +01:00
|
|
|
def to_json_archive(invoices)
|
2019-01-31 12:19:50 +01:00
|
|
|
previous_file = previous_period&.archive_file
|
|
|
|
code_checksum = Checksum.code
|
2019-02-12 16:19:11 +01:00
|
|
|
last_archive_checksum = previous_file ? Checksum.file(previous_file) : nil
|
2019-01-10 10:52:29 +01:00
|
|
|
ApplicationController.new.view_context.render(
|
|
|
|
partial: 'archive/accounting',
|
2019-01-31 12:19:50 +01:00
|
|
|
locals: {
|
|
|
|
invoices: invoices,
|
|
|
|
code_checksum: code_checksum,
|
|
|
|
last_archive_checksum: last_archive_checksum,
|
|
|
|
previous_file: previous_file,
|
|
|
|
software_version: Version.current
|
|
|
|
},
|
2019-01-10 10:52:29 +01:00
|
|
|
formats: [:json],
|
|
|
|
handlers: [:jbuilder]
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2019-01-31 12:19:50 +01:00
|
|
|
def previous_period
|
2019-02-12 16:19:11 +01:00
|
|
|
AccountingPeriod.where('closed_at < ?', closed_at).order(closed_at: :desc).limit(1).last
|
2019-01-31 12:19:50 +01:00
|
|
|
end
|
|
|
|
|
2019-01-10 10:52:29 +01:00
|
|
|
def archive_closed_data
|
|
|
|
data = Invoice.where('created_at >= :start_date AND created_at < :end_date', start_date: start_at, end_date: end_at)
|
|
|
|
.includes(:invoice_items)
|
|
|
|
File.write(archive_file, to_json_archive(data))
|
|
|
|
end
|
2019-01-07 12:29:52 +01:00
|
|
|
end
|