# frozen_string_literal: true require 'date' module Codat module Models class FinancialSheet < BaseModel # Default period length (months) DEFAULT_PERIOD_LENGTH = 12 # Default number of periods to compare DEFAULT_PERIODS_TO_COMPARE = 2 attr_reader :reports def self.inherited(other) super other.attributes :currency, :most_recent_available_month, :earliest_available_month end # Finds the latest financial sheet for a company. This can be a balance sheet or a profit and # loss document. # # Params are listed below: # * company_id - the company ID from Codat # * period_length - the number of months to get # * periods_to_compare - how many periods (of period_length size) you want # * start_month (optional) - starting in which month (date) # # An ArgumentError is raised unless you provide a :company_id key in the params. def self.find(params = {}) company_id = params[:company_id] raise ArgumentError, 'please provide company_id' unless company_id url = format_url(@endpoint, company_id: company_id.to_s.strip) result = get(url, build_query(params)) return nil unless successful_response?(result) new(json: result.body) end def self.build_query(params) options = params.dup query = { periodLength: options.fetch(:period_length, DEFAULT_PERIOD_LENGTH), periodsToCompare: options.fetch(:periods_to_compare, DEFAULT_PERIODS_TO_COMPARE) } options = options.transform_keys { |key| Camelizer.transform(key) } query.merge(options) end def self.report_class(report_class = nil) return @report_class unless report_class @report_class = report_class end def self.endpoint(endpoint = nil) return @endpoint unless endpoint @endpoint = endpoint end def initialize(json: {}) super @most_recent_available_month = Date.parse(json[:mostRecentAvailableMonth]) @earliest_available_month = Date.parse(json[:earliestAvailableMonth]) reports_json = json.fetch(:reports, {}) @reports = reports_json.map { |report| self.class.report_class.new(json: report) } end end end end