# frozen_string_literal: true require 'work_day' module ROI module RentabilityPeriods def days(days_amount = 1) scoped_start = WorkDay.last_until(end_date - days_amount) format(scoped_start, end_date) end def current_month scoped_start = WorkDay.last_until((end_date - 1.month).end_of_month) check_gaps_and_format(adjust_start_date(scoped_start), end_date) end def months(amount, date = end_date) scoped_start = WorkDay.last_until((date - amount.month).end_of_month) scoped_end = adjust_end_date(date) check_gaps_and_format(scoped_start, scoped_end) end def current_year scoped_start = WorkDay.last_until((end_date - 1.year).end_of_year) format(adjust_start_date(scoped_start), end_date) end def years_ago(amount) scoped_end = WorkDay.last_until((end_date - amount.year).end_of_year) scoped_start = WorkDay.last_until((scoped_end - 1.year).end_of_year) format(adjust_start_date(scoped_start), scoped_end) end def portfolio format(start_date, end_date) end private def adjust_start_date(date) [start_date, date].compact.max end def adjust_end_date(date) scoped_end = if date.strftime('%Y-%m') == end_date.strftime('%Y-%m') end_date else date.end_of_month end WorkDay.last_until(scoped_end) end def format(start_date, end_date) scoped_start, scoped_end = rentabilities.values_at(start_date, end_date) if scoped_start && scoped_end ((scoped_end.quota / scoped_start.quota - 1) * 100).round(8) end end def check_gaps_and_format(scoped_start, scoped_end) local_start, local_end = rentabilities.values_at(scoped_start, scoped_end) return unless local_start && local_end return if skip_on_gap && gap?(local_start, local_end) format(scoped_start, scoped_end) end def gap?(start_date, end_date) gap = rentabilities.values.detect do |line| line.reference_date.between?( start_date.reference_date, end_date.reference_date ) && !line.have_position end !gap.nil? end end end