module Eco module API module Common module People # Helper factory to build `Ecoportal::API::V1::Person` or `Ecoportal::API::Internal::Person` objects # @attr_reader schema [Ecoportal::API::V1::PersonSchema] person schema to be used in this person factory # @attr_reader schema_attrs [Array] _inernal names_ of the schema fields/attributes class PersonFactory attr_reader :schema, :schema_attrs def initialize(person: {}, schema: {}, account: {}, modifier: Common::People::PersonModifier.new) @modifier = Common::People::PersonModifier.new(modifier) @person = person @account = account @schema = schema @schema_attrs = @schema&.fields&.map { |fld| fld.alt_id } end def new(person: nil) in_raw_modifier = Common::People::PersonModifier.new.no_details return PersonFactory.new(person: person, schema: @schema, modifier: in_raw_modifier).new unless !person person = klass.new(person_hash(@person)) person.account = account_hash(@account) if @modifier.add_account? && @modifier.internal? person.add_details(@schema) unless @modifier.no_details? person end def new_contact(schema) factory = self.class.new(@modifier.reset_account, person: @person, schema: @schema, account: @account) factory.new end def new_doc new_hash(@modifier) end def schema_id nil if !@schema @schema['schema_id'] || @schema['id'] end private def klass if @modifier.external? Ecoportal::API::V1::Person else Ecoportal::API::Internal::Person end end def new_hash(modifier) modifier = Common::People::PersonModifier.new(modifier) doc = person_hash(@person) doc = add_account(doc, @account) if modifier.add_account? && modifier.internal? doc = add_details(doc, @schema) unless modifier.no_details? end def add_details(doc, details) return nil if !doc doc_det = details_hash(details) doc.merge({ "details" => doc_det }) end def add_account(doc, account) return nil if !doc doc_acc = account_hash(account) doc.merge({ "account" => doc_acc }) end def person_hash(person) case person when Ecoportal::API::V1::Person JSON.parse(person.doc.to_json) when Hash JSON.parse(person.to_json) else {} end end def details_hash(details) case details when Ecoportal::API::V1::PersonDetails doc = JSON.parse(details.doc.to_json) when Ecoportal::API::V1::PersonSchema doc =JSON.parse(details.doc.to_json) when Hash doc = JSON.parse(details.to_json) doc = doc["details"] if doc.key?("details") else doc = {} end doc["schema_id"] = doc.delete("id") if doc&.key?("id") doc end def account_hash(account) case when account.is_a?(Ecoportal::API::Internal::Account) JSON.parse(account.doc.to_json) when account.is_a?(Hash) doc = JSON.parse(account.to_json) doc["account"] if doc.key?("account") else {} end end end end end end end