Beispiel #1
0
    def send_letter_image(self, image_data, image_type, base64encoded=True):
        """ Sends an image of a Letter to Onramp U.S. Image Upload Service.
        See http://developer.compassion.com/docs/read/compassion_connect2/
            service_catalog/Image_Submission

        Returns the uploaded image URL.
        """
        content_type = ""
        if image_type == "pdf":
            content_type = "application"
        else:
            content_type = "image"
        headers = {f"Content-type": f"{content_type}/{image_type}"}
        params = {"doctype": "s2bletter"}
        url = self._connect_url + "images/documents"
        OnrampConnector.log_message("POST",
                                    url,
                                    headers,
                                    message="{image binary data not shown}")
        if base64encoded:
            data = base64.b64decode(image_data)
        else:
            data = image_data
        r = self._session.post(url, params=params, headers=headers, data=data)
        status = r.status_code
        if status == 201:
            letter_url = r.text
        else:
            raise UserError(_("[%s] %s") % (str(r.status_code), r.text))
        return letter_url
Beispiel #2
0
    def send_letter_image(self, image_data, image_type, base64encoded=True):
        """ Sends an image of a Letter to Onramp U.S. Image Upload Service.
        See http://developer.compassion.com/docs/read/compassion_connect2/
            service_catalog/Image_Submission

        Returns the uploaded image URL.
        """
        headers = {'Content-type': 'image/{0}'.format(image_type)}
        params = {'doctype': 's2bletter'}
        url = self._connect_url + 'images/documents'
        OnrampConnector.log_message('POST',
                                    url,
                                    headers,
                                    message='{image binary data not shown}')
        if base64encoded:
            data = base64.b64decode(image_data)
        else:
            data = image_data
        r = self._session.post(url, params=params, headers=headers, data=data)
        status = r.status_code
        if status == 201:
            letter_url = r.text
        else:
            raise UserError(_('[%s] %s') % (r.status_code, r.text))
        return letter_url
 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
Beispiel #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
Beispiel #5
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
Beispiel #7
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
Beispiel #9
0
 def get_letter_image(self, letter_url, img_type='jpeg', pages=0, dpi=96):
     """ Calls Letter Image Service from Onramp U.S. and get the data
     http://developer.compassion.com/docs/read/compassion_connect2/
     service_catalog/Image_Retrieval
     """
     params = {'format': img_type, 'pg': pages, 'dpi': dpi}
     OnrampConnector.log_message('GET', letter_url)
     r = self._session.get(letter_url, params=params)
     letter_data = None
     if r.status_code == 200:
         letter_data = base64.b64encode(r.content)
     return letter_data
 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()
Beispiel #11
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)
Beispiel #14
0
    def test_message(self, test_message):
        """ Sends a message to any onramp.
        :param test_message (onramp.simulator record): the message to send
        """
        headers = {
            "Content-type": "application/json",
            "x-cim-MessageType": test_message.message_type_url,
            "x-cim-FromAddress": "CHTest",
            "x-cim-ToAddress": "CH",
        }
        url = test_message.server_url
        body = test_message.body_json

        OnrampConnector.log_message("POST", url, headers, body)
        r = self._session.post(url,
                               headers=headers,
                               json=simplejson.loads(body))
        status = r.status_code
        OnrampConnector.log_message(status, "RESULT", message=r.text)
        test_message.write({"result": r.text, "result_code": r.status_code})
    def test_message(self, test_message):
        """ Sends a message to any onramp.
        :param test_message (onramp.simulator record): the message to send
        """
        headers = {
            'Content-type': 'application/json',
            'x-cim-MessageType': test_message.message_type_url,
            'x-cim-FromAddress': 'CHTest',
            'x-cim-ToAddress': 'CH'
        }
        url = test_message.server_url
        body = test_message.body_json

        OnrampConnector.log_message('POST', url, headers, body)
        r = self._session.post(url, headers=headers,
                               json=simplejson.loads(body))
        status = r.status_code
        OnrampConnector.log_message(status, 'RESULT', message=r.text)
        test_message.write({
            'result': r.text,
            'result_code': r.status_code
        })
    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()
Beispiel #17
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()