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
Esempio n. 2
0
 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
Esempio n. 3
0
 def lang(self, record):
     path = "/V1/storeview"
     try:
         lang_data = req(self.backend_record, path)
     except:
         raise UserError("""
                     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.
                     """)
     for data in lang_data:
         if int(data['store_id']) == record.get('id'):
             lang_code = data.get('language')
             language = self.env['res.lang'].search([('code', '=',
                                                      lang_code)])
             if not language:
                 language = self.env['res.lang'].search([
                     ('code', '=', lang_code), '|', ('active', '=', False),
                     ('active', '=', True)
                 ])
                 language_install = self.env[
                     'base.language.install'].create(
                         {'lang': language.code})
                 language_install.lang_install()
             break
             return {'lang_id': language.id}
Esempio n. 4
0
    def read(self, id, attributes=None):
        """ Returns the information of a record

        :rtype: dict
        """
        content = req(self.backend_record, self._path + "/%s" % (id))
        return content
 def delete(self, vals):
     """ Delete a record on the external system """
     option_id = vals.get('option_mag_id', '')
     attribute_id = vals.get('attribute_mag_id', '')
     path = str(self._path + "/{option_id}").format(
         attributeCode=attribute_id, option_id=option_id)
     result = req(self.backend_record, path, method="DELETE")
     return result
Esempio n. 6
0
    def read(self, id, attributes=None):
        """ Returns the information of a record

        :rtype: dict
        """
        result = {}
        content = req(self.backend_record, self._path)

        for record in content:
            if record['id'] == int(id):
                path = '/V1/store/storeConfigs'
                configs = req(self.backend_record, path)
                for config in configs:
                    if config['id'] == int(id):
                        record['base_media_url'] = config['base_media_url']
                return record

        return result
Esempio n. 7
0
    def search(self, filters=None, params=None):
        """ Search records according to some criterias
        and returns a list of ids

        :rtype: list
        """

        queystring = False
        if filters:
            url = filters.get('url',
                              False) and filters.pop('url') or self._path
            #Date : 14-sep-2017
            #If pagesize and currenpage is parameter are given in filters then search
            #Customers with pagesize and currentPage
            page_size = filters.get('pageSize') and filters.pop(
                'pageSize', None) or 0
            currentPage = filters.get('currentPage') and filters.pop(
                'currentPage', None) or 0
            #First Prepare searchCriteria dictionary and then add pagesize and currentpage in that.
            filters = create_search_criteria(filters)
            if page_size and currentPage and filters.get('searchCriteria'):
                filters['searchCriteria'].update({
                    'currentPage': currentPage,
                    'pageSize': page_size
                })

            #prepare query string from filters
            queystring = Php.http_build_query(filters)
            url = queystring and "%s?%s" % (url, queystring) or url
        else:
            url = self._path
        result = []
        content = req(self.backend_record, url, params=params)
        if isinstance(content,
                      list) and len(content) > 0 and ('id'
                                                      in content[0].keys()):
            for record in content:
                result.append(record['id'])
            return result
        if 'items' in content:
            if len(content['items']) == 0:
                return result
            if 'id' in content['items'][0]:
                for record in content.get('items'):
                    result.append(record['id'])
                return result
        """
        if content.get('items') and len(content.get('items')) == 0:
                return result
        if content.get('items',False) :
            if content['items'][0].has_key('id') :
                for record in content.get('items'):
                    result.append(record['id'])
                return result
        """
        return content
    def create(self, data):
        attribute_id = data.pop('attribute')
        if not attribute_id:
            job = self.env['queue.job'].search([('model_name', '=',
                                                 'magento.attribute.option'),
                                                ('state', '=', 'started')])
            job.requeue()
            #raise FailedJobError(("Attribute not found for attribute option : %s")% data.get('label'))
        data = {'option': data}

        path = self._path.format(attributeCode=attribute_id)
        result = req(self.backend_record, path, method="POST", data=data)
        if result == True:
            path = self._path.format(attributeCode=attribute_id)
            options = req(self.backend_record, path, method="GET")
            for option in options:
                if option.get('label') == data['option'].get('label'):
                    return option.get('value')
        return
Esempio n. 9
0
 def addAttribute(self, attribute_id, set_id, group_id,sequence=1):
     data = {
             'attribute_set_id':set_id,
             'attribute_group_id':group_id,
             'attribute_code':attribute_id,
             'sort_order':sequence 
             }
     url = self._path+"attributes"
     content = req(self.backend_record,url,method="POST",data=data)
     return
Esempio n. 10
0
 def write(self, id, data):
     set_id = data.get('attribute_set_id')
     data.update({
                  'attribute_group_id':id,
                  })
     url = self._path+"%s/groups"%(set_id)
     data={
           'group':data
           }
     content = req(self.backend_record,url,method="PUT",data=data)
     return 
Esempio n. 11
0
    def read(self, id, attributes=None):
        """ Returns the information of a record

        :rtype: dict
        """
        result = {}
        content = req(self.backend_record, self._path)
        for record in content:
            if record['id'] == int(id):
                return record
        return result
    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
Esempio n. 13
0
 def read_attributes(self,set_id,group_name):
     data = {
             'attribute_set_id':set_id
             }
     url = "/V1/attribute"
     groups = req(self.backend_record,url,method="POST",data=data)
     attribute_list = {}
     for group in groups :
         attributes = group.get(group_name)
         if attributes:
             for attribute in attributes :
                 attribute_list.update({attributes[attribute].values()[0]:(attribute,attributes[attribute].keys()[0])}) 
             return attribute_list
     return attribute_list
Esempio n. 14
0
    def read(self, id, storeview_id=None, attributes=None):
        """ Returns the information of a record

        :rtype: dict
        """
        if storeview_id :
            url = self._path+"/%s?store_id=%s"%(id,storeview_id)
        else :
            url = self._path+"/%s"%(id)
        content = req(self.backend_record,url)
        if content.get('custom_attributes') :
            for attribute in content.get('custom_attributes'):
                content.update({attribute['attribute_code']:attribute['value']})
        return content
Esempio n. 15
0
    def search_read(self, filters=None):
        """ Search records according to some criterias
        and returns their information"""

        queystring = False
        if filters:
            url = filters.get('url',
                              False) and filters.pop('url') or self._path
            filters = create_search_criteria(filters)
            queystring = Php.http_build_query(filters)
            url = queystring and "%s?%s" % (url, queystring) or url
        else:
            url = self._path
        content = req(self.backend_record, url)
        result = content.get('items', False) or content
        return result
Esempio n. 16
0
 def create(self, order_id, items, comment, picking ,email, include_comment):
     """ Create a record on the external system """
     order_item = []
     if items :
         for item_id,qty in items.items() :
             item={}
             item.setdefault("orderItemId",item_id)
             item.setdefault("qty",qty)
             order_item.append(item)
     else :
         order_item.append(items)
     
     track_numbers = self.add_tracking_number(picking)
     values = {"entity":{"orderId":order_id,
                         "items":order_item,
                         "tracks" : track_numbers or []
                         }}
    
     values['url']="%s/"%self._path
     result = super(StockPickingAdapter,self).create(values)
     magento_id = result.get('entity_id')
     
     if not magento_id : 
         filters = {'order_id':order_id}
         filters = create_search_criteria(filters)
                 
         qs = Php.http_build_query(filters)
         url = "%ss?%s"%(self._path,qs)
     
         result = []
         content = req(self.backend_record,url)
         shipments = content.get('items',False)
         if shipments : 
             if len(shipments) == 1 :
                 magento_id = shipments[0]['entity_id']   
             else :
                 shipment_dates = {}
                 for shipment in shipments :
                     shipment_dates.setdefault(shipment['entity_id'],shipment['created_at'])
                 latest_date = max(shipment_dates.values())
                 for shipment in shipment_dates:
                     if latest_date == shipment_dates[shipment] :
                         magento_id = shipment
                         break
                 
     return magento_id    
Esempio n. 17
0
 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)
Esempio n. 18
0
 def import_payment_method(self):
     payment_method_obj = self.env['magento.payment.method']
     url = '/V1/paymentmethod'
     payment_methods = req(self, url)
     #print(payment_methods)
     for payment_method in payment_methods:
         payment_method_code = payment_method.get('value')
         new_payment_method = payment_method_obj.search([
             ('payment_method_code', '=', payment_method_code),
             ('backend_id', '=', self.id)
         ])
         if not new_payment_method:
             payment_method_obj.create({
                 'payment_method_code':
                 payment_method.get('value'),
                 'payment_method_name':
                 payment_method.get('title'),
                 'backend_id':
                 self.id
             })
Esempio n. 19
0
 def import_delivery_method(self):
     delivery_method_obj = self.env['magento.delivery.carrier']
     url = '/V1/shippingmethod'
     delivery_methods = req(self, url)
     #print(delivery_methods)
     for delivery_method in delivery_methods:
         for method_value in delivery_method.get('value'):
             delivery_method_code = method_value.get('value')
             new_delivery_carrier = delivery_method_obj.search([
                 ('carrier_code', '=', delivery_method_code),
                 ('backend_id', '=', self.id)
             ])
             if not new_delivery_carrier:
                 delivery_method_obj.create({
                     'carrier_code':
                     method_value.get('value'),
                     'carrier_label':
                     method_value.get('label'),
                     'backend_id':
                     self.id,
                     'magento_carrier_title':
                     delivery_method.get('label')
                 })
    def search(self, filters=None):
        """ Search records according and returns a list of ids
        :rtype: list
        """
        #filters = create_search_criteria(filters)
        filters = {
            'searchCriteria': {
                'filterGroups': [{
                    'filters': [{
                        'field': 'entity_type_id',
                        'value': -1,
                        'condition_type': 'gt'
                    }]
                }]
            }
        }
        qs = Php.http_build_query(filters)
        url = "%s/sets/list?%s" % (self._path, qs)

        result = []
        content = req(self.backend_record, url)
        for record in content.get('items'):
            result.append(record['attribute_set_id'])
        return result
Esempio n. 21
0
    def create(self, data):
        """ Create a record on the external system """

        url = data.get('url', False) and data.pop('url') or self._path
        content = req(self.backend_record, url, method="POST", data=data)
        return content
Esempio n. 22
0
 def write(self, id, data):
     """ Update records on the external system """
     url = data.get('url', False) and data.pop('url') or self._path
     url = "%s/%s" % (url, id)
     content = req(self.backend_record, url, method="PUT", data=data)
     return content
Esempio n. 23
0
 def delete(self, id, data=None):
     """ Delete a record on the external system """
     url = data and data.get('url', False) or self._path
     url = "%s/%s" % (url, id)
     content = req(self.backend_record, url, method='DELETE')
     return content