def read(self, id, storeview_id=None, attributes=None): """ Returns the information of a record :rtype: dict """ content = req(self.backend_record, self._path + "/%s" % (id)) # to get list of groups filters = {'attribute_set_id': int(id)} filters = create_search_criteria(filters) qs = Php.http_build_query(filters) url = "%s/groups/list?%s" % (self._path, qs) groups_list = [] groups = req(self.backend_record, url) groups = groups and groups.get('items', False) attributes = [] url = "/V1/attribute" data = {'attribute_set_id': id} set_attribute_list = {} try: attributes = req(self.backend_record, url, method="POST", data=data) except HTTPError as e: response = e.response status_code = response.get('status_code', '') if status_code and status_code == 404: raise FailedJobError(""" Attribute Set Import Job Failed : it seems Magento plugin not installed on Magento side. Resolution : You have to install magento plugin named "Emipro_Apichange" Please Install Magento plugin 'Emipro_Apichange' on Magento. """) else: raise FailedJobError( "Attribute Set Import Job Failed : \n\n\t%s" % response) for group in groups: for attribute in attributes: if 'attribute_group_name' in group and group[ 'attribute_group_name'] in attribute: attribute_list = attribute[group['attribute_group_name']] group_attributes = {} for attri in attribute_list: group_attributes.update({ list(attribute_list[attri].values())[0]: list(attribute_list[attri].keys())[0] }) group.update({'attribute_list': group_attributes}) set_attribute_list.update(group_attributes) break groups_list.append(group) content.setdefault('group_list', groups_list) content.update({'attribute_list': set_attribute_list}) return content
def delete(self, id, sku): """ Delete a record on the external system """ if not sku: raise FailedJobError("SKU not found for product image.") if not id: raise FailedJobError("External ID not found for product image.") url = str(self._path).format(sku=sku) data = {'url': url} res = super(ProductImageAdapter, self).delete(id, data) if res and isinstance(res, bool): return res else: raise FailedJobError( "Product image not deleted in external system : %s" % res)
def write(self, attribute_id, data): binder = self.binder_for() attribute = binder.to_openerp(attribute_id, browse=True) attribute_code = attribute and attribute.attribute_code or False if not attribute_code: raise FailedJobError("attribute code not found") data.update({'attribute_id': attribute_id}) data = {'attribute': data} content = super(ProductAttributeAdapter, self).write(attribute_code, data) result = content.get('attribute_id', False) if not result: raise FailedJobError("Attribute not updated : %s " % content) return result
def read(self, id, sku, storeview_id=None): sku = urllib.parse.quote(sku) if not sku: raise FailedJobError("SKU not found for product image.") url = str(self._path + "/{id}").format(sku=sku, id=id) res = req(self.backend_record, url, method="GET") return res
def perform(self, session): """ Execute the job. The job is executed with the user which has initiated it. :param session: session to execute the job :type session: ConnectorSession """ assert not self.canceled, "Canceled job" with session.change_user(self.user_id): self.retry += 1 try: with session.change_context({'job_uuid': self._uuid}): self.result = self.func(session, *self.args, **self.kwargs) except RetryableJobError as err: if err.ignore_retry: self.retry -= 1 raise elif not self.max_retries: # infinite retries raise elif self.retry >= self.max_retries: type_, value, traceback = sys.exc_info() # change the exception type but keep the original # traceback and message: # http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/ new_exc = FailedJobError( "Max. retries (%d) reached: %s" % (self.max_retries, value or type_)) raise (new_exc.__class__, new_exc, traceback) raise return self.result
def run(self, binding_id): """ Run the job to export the validated/paid invoice """ invoice = self.model.browse(binding_id) magento_order = invoice.sale_id.magento_bind_ids and invoice.sale_id.magento_bind_ids[0] magento_store = magento_order.store_id mail_notification = magento_store.send_invoice_paid_mail lines_info = self._get_lines_info(invoice) magento_id = None try: magento_id = self._export_invoice(magento_order.magento_id, lines_info, mail_notification) except FailedJobError as err: # When the invoice is already created on Magento, it returns: magento_id = self._get_existing_invoice(magento_order) if magento_id is None: raise FailedJobError('Invoice Export job failed') if not magento_id: # If Magento returned no ID, try to find the Magento # invoice, but if we don't find it, let consider the job # as done, because Magento did not raised an error magento_id = self._get_existing_invoice(magento_order) invoice.write({'is_exported_to_magento' : True , 'magento_id' : magento_id}) return "Invoice is successfully exported on Magento with ID %s"%(magento_id)
def create(self, data): """ Create a record on the external system """ data = {"attribute": data} content = super(ProductAttributeAdapter, self).create(data) result = content.get('attribute_id') if not result: raise FailedJobError("Result from Magento : %s" % content) return result
def create(self, data, storeview_id=None): sku = data.pop('product') sku = urllib.parse.quote(sku) if not sku: raise FailedJobError("SKU not found for product image.") path = self._path.format(sku=sku) data = {'entry': data} try: res = req(self.backend_record, path, method="POST", data=data) except HTTPError as err: response = err.response if response.get('status_code') == 400: raise NothingToDoJob('Product Image is not exported : ' + response.get('message')) if isinstance(res, str): """If media gallery entry created and return ID if id not found then raise exception""" return res else: raise FailedJobError("%s" % res)
def create(self, data): skeleton_id = data.pop('skeletonSetId') data = {'attributeSet': data, 'skeletonId': skeleton_id} content = req(self.backend_record, self._path, method="POST", data=data) result = content.get('attribute_set_id') if not result: raise FailedJobError("Result from Magento : %s" % content) return result
def _get_magento_data(self): """ Return the raw Magento data for ``self.magento_id`` """ result = self.backend_adapter.read(self.magento_id) if result and result.get('attribute_id'): self.magento_id = result.get('attribute_id') return result else: #23/03/2017 #if attribute is import custom set to "No" in Magento then #in response false will be there so we will skip the attribute import if not result: return result raise FailedJobError("Attribute id not found : %s" % result)
def skeletonSetId(self, record): tmpl_set_id = self.backend_record.attribute_set_tpl_id.id if tmpl_set_id: binder = self.binder_for('magento.attribute.set') magento_tpl_set_id = binder.to_backend(tmpl_set_id) else: raise FailedJobError( ("\n\n'Default Attribute Set' field must be define on " "the Magento Global.\n\n" "Resolution: \n" "- Go to Magento > Settings > Globals > '%s'\n" "- Set the field Attribte set Tempalte\n") % self.backend_record.name) return {'skeletonSetId': magento_tpl_set_id}
def write(self, id, data): """ Update records on the external system """ sku = data.pop('product') sku = urllib.parse.quote(sku) if not sku: raise FailedJobError("SKU not found for product image.") url = str(self._path).format(sku=sku) data.update({'id': id}) data = {'entry': data} data.update({'url': url}) try: res = super(ProductImageAdapter, self).write(id, data) except HTTPError as err: response = err.response if response.get('status_code') == 400: raise NothingToDoJob('Product Image is not exported : ' + response.get('message')) return res
def req(backend, path, method='GET', data=None, params=None): location_url = backend._check_location_url(backend.location) api_url = '%s%s' % (location_url, path) headers = { 'Accept': '*/*', 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % backend.token } try: #resp, content = client.request(api_url,method=method, body=json.dumps(data),headers=headers) _logger.info('Data pass to Magento : %s' % data) if method == 'GET': resp = requests.get(api_url, headers=headers, verify=False, params=params) elif method == 'POST': resp = requests.post(api_url, headers=headers, data=json.dumps(data), verify=False, params=params) elif method == 'DELETE': resp = requests.delete(api_url, headers=headers, verify=False, params=params) elif method == 'PUT': resp = requests.put(api_url, headers=headers, data=json.dumps(data), verify=False, params=params) else: resp = requests.get(api_url, headers=headers, verify=False, params=params) content = resp.json() _logger.info('Response status code from Magento : %s', resp.status_code) _logger.info('Content : %s' % content) _logger.info('API URL : %s' % api_url) _logger.info('Response Status code : %s' % resp.status_code) if resp.status_code == 401: raise FailedJobError( 'Given Credentials is incorrect, please provide correct Credentials.' ) if not resp.ok: if resp.headers.get('content-type').split(';')[0] == 'text/html': raise FailedJobError( "Content-type is not JSON \n %s : %s \n %s \n %s" % (resp.status_code, resp.reason, path, resp.content)) else: response = resp.json() response.update({'status_code': resp.status_code}) raise HTTPError(str(response), response=response) except HTTPError as err: response = err.response raise FailedJobError( "Request is not Satisfied : \n Status Code : %s \n Content : %s" % (response.get('status_code'), response.get('message'))) except (socket.gaierror, socket.error, socket.timeout) as err: raise NetworkRetryableError( 'A network error caused the failure of the job: ' '%s' % err) return content