Exemplo n.º 1
0
 def _call_search_service(self,
                          mapping_name,
                          service_name,
                          result_name,
                          method='GET'):
     """
     Calls the given search service for the global childpool
     :param mapping_name: Name of the action mapping to use the correct
                          mapping.
     :param service_name: URL endpoint of the search service to call
     :param result_name: Name of the wrapping tag for the answer
     :param method: Method URL (GET or POST)
     :return:
     """
     mapping = base_mapping.new_onramp_mapping(self._name, self.env,
                                               mapping_name)
     params = mapping.get_connect_data(self)
     onramp = OnrampConnector()
     if method == 'POST':
         result = onramp.send_message(service_name, method, params)
     else:
         result = onramp.send_message(service_name, method, None, params)
     if result['code'] == 200:
         self.nb_found = result['content'].get('NumberOfBeneficiaries', 0)
         mapping = base_mapping.new_onramp_mapping(
             'compassion.global.child', self.env)
         if not result['content'][result_name]:
             raise UserError(_("No children found meeting criterias"))
         new_children = self.env['compassion.global.child']
         for child_data in result['content'][result_name]:
             child_vals = mapping.get_vals_from_connect(child_data)
             child_vals['search_view_id'] = self.id
             new_children += self.env['compassion.global.child'].create(
                 child_vals)
         restricted_children = new_children - new_children.filtered(
             'field_office_id.available_on_childpool')
         new_children -= restricted_children
         self.nb_restricted_children = len(restricted_children)
         restricted_children.unlink()
         self.global_child_ids += new_children
     else:
         error = result.get('content', result)['Error']
         if isinstance(error, dict):
             error = error.get('ErrorMessage')
         raise UserError(error)
    def _call_search_service(self,
                             mapping_name,
                             service_name,
                             result_name,
                             method="GET"):
        """
        Calls the given search service for the global childpool
        :param mapping_name: Name of the action mapping to use the correct
                             mapping.
        :param service_name: URL endpoint of the search service to call
        :param result_name: Name of the wrapping tag for the answer
        :param method: Method URL (GET or POST)
        :return:
        """
        params = self.data_to_json(mapping_name)
        onramp = OnrampConnector()
        if method == "POST":
            result = onramp.send_message(service_name, method, params)
        else:
            result = onramp.send_message(service_name, method, None, params)
        if result["code"] == 200:
            self.nb_found = result["content"].get("NumberOfBeneficiaries", 0)

            if not result["content"][result_name]:
                raise UserError(_("No children found meeting criterias"))
            new_children = self.env["compassion.global.child"]
            for child_data in result["content"][result_name]:
                child_vals = new_children.json_to_data(
                    child_data, "Childpool Search Response")
                child_vals["search_view_id"] = self.id
                new_children += self.env["compassion.global.child"].create(
                    child_vals)
            restricted_children = new_children - new_children.filtered(
                "field_office_id.available_on_childpool")
            new_children -= restricted_children
            self.nb_restricted_children = len(restricted_children)
            restricted_children.unlink()
            self.global_child_ids += new_children
        else:
            error = result.get("content", result)["Error"]
            if isinstance(error, dict):
                error = error.get("ErrorMessage")
            raise UserError(error)
 def _call_search_service(self, mapping_name, service_name, result_name,
                          method='GET'):
     """
     Calls the given search service for the global childpool
     :param mapping_name: Name of the action mapping to use the correct
                          mapping.
     :param service_name: URL endpoint of the search service to call
     :param result_name: Name of the wrapping tag for the answer
     :param method: Method URL (GET or POST)
     :return:
     """
     mapping = base_mapping.new_onramp_mapping(
         self._name, self.env, mapping_name)
     params = mapping.get_connect_data(self)
     onramp = OnrampConnector()
     if method == 'POST':
         result = onramp.send_message(service_name, method, params)
     else:
         result = onramp.send_message(service_name, method, None, params)
     if result['code'] == 200:
         self.nb_found = result['content'].get('NumberOfBeneficiaries', 0)
         mapping = base_mapping.new_onramp_mapping(
             'compassion.global.child', self.env)
         if not result['content'][result_name]:
             raise UserError(_("No children found meeting criterias"))
         new_children = self.env['compassion.global.child']
         for child_data in result['content'][result_name]:
             child_vals = mapping.get_vals_from_connect(child_data)
             child_vals['search_view_id'] = self.id
             new_children += self.env['compassion.global.child'].create(
                 child_vals)
         restricted_children = new_children - new_children.filtered(
             'field_office_id.available_on_childpool')
         new_children -= restricted_children
         self.nb_restricted_children = len(restricted_children)
         restricted_children.unlink()
         self.global_child_ids += new_children
     else:
         error = result.get('content', result)['Error']
         if isinstance(error, dict):
             error = error.get('ErrorMessage')
         raise UserError(error)
Exemplo n.º 4
0
 def get_lifecycle_event(self):
     onramp = OnrampConnector()
     endpoint = "beneficiaries/{}/kits/beneficiarylifecycleeventkit"
     lifecylcle_ids = list()
     for child in self:
         result = onramp.send_message(endpoint.format(child.global_id), "GET")
         if "BeneficiaryLifecycleEventList" in result.get("content", {}):
             lifecylcle_ids.extend(
                 self.env["compassion.child.ble"].process_commkit(result["content"])
             )
     return lifecylcle_ids
 def get_lifecycle_event(self):
     onramp = OnrampConnector()
     endpoint = 'beneficiaries/{}/kits/beneficiarylifecycleeventkit'
     lifecylcle_ids = list()
     for child in self:
         result = onramp.send_message(
             endpoint.format(child.global_id), 'GET')
         if 'BeneficiaryLifecycleEventList' in result.get('content', {}):
             lifecylcle_ids.extend(self.env[
                 'compassion.child.ble'].process_commkit(result['content']))
     return lifecylcle_ids
Exemplo n.º 6
0
 def get_lifecycle_event(self):
     onramp = OnrampConnector()
     endpoint = 'churchpartners/{}/kits/icplifecycleeventkit'
     lifecylcle_ids = list()
     for project in self:
         result = onramp.send_message(endpoint.format(project.fcp_id),
                                      'GET')
         if 'ICPLifecycleEventList' in result.get('content', {}):
             lifecylcle_ids.extend(
                 self.env['compassion.project.ile'].process_commkit(
                     result['content']))
     return lifecylcle_ids
 def get_lifecycle_event(self):
     onramp = OnrampConnector()
     endpoint = 'beneficiaries/{}/kits/beneficiarylifecycleeventkit'
     lifecylcle_ids = list()
     for child in self:
         result = onramp.send_message(endpoint.format(child.global_id),
                                      'GET')
         if 'BeneficiaryLifecycleEventList' in result.get('content', {}):
             lifecylcle_ids.extend(
                 self.env['compassion.child.ble'].process_commkit(
                     result['content']))
     return lifecylcle_ids
Exemplo n.º 8
0
 def get_lifecycle_event(self):
     onramp = OnrampConnector()
     endpoint = "churchpartners/{}/kits/icplifecycleeventkit"
     lifecylcle_ids = list()
     for project in self:
         result = onramp.send_message(endpoint.format(project.fcp_id),
                                      "GET")
         if "ICPLifecycleEventList" in result.get("content", {}):
             lifecylcle_ids.extend(
                 self.env["compassion.project.ile"].process_commkit(
                     result["content"]))
     return lifecylcle_ids
 def get_lifecycle_event(self):
     onramp = OnrampConnector()
     endpoint = 'churchpartners/{}/kits/icplifecycleeventkit'
     lifecylcle_ids = list()
     for project in self:
         result = onramp.send_message(
             endpoint.format(project.icp_id), 'GET')
         if 'ICPLifecycleEventList' in result.get('content', {}):
             lifecylcle_ids.extend(
                 self.env['compassion.project.ile'].process_commkit(
                     result['content']))
     return lifecylcle_ids
 def fetch_missing_relational_records(self, field_relation, field_name,
                                      values, json_name):
     onramp = OnrampConnector()
     endpoint = "churchpartners/{0}/kits/icpkit?FinalLanguage={1}"
     languages_map = {
         "English": "en_US",
         "French": "fr_CH",
         "German": "de_DE",
         "Italian": "it_IT",
     }
     # transform values to list first
     if not isinstance(values, list):
         values = [values]
     # go over all missing values, keep count of index to know which translation
     # to take from onramp result
     for i, value in enumerate(values):
         # check if hobby/household duty, etc... exists in our database
         search_vals = [(field_name, "=", value)]
         relation_obj = self.env[field_relation].sudo()
         if hasattr(relation_obj, "value"):
             # Useful for connect.multipicklist objects
             search_vals.insert(0, "|")
             search_vals.append(("value", "=", value))
         search_count = relation_obj.search_count(search_vals)
         # if not exist, then create it
         if not search_count:
             value_record = (relation_obj.create({
                 field_name: value,
                 "value": value
             }))
             if not hasattr(relation_obj, "value"):
                 return
             # fetch translations for connect.multipicklist values
             must_manually_translate = False
             for lang_literal, lang_context in languages_map.items():
                 result = onramp.send_message(
                     endpoint.format(self[0].fcp_id, lang_literal), "GET")
                 if "ICPResponseList" in result.get("content", {}):
                     content = result["content"]["ICPResponseList"][0]
                     if json_name in content:
                         content_values = content[json_name]
                         if not isinstance(content_values, list):
                             content_values = [content_values]
                         translation = content_values[i]
                         if translation == value_record.value:
                             must_manually_translate = True
                         value_record.with_context(
                             lang=lang_context).value = translation
             if must_manually_translate:
                 value_record.assign_translation()
    def fetch_missing_relational_records(self, field_relation, field_name,
                                         values, json_name):
        """ Fetch missing relational records in various languages.

        Method used to catch and create missing values and translations of fields
        received by GMC.

        :param field_relation: relation
        :param field_name: name of field in the relation
        :param values: missing relational values
        :param json_name: key name in content
        :type field_relation: str
        :type values: str or list of str
        :type json_name: str

        """
        onramp = OnrampConnector()
        # mapping of languages for translations
        languages_map = {
            "English": "en_US",
            "French": "fr_CH",
            "German": "de_DE",
            "Italian": "it_IT",
        }
        # mapping for endpoints
        endpoint_map = {
            "compassion.child":
            "beneficiaries/{0}/details?FinalLanguage={1}",
            "compassion.project":
            "churchpartners/{0}/kits/icpkit?FinalLanguage={1}",
            "compassion.intervention":
            "interventions/{0}/kits/InterventionKit?"
            "FinalLanguage={1}"
        }
        # mapping for key to fetch content in GMC result
        content_key_map = {
            "compassion.child": "BeneficiaryResponseList",
            "compassion.project": "ICPResponseList",
            "compassion.intervention": "InterventionDetailsRequest"
        }
        # mapping for id of object passed
        id_map = {
            "compassion.child": "global_id",
            "compassion.project": "fcp_id",
            "compassion.intervention": "intervention_id"
        }
        # declare variables from mappings
        try:
            endpoint = endpoint_map[self._name]
            content_key = content_key_map[self._name]
            id_ = id_map[self._name]
        except KeyError:
            raise MappingKeyNotFound(
                _("Model %s has not yet been defined in mappings when fetching "
                  "missing relational records") % (self._name))
        # transform values to list first
        if not isinstance(values, list):
            values = [values]
        # go over all missing values, keep count of index to know which translation
        # to take from onramp result
        for i, value in enumerate(values):
            # check if hobby/household duty, etc... exists in our database
            search_vals = [(field_name, "=", value)]
            relation_obj = self.env[field_relation].sudo()
            if hasattr(relation_obj, "value"):
                # Useful for connect.multipicklist objects
                search_vals.insert(0, "|")
                search_vals.append(("value", "=", value))
            search_count = relation_obj.search_count(search_vals)
            # if not exist, then create it
            if not search_count:
                value_record = (relation_obj.create({
                    field_name: value,
                    "value": value
                }))
                if not hasattr(relation_obj, "value"):
                    return
                # fetch translations for connect.multipicklist values
                must_manually_translate = False
                for lang_literal, lang_context in languages_map.items():
                    result = onramp.send_message(
                        endpoint.format(getattr(self, id_), lang_literal),
                        "GET")
                    if content_key in result.get("content", {}):
                        content = result["content"][content_key][0]
                        if json_name in content:
                            content_values = content[json_name]
                            if not isinstance(content_values, list):
                                content_values = [content_values]
                            translation = content_values[i]
                            if translation == value_record.value:
                                must_manually_translate = True
                            value_record.with_context(
                                lang=lang_context).value = translation
                if must_manually_translate:
                    value_record.assign_translation()
Exemplo n.º 12
0
    def fetch_missing_relational_records(self, field_relation, field_name,
                                         values, json_name):
        """ Fetch missing relational records in various languages.

        Method used to catch missing values for household duties, hobbies,
        and Christian activities of compassion.child and write them onto
        the database.

        :param field_relation: relation
        :param field_name: name of field in the relation
        :param values: missing relational values
        :param json_name: key name in content
        :type field_relation: str
        :type values: str or list of str
        :type json_name: str

        TODO: check if value already exists in another form (spaces, with regex...)

        """
        onramp = OnrampConnector()
        endpoint = "beneficiaries/{0}/details?FinalLanguage={1}"
        languages_map = {
            "English": "en_US",
            "French": "fr_CH",
            "German": "de_DE",
            "Italian": "it_IT",
        }
        # transform values to list first
        if not isinstance(values, list):
            values = [values]
        # go over all missing values, keep count of index to know which translation
        # to take from onramp result
        for i, value in enumerate(values):
            # check if hobby/household duty, etc... exists in our database
            search_vals = [(field_name, "=", value)]
            relation_obj = self.env[field_relation].sudo()
            if hasattr(relation_obj, "value"):
                # Useful for connect.multipicklist objects
                search_vals.insert(0, "|")
                search_vals.append(("value", "=", value))
            search_count = relation_obj.search_count(search_vals)
            # if not exist, then create it
            if not search_count:
                value_record = (relation_obj.create({
                    field_name: value,
                    "value": value
                }))
                if not hasattr(relation_obj, "value"):
                    return
                # fetch translations for connect.multipicklist values
                must_manually_translate = False
                for lang_literal, lang_context in languages_map.items():
                    result = onramp.send_message(
                        endpoint.format(self[0].global_id, lang_literal),
                        "GET")
                    if "BeneficiaryResponseList" in result.get("content", {}):
                        content = result["content"]["BeneficiaryResponseList"][
                            0]
                        if json_name in content:
                            content_values = content[json_name]
                            if not isinstance(content_values, list):
                                content_values = [content_values]
                            translation = content_values[i]
                            if translation == value_record.value:
                                must_manually_translate = True
                            value_record.with_context(
                                lang=lang_context).value = translation
                if must_manually_translate:
                    value_record.assign_translation()