module Ecoportal module API class V1 class Person < Common::BaseModel passthrough :id, :external_id, :name, :email, :supervisor_id, :subordinates, to: :doc def supervisor(client) return @supervisor if defined?(@supervisor) return @supervisor = nil if supervisor_id.nil? @supervisor = client.people.get(supervisor_id).result end def supervisor=(person) self.supervisor_id = person.id end def as_json super.merge "details" => details&.as_json end def details return @details if defined?(@details) return @details = nil if doc["details"].nil? @details = person_details_class.new(doc["details"]) end def details=(value) case value when NilClass doc["details"] = nil when person_details_class doc["details"] = value.as_json when Hash doc["details"] = value.slice("schema_id", "fields") else raise "Invalid set on details: Need nil, PersonDetails or Hash; got #{value.class}" end remove_instance_variable("@details") if defined?(@details) details.tap do |details| # When reassigning details, mark the whole thing as dirty details&.instance_variable_set("@original_doc", {}) end end def add_details(schema_or_id) person_details_class.new.tap do |new_details| case schema_or_id when person_schema_class schema_or_id.initialize_details(new_details) when String new_details.schema_id = schema_or_id end self.details = new_details # Patch out static data from as_update @original_doc["details"] = { "fields" => JSON.parse(doc["details"]["fields"].to_json) } end self.details.tap do |details| # Patch out static data from as_update original = details.instance_variable_get("@original_doc") original["fields"] = JSON.parse(doc["details"]["fields"].to_json) end end private def person_schema_class V1::PersonSchema end def person_details_class V1::PersonDetails end end end end end