Class: FinancialYear

Inherits:
Ekylibre::Record::Base show all
Includes:
Attachable, Customizable
Defined in:
app/models/financial_year.rb

Overview

Informations

License

Ekylibre - Simple agricultural ERP Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon Copyright (C) 2010-2012 Brice Texier Copyright (C) 2012-2019 Brice Texier, David Joulin

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see www.gnu.org/licenses.

Table: financial_years

accountant_id             :integer
closed                    :boolean          default(FALSE), not null
code                      :string           not null
created_at                :datetime         not null
creator_id                :integer
currency                  :string           not null
currency_precision        :integer
custom_fields             :jsonb
id                        :integer          not null, primary key
last_journal_entry_id     :integer
lock_version              :integer          default(0), not null
started_on                :date             not null
stopped_on                :date             not null
tax_declaration_frequency :string
tax_declaration_mode      :string           not null
updated_at                :datetime         not null
updater_id                :integer

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Customizable

#custom_value, #set_custom_value, #validate_custom_fields

Methods inherited from Ekylibre::Record::Base

#already_updated?, #check_if_destroyable?, #check_if_updateable?, columns_definition, #customizable?, customizable?, #customized?, #destroyable?, #editable?, has_picture, #human_attribute_name, nomenclature_reflections, #old_record, #others, refers_to, #unsuppress, #updateable?

Methods included from Userstamp::Stampable

included

Methods included from Userstamp::Stamper

included

Class Method Details

.at(searched_at = Time.zone.now) ⇒ Object Also known as: ensure_exists_at!

Find or create if possible the requested financial year for the searched date


98
99
100
# File 'app/models/financial_year.rb', line 98

def at(searched_at = Time.zone.now)
  on(searched_at.to_date)
end

.balance_expr(credit = false, options = {}) ⇒ Object


358
359
360
361
362
363
364
365
366
367
# File 'app/models/financial_year.rb', line 358

def self.balance_expr(credit = false, options = {})
  columns = %i[debit credit]
  columns.reverse! if credit
  prefix = (options[:record] ? options.delete(:record).to_s + '.' : '') + 'local_'
  if options[:forced]
    return "(#{prefix}#{columns[0]} - #{prefix}#{columns[1]})"
  else
    return "(CASE WHEN #{prefix}#{columns[0]} > #{prefix}#{columns[1]} THEN #{prefix}#{columns[0]} - #{prefix}#{columns[1]} ELSE 0 END)"
  end
end

.closableObject


111
112
113
# File 'app/models/financial_year.rb', line 111

def closable
  closables.first
end

.currentObject


107
108
109
# File 'app/models/financial_year.rb', line 107

def current
  on(Time.zone.today)
end

.first_of_allObject


103
104
105
# File 'app/models/financial_year.rb', line 103

def first_of_all
  reorder(:started_on).first
end

.last_closureObject

Returns the date of the last closure if any


116
117
118
119
120
121
# File 'app/models/financial_year.rb', line 116

def last_closure
  if year = closed.reorder(started_on: :desc).first
    return year.stopped_on
  end
  nil
end

.on(searched_on) ⇒ Object


86
87
88
89
90
91
92
93
94
95
# File 'app/models/financial_year.rb', line 86

def on(searched_on)
  year = where('? BETWEEN started_on AND stopped_on', searched_on).order(started_on: :desc).first
  return year if year
  born_on = Entity.of_company.born_on
  return nil if searched_on < born_on
  year = FinancialYear.where('stopped_on < ?', searched_on).order(stopped_on: :desc).first
  year ||= FinancialYear.create_with(stopped_on: (born_on >> 11).end_of_month).find_or_create_by!(started_on: born_on)
  year = year.find_or_create_next! while year.stopped_on < searched_on
  year
end

Instance Method Details

#balance(accounts, credit = false) ⇒ Object

Computes the value of list of accounts in a String 123 will take all accounts 123* ^456 will remove all accounts 456* 789X will compute the balance although result is negative


310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'app/models/financial_year.rb', line 310

def balance(accounts, credit = false)
  normals = ['(XD)']
  excepts = []
  negatives = []
  forceds = []
  accounts.strip.split(/\s*[\,\s]+\s*/).each do |prefix|
    code = prefix.gsub(/(^(\-|\^)|[CDX]+$)/, '')
    excepts << code if prefix =~ /^\^\d+$/
    negatives << code if prefix =~ /^\-\d+/
    forceds << code if prefix =~ /^\-?\d+[CDX]$/
    normals << code if prefix =~ /^\-?\d+[CDX]?$/
  end

  balance = FinancialYear.balance_expr(credit)
  if !forceds.empty? || !negatives.empty?
    forceds_and_negatives = forceds & negatives
    balance = 'CASE'
    balance << ' WHEN ' + forceds_and_negatives.sort.collect { |c| "a.number LIKE '#{c}%'" }.join(' OR ') + " THEN -#{FinancialYear.balance_expr(!credit, forced: true)}" unless forceds_and_negatives.empty?
    balance << ' WHEN ' + forceds.collect { |c| "a.number LIKE '#{c}%'" }.join(' OR ') + " THEN #{FinancialYear.balance_expr(credit, forced: true)}" unless forceds.empty?
    balance << ' WHEN ' + negatives.sort.collect { |c| "a.number LIKE '#{c}%'" }.join(' OR ') + " THEN -#{FinancialYear.balance_expr(!credit)}" unless negatives.empty?
    balance << " ELSE #{FinancialYear.balance_expr(credit)} END"
  end

  query = "SELECT sum(#{balance}) AS balance FROM #{AccountBalance.table_name} AS ab JOIN #{Account.table_name} AS a ON (a.id=ab.account_id) WHERE ab.financial_year_id=#{id}"
  query << ' AND (' + normals.sort.collect { |c| "a.number LIKE '#{c}%'" }.join(' OR ') + ')'
  query << ' AND NOT (' + excepts.sort.collect { |c| "a.number LIKE '#{c}%'" }.join(' OR ') + ')' unless excepts.empty?
  balance = ActiveRecord::Base.connection.select_value(query)
  (balance.blank? ? nil : balance.to_d)
end

#can_create_exchange?Boolean

Returns:

  • (Boolean)

407
408
409
# File 'app/models/financial_year.rb', line 407

def can_create_exchange?
  accountant_with_booked_journal? && !opened_exchange?
end

#closable?(noticed_on = nil) ⇒ Boolean

tests if the financial_year can be closed.

Returns:

  • (Boolean)

228
229
230
231
# File 'app/models/financial_year.rb', line 228

def closable?(noticed_on = nil)
  list = closure_obstructions(noticed_on)
  list.empty?
end

#close(to_close_on = nil, options = {}) ⇒ Object

When a financial year is closed,.all the matching journals are closed too.


250
251
252
# File 'app/models/financial_year.rb', line 250

def close(to_close_on = nil, options = {})
  FinancialYearClose.new(self, to_close_on, options).execute
end

#closure_obstructions(noticed_on = nil) ⇒ Object


216
217
218
219
220
221
222
223
224
225
# File 'app/models/financial_year.rb', line 216

def closure_obstructions(noticed_on = nil)
  noticed_on ||= Time.zone.today
  list = []
  list << :financial_year_already_closed if closed
  list << :draft_journal_entries_are_present if journal_entries.where(state: :draft).any?
  list << :previous_financial_year_is_not_closed if previous && !previous.closed
  list << :unbalanced_journal_entries_are_present_in_year unless journal_entries.where('debit != credit').empty?
  list << :financial_year_is_not_past if stopped_on >= noticed_on
  list
end

#closures(noticed_on = nil) ⇒ Object


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'app/models/financial_year.rb', line 233

def closures(noticed_on = nil)
  noticed_on ||= Time.zone.today
  array = []
  first_year = self.class.order('started_on').first
  if (first_year.nil? || first_year == self) && self.class.count <= 1
    date = started_on.end_of_month
    while date < noticed_on
      array << date
      date = (date + 1).end_of_month
    end
  else
    array << stopped_on
  end
  array
end

#compute_balances!Object

Re-create all account_balances record for the financial year


370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'app/models/financial_year.rb', line 370

def compute_balances!
  results = ActiveRecord::Base.connection.select_all("SELECT account_id, sum(debit) AS debit, sum(credit) AS credit, count(id) AS count FROM #{JournalEntryItem.table_name} WHERE state != 'draft' AND printed_on BETWEEN #{self.class.connection.quote(started_on)} AND #{self.class.connection.quote(stopped_on)} GROUP BY account_id")
  .clear
  results.each do |result|
    .create!(
      account_id: result['account_id'].to_i,
      local_count: result['count'].to_i,
      local_credit: result['credit'].to_f,
      local_debit: result['debit'].to_f,
      currency: self.currency
    )
  end
  self
end

#credit_balance(accounts) ⇒ Object

Computes and formats credit balance for an account regexp Use I18n to produce string


351
352
353
354
355
356
# File 'app/models/financial_year.rb', line 351

def credit_balance(accounts)
  if value = balance(accounts, true)
    return value.l(currency: self.currency)
  end
  nil
end

#debit_balance(accounts) ⇒ Object

Computes and formats debit balance for an account regexp Use I18n to produce string


342
343
344
345
346
347
# File 'app/models/financial_year.rb', line 342

def debit_balance(accounts)
  if value = balance(accounts, false)
    return value.l(currency: self.currency)
  end
  nil
end

#default_codeObject


212
213
214
# File 'app/models/financial_year.rb', line 212

def default_code
  tc('code.' + (started_on.year != stopped_on.year ? 'double' : 'single'), first_year: started_on.year, second_year: stopped_on.year)
end

#find_or_create_next!Object

Find or create the next financial year based on the date of the current


265
266
267
268
269
270
# File 'app/models/financial_year.rb', line 265

def find_or_create_next!
  unless (year = self.next)
    year = self.class.create!(started_on: stopped_on + 1.day, stopped_on: (stopped_on >> 12).end_of_month, currency: self.currency)
  end
  year
end

#find_or_create_previous!Object

Find or create the previous financial year based on the date of the current


273
274
275
276
277
278
# File 'app/models/financial_year.rb', line 273

def find_or_create_previous!
  unless (year = previous)
    year = self.class.create!(started_on: started_on << 12, stopped_on: started_on - 1, currency: self.currency)
  end
  year
end

#generate_last_journal_entry(options = {}) ⇒ Object

Generate last journal entry with financial assets depreciations (optionnally)


386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'app/models/financial_year.rb', line 386

def generate_last_journal_entry(options = {})
  unless last_journal_entry
    create_last_journal_entry!(printed_on: stopped_on, journal_id: options[:journal_id])
  end

  # Empty journal entry
  last_journal_entry.items.clear

  if options[:fixed_assets_depreciations]
    for depreciation in fixed_asset_depreciations.includes(:fixed_asset)
      name = tc(:bookkeep, resource: FixedAsset.model_name.human, number: depreciation.fixed_asset.number, name: depreciation.fixed_asset.name, position: depreciation.position, total: depreciation.fixed_asset.depreciations.count)
      # Charges
      last_journal_entry.add_debit(name, depreciation.fixed_asset., depreciation.amount)
      # Allocation
      last_journal_entry.add_credit(name, depreciation.fixed_asset., depreciation.amount)
      depreciation.update_attributes(journal_entry_id: last_journal_entry.id)
    end
  end
  self
end

#get_mandatory_line_calculation(document = :profit_and_loss_statement, line = nil) ⇒ Object

get the equation to compute from accountancy abacus


288
289
290
291
292
293
294
295
# File 'app/models/financial_year.rb', line 288

def get_mandatory_line_calculation(document = :profit_and_loss_statement, line = nil)
  ac = Account.accounting_system
  source = Rails.root.join('config', 'accoutancy_mandatory_documents.yml')
  data = YAML.load_file(source).deep_symbolize_keys.stringify_keys if source.file?
  if data && ac && document && line
    data[ac.to_s][document][line] if data[ac.to_s] && data[ac.to_s][document]
  end
end

#journal_entries(conditions = nil) ⇒ Object


156
157
158
159
160
161
162
163
# File 'app/models/financial_year.rb', line 156

def journal_entries(conditions = nil)
  entries = JournalEntry.where(printed_on: started_on..stopped_on)
  if conditions.present?
    ActiveSupport::Deprecation.warn('Use of conditions in FinancialYear#journal_entries is deprecated. Please use #where after instead.')
    entries = entries.where(conditions)
  end
  entries
end

#missing_tax_declaration?Boolean

Returns:

  • (Boolean)

169
170
171
172
# File 'app/models/financial_year.rb', line 169

def missing_tax_declaration?
  !tax_declaration_frequency_none? &&
    TaxDeclaration.where('? BETWEEN started_on AND stopped_on', stopped_on).empty?
end

#nameObject


165
166
167
# File 'app/models/financial_year.rb', line 165

def name
  code
end

#nextObject

this method returns the next financial_year by default.


260
261
262
# File 'app/models/financial_year.rb', line 260

def next
  self.class.find_by(started_on: stopped_on + 1)
end

#next_tax_declaration_onObject


174
175
176
177
178
179
180
181
# File 'app/models/financial_year.rb', line 174

def next_tax_declaration_on
  declarations = TaxDeclaration.where('stopped_on BETWEEN ? AND ?', started_on, stopped_on)
  if declarations.any?
    declarations.order(stopped_on: :desc).first.stopped_on + 1
  else
    started_on
  end
end

#opened_exchange?Boolean

Returns:

  • (Boolean)

411
412
413
# File 'app/models/financial_year.rb', line 411

def opened_exchange?
  exchanges.opened.any?
end

#previousObject

this method returns the previous financial_year by default.


255
256
257
# File 'app/models/financial_year.rb', line 255

def previous
  self.class.find_by(stopped_on: started_on - 1)
end

#previous_codes_with_missing_tax_declarationObject


200
201
202
203
204
205
# File 'app/models/financial_year.rb', line 200

def previous_codes_with_missing_tax_declaration
  FinancialYear.with_missing_tax_declaration
               .where('financial_years.stopped_on < ?', stopped_on)
               .order(:started_on)
               .pluck(:code)
end

#previous_consecutives?Boolean

Returns:

  • (Boolean)

207
208
209
210
# File 'app/models/financial_year.rb', line 207

def previous_consecutives?
  years = FinancialYear.select(:started_on, :stopped_on).where('started_on <= ?', started_on).order(:started_on)
  years[1..-1].find.with_index { |year, index| year.started_on - years[index].stopped_on > 1 }.blank?
end

#split_into_periods(interval) ⇒ Object


415
416
417
418
419
420
421
422
423
424
425
426
# File 'app/models/financial_year.rb', line 415

def split_into_periods(interval)
  case interval
  when 'year'
    [[started_on, stopped_on]]
  when 'semesters'
    compute_ranges(6)
  when 'trimesters'
    compute_ranges(3)
  when 'months'
    compute_ranges(1)
  end
end

#sum_entry_items(expression, options = {}) ⇒ Object

See Journal.sum_entry_items


281
282
283
284
285
# File 'app/models/financial_year.rb', line 281

def sum_entry_items(expression, options = {})
  options[:started_on] ||= started_on
  options[:stopped_on] ||= stopped_on
  Journal.sum_entry_items(expression, options)
end

#sum_entry_items_with_mandatory_line(document = :profit_and_loss_statement, line = nil, options = {}) ⇒ Object


297
298
299
300
301
302
303
304
# File 'app/models/financial_year.rb', line 297

def sum_entry_items_with_mandatory_line(document = :profit_and_loss_statement, line = nil, options = {})
  # remove closure entries
  options[:unwanted_journal_nature] ||= [:closure] if document == :balance_sheet
  options[:unwanted_journal_nature] ||= %i[result closure]

  equation = get_mandatory_line_calculation(document, line) if line
  equation ? sum_entry_items(equation, options) : 0
end

#tax_declaration_frequency_durationObject


183
184
185
186
187
188
189
190
191
# File 'app/models/financial_year.rb', line 183

def tax_declaration_frequency_duration
  if tax_declaration_frequency_monthly?
    1.month
  elsif tax_declaration_frequency_quaterly?
    3.months
  elsif tax_declaration_frequency_yearly?
    12.months
  end
end

#tax_declaration_stopped_on(from_on) ⇒ Object


193
194
195
196
197
198
# File 'app/models/financial_year.rb', line 193

def tax_declaration_stopped_on(from_on)
  return nil if tax_declaration_frequency_none?
  end_on = (from_on + tax_declaration_frequency_duration).beginning_of_month - 1
  end_on = stopped_on if end_on > stopped_on
  end_on
end