def get_ebay_basic_result(self, instance): api = instance.with_context({ 'do_not_use_site_id': True }).get_trading_api_object() api.execute('GeteBayDetails', {}) results = api.response.dict() return results
def fetch_revoked_token_from_ebay(self): "This Method is created for Fetching Token from eBay by calling <FetchToken> Api By passing SessionID only " "This Method requires user to complete sign-in in eBay site first " "This Method will execute when user click on <Continue> button on wizard " "Method will store token to database" ebay_instance_obj = self.env['ebay.instance.ept'] instance_ids = self._context.get('active_ids') for instance in ebay_instance_obj.browse(instance_ids): try: if instance.environment == 'is_sandbox': api = instance.with_context({ 'do_not_use_site_id': True }).get_trading_api_object() else: api = instance.get_trading_api_object() sessionID_dict = {'SessionID': self.session_id} api.execute('FetchToken', sessionID_dict) fetchtoken_results = api.response.dict() token = fetchtoken_results['eBayAuthToken'] results = instance.env['ebay.instance.ept'].search([ ('id', '=', instance.id) ]) results.write({ 'auth_token': token, 'fetch_token_boolean': False }) except Exception as e: raise Warning(e) return True
def sync_policies(self,instance): api=instance.get_trading_api_object() para ={'ShowSellerProfilePreferences':True,'ShowSellerReturnPreferences':True,'ShowOutOfStockControlPreference':True} api.execute('GetUserPreferences',para) result = api.response.dict() SellerProfilePreferences = result.get('SellerProfilePreferences',{}) SupportedSellerProfiles = SellerProfilePreferences.get('SupportedSellerProfiles',{}) policies = [] if SupportedSellerProfiles : policies = SupportedSellerProfiles.get('SupportedSellerProfile',[]) if not isinstance(policies, list): policies = [policies] OutOfStockControlPreference = result.get('OutOfStockControlPreference') if OutOfStockControlPreference == 'false': instance.write({'allow_out_of_stock_product':False}) else : instance.write({'allow_out_of_stock_product':True}) policy_ids = list(map(lambda p: p['ProfileID'], policies)) existing_policies=self.search([('policy_id', 'not in', policy_ids),('instance_id','=',instance.id)]) existing_policies.unlink() for policy in policies: record = self.search([('policy_id', '=', policy['ProfileID'])]) if not record: record = self.create({ 'policy_id': policy['ProfileID'], }) record.write({ 'name': policy['ProfileName'], 'policy_type': policy['ProfileType'], 'short_summary': policy['ShortSummary'] if 'ShortSummary' in policy else ' ', 'instance_id':instance.id }) return True
def get_sessionid_from_ebay(self): "This Method is created for geting SessionID by calling <GetSessionID> API By passing RuName" "This Method will execute when click on link in wizard" "And Redirecting User to eBay Site for verification in new Tab " getsession_dict = {'RuName': self.instance_id.redirect_url_name} try: if self.instance_id.environment == 'is_sandbox': api = self.instance_id.with_context({ 'do_not_use_site_id': True }).get_trading_api_object() else: api = self.instance_id.get_trading_api_object() api.execute('GetSessionID', getsession_dict) getsession_results = api.response.dict() sessionID_temp = getsession_results['SessionID'] self.session_id = sessionID_temp if self.instance_id.environment == 'is_sandbox': base_URL = 'https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn&RUName=' + self.instance_id.redirect_url_name + '&SessID=' else: base_URL = 'https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RUName=' + self.instance_id.redirect_url_name + '&SessID=' base_URL += sessionID_temp except Exception as e: raise Warning(e) return { 'type': 'ir.actions.act_url', 'url': base_URL, 'nodestroy': True, 'target': 'new' }
def cancel_listing_in_ebay(self): for record in self: instance = record.instance_id if not instance.check_instance_confirmed_or_not(): return False item_id = record.name cancel_listing = record.cancel_listing difft_time = datetime.utcnow() - datetime.now() if cancel_listing == True: ending_reason = record.ending_reason results = {} try: api = instance.get_trading_api_object() api.execute('EndItem', { 'ItemID': item_id, 'EndingReason': ending_reason }) results = api.response.dict() FMT = '%Y-%m-%d %H:%M:%S' endtime = results.get('EndTime', False) end_tm = self.env['ebay.instance.ept'].openerp_format_date( endtime) endtime = datetime.strptime(end_tm, FMT) - difft_time ebay_end_tm2 = str(endtime)[:19] ebay_end_tm = ebay_end_tm2 record.write({'is_cancel': True, 'end_time': ebay_end_tm}) except Exception as e: raise Warning(str(e)) return True
def send_feedback_reply_ept(self, response_text, response_type): for record in self: instance = record.instance_id iteam_id = self.sale_order_line_id.item_id ebay_order_line_item_id = self.sale_order_line_id.ebay_order_line_item_id transection_id = ebay_order_line_item_id.split("-")[1] results = {} para = { 'ItemID': iteam_id, 'TransactionID': transection_id, 'ResponseText': response_text, 'ResponseType': response_type, 'TargetUserID': self.feedback_user_id } try: api = instance.get_trading_api_object() api.execute('RespondToFeedback', para) results = api.response.dict() ack = results.get('Ack') if ack == 'Success': record.message_post( body=('<b>The FeedBack Message sent</b><br/>%s.') % (response_text)) except Exception as e: raise Warning(str(e))
def get_sessionid_for_revoked_fetch_token(self): ebay_instance_obj = self.env['ebay.instance.ept'] instance_ids = self._context.get('active_ids') for instance in ebay_instance_obj.browse(instance_ids): getsession_dict = {'RuName': instance.redirect_url_name} try: if instance.environment == 'is_sandbox': api = instance.with_context({ 'do_not_use_site_id': True }).get_trading_api_object() else: api = instance.get_trading_api_object() api.execute('GetSessionID', getsession_dict) getsession_results = api.response.dict() sessionID_temp = getsession_results['SessionID'] self.session_id = sessionID_temp if instance.environment == 'is_sandbox': base_URL = 'https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn&RUName=' + instance.redirect_url_name + '&SessID=' else: base_URL = 'https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RUName=' + instance.redirect_url_name + '&SessID=' base_URL += sessionID_temp return { 'type': 'ir.actions.act_url', 'url': base_URL, 'nodestroy': True, 'target': 'new' } except Exception as e: raise Warning(e)
def update_listing(self): increment = 0 for product_listing_record in self: product = product_listing_record.prod_list product_name = product.name ebay_item_id = product_listing_record.name instance = product_listing_record.instance_id related_template = product_listing_record.related_template listing_type = product_listing_record.type if related_template and product_listing_record.state != 'Ended': listing_duration = product_listing_record.listing_duration or 'GTC' try: product_dict = self.env[ 'product.listing.templates'].prepare_product_dict( product, related_template, instance, listing_type, listing_duration) if not product_dict.get('Item', False): continue api = instance.get_trading_api_object() product_dict['Item'].update({'ItemID': ebay_item_id}) product_dict = product_dict.copy() api.execute('ReviseItem', product_dict) results = api.response.dict() except Exception as e: raise Warning(e) api.response.text #api.request.body # results = connection_obj.call(cr, uid,instance_id, 'ReviseItem', ids,product.id,ebay_item_id,title,description_final,subtitle_final,shop.post_code,increment,shop.site_id.site_id) #results ={} ack = results.get('Ack', False) if ack == 'Failure': if results.get('LongMessage', False): long_message = results['LongMessage'] for each_messsge in long_message: severity_code = each_messsge[0]['SeverityCode'] if severity_code == 'Error': Longmessage = each_messsge[0]['LongMessage'] product_long_message = ( 'Error : This %s product cannot be Updated because:' ) % (product_name) + ' ' + Longmessage increment += 1 product_listing_record.log( increment, product_long_message) elif ack == 'Warning': if results.get('LongMessage', False): long_message = results['LongMessage'] for each_messsge in long_message: severity_code = each_messsge[0]['SeverityCode'] if severity_code == 'Warning': Longmessage = each_messsge[0]['LongMessage'] product_long_message = ('Warning : %s:') % ( product_name) + ' ' + Longmessage increment += 1 product_listing_record.log( increment, product_long_message) return True
def check_connection(self): api = self.get_trading_api_object() para = {} try: api.execute('GetUser', para) except Exception as e: raise Warning(e) raise Warning('Service working properly') return True
def get_ebay_official_time(self): try: api = self.get_trading_api_object() api.execute('GeteBayOfficialTime', {}) results = api.response.dict() return results.get('Timestamp', False) and results['Timestamp'][:19] + '.000Z' except Exception: raise Warning("Call GeteBayOfficialTime API time error.")
def create_update_delete_promotion_on_ebay(self): context = dict(self._context) instance = self.instance_id api = instance.get_trading_api_object() action = context.get('action', False) ebay_action = '' PromotionalSaleDetails = {} promotion_id = self.promotion_sale_id if action == 'delete': PromotionalSaleDetails.update({'PromotionalSaleID': promotion_id}) print 'delete' ebay_action = 'Delete' return True elif action == 'add': ebay_action = 'Add' elif action == 'update': PromotionalSaleDetails.update({'PromotionalSaleID': promotion_id}) ebay_action = 'Update' if action in ['update', 'delete'] and not promotion_id: raise Warning( "First you need to create Promotion, You cannot update / delete promotion without creating Promotion on eBay" ) if action != 'delete': PromotionalSaleDetails.update({ 'PromotionalSaleName': self.promotion_name, 'DiscountType': self.discount_type, 'DiscountValue': self.discount_value, 'PromotionalSaleStartTime': self.promotion_start_date, 'PromotionalSaleEndTime': self.promotion_end_date, 'PromotionalSaleType': self.promotion_type }) para = { 'Action': ebay_action, 'PromotionalSaleDetails': PromotionalSaleDetails, 'WarningLevel': 'High' } try: api.execute('SetPromotionalSale', para) results = api.response.dict() if action != 'delete': promo_sale_id = results.get('PromotionalSaleID', False) status = results.get('Status', False) self.write({ 'status': status, 'promotion_sale_id': promo_sale_id, 'created_in_ebay': True }) except Exception as e: raise Warning(str(e)) return True
def confirm(self): if self.state != 'confirmed': api = self.get_trading_api_object() para = {} try: api.execute('GetUser', para) except Exception as e: raise Warning(e) self.write({'state': 'confirmed'}) return True
def call_payment_update_api(self, instance, invoice_lines, para): try: lang = instance.lang_id and instance.lang_id.code if lang: para.update({'ErrorLanguage': lang}) api = instance.get_trading_api_object() api.execute('ReviseCheckoutStatus', para) api.response.dict() invoice_lines.write({'payment_updated_in_ebay': True}) self._cr.commit() except Exception: raise Warning(api.response.dict())
def write(self, vals): check = vals.get('allow_out_of_stock_product') if ('allow_out_of_stock_product' in vals) and self.auth_token and len(self.auth_token) > 1: api = self.get_trading_api_object() if check == True: dict_temp = {'OutOfStockControlPreference': 'true'} else: dict_temp = {'OutOfStockControlPreference': 'false'} api.execute('SetUserPreferences', dict_temp) results = api.response.dict() res = super(ebay_instace_ept, self).write(vals) return res
def ebay_sdk(self): try: api = Trading( config_file=False, appid='ReviveOn-ZestERP-PRD-05d7504c4-7e62e952', token= 'AgAAAA**AQAAAA**aAAAAA**514uWg**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AFloCgAJaEogidj6x9nY+seQ**4M8DAA**AAMAAA**pJTxWPk5v7uA4HdkanTFWcUAzgQdjHsD7hreui/eFJdqrxw3PsgdsK+WGP5fY8urMJ9rmIozaeVq5Wh7rU9FchyAwcTYu42LFXXM+7Q/TGo+KhsDuWL2WGz4t4JtuFw4iVJpWWLnkdGNkMed6S+xYjvfSU0XOYKIRnSIcs4JfzK1uwgCuSaUS1ajmH5ZCpVciLjtm9pQvguT4j3odY5CoGh5wsRYMJnjvYvQqCI114Nx65XBmShPKRLVZOfvO6OWYL6bkBhd8grmR3JFYMGj5LZz3Z3lF/Xy7Qdfz9Lpjt49k7TThwXzZw0jjsKCUUJBdfEvFBg/qZcVPreCDgm3h8X3p55e78mBnqV+OQFmIh38Kk1ZKAaYiicOHxRvVxTcZib+6bBB/5Jb1gBYTLDdqYZ6BC0B6TYc49BsOE8yMAe3/VTm0V5SZw0R3WAiyy3Csj7pFy8KN6oxXwLJsC8v2RqqnueejMPp08Vn6kRohh5uoLFSiTdxMoam5Bim/3KLXH7qNeM4y720Rw/FIantaeezF5kVug9Ic/9gq84nXj1rqRfeZfRrr2BofIBF9rjiLmZ5YHHhNKXCMsLctNgCyOosPeMc08jhZIS53ELYqZ/RB8fVCIHXAZyXFy5Vg5D/2YP9T+4NELQjJgYIx2EYh079iNJMxE9jBYOsKQP5qshRuJqOCZvubTFCiJN9e0MPLaaUz5569T2Xxi9QTlSBLuaMNmEGHeFCwGKt31cWgx9oEQroxRKBE7unHGNUY9Ws', certid='PRD-5d7504c480f9-39be-4693-bc3c-5485', devid='12b0abb8-96e5-4f07-b012-97081166a3a8', warnings=True) # pass in an open file # the Requests module will close the file files = { 'file': ('EbayImage', open('/home/girish/Pictures/t-shirt.png', 'rb')) } pictureData = { "WarningLevel": "High", "PictureName": "WorldLeaders" } response = api.execute('UploadSiteHostedPictures', pictureData, files=files) print(response.dict()) json.dumps(api) except ConnectionError as e: print(e) print(e.response.dict())
def get_item_listning(self, instance, item, item_id): results = {} item = {} try: api = instance.get_trading_api_object() product_dict = { 'ItemID': item_id, 'DetailLevel': 'ItemReturnDescription' } api.execute('GetItem', product_dict) results = api.response.dict() if results.get('Ack') == 'Success': item = results.get('Item') except Exception as e: raise Warning(('%s') % (str(e))) return item if item else {}
def create_ebay_feedback_ept(self, instance, product_listing): try: api = instance.get_trading_api_object() api.execute('GetFeedback', { 'DetailLevel': 'ReturnAll', 'ItemID': product_listing.name }) results = api.response.dict() feedback_results = results.get('FeedbackDetailArray', {}).get('FeedbackDetail', {}) if isinstance(feedback_results, dict): feedback_results = [feedback_results] if any(feedback_results): self.create_or_update_feedback_ept(feedback_results, instance, product_listing) except Exception as e: raise Warning(str(e)) return True
def cancel_in_ebay(self): """ Cancel Order In eBay using AddDispute API. """ active_id = self._context.get('picking_id') picking = self.env['stock.picking'].browse(active_id) instance = picking.ebay_instance_id if not instance.check_instance_confirmed_or_not(): return False dispute_explanation_code = '' for move in picking.move_lines: sale_line_id = move.sale_line_id or False if not sale_line_id or move.canceled_in_ebay: continue if not sale_line_id.ebay_order_line_item_id or not sale_line_id.item_id: continue dispute_reason = self.dispute_reason_code if dispute_reason == 'BuyerHasNotPaid': dispute_explanation_code = self.dispute_explanation_code_for_bhnp else: dispute_explanation_code = self.dispute_explanation_code_for_tmc dispute_data = { 'DisputeExplanation': dispute_explanation_code, 'DisputeReason': dispute_reason, 'OrderLineItemID': sale_line_id.ebay_order_line_item_id, 'ItemID': sale_line_id.item_id, 'TransactionID': sale_line_id.order_id.ebay_order_id } try: lang = instance.lang_id and instance.lang_id.code lang and dispute_data.update({'ErrorLanguage': lang}) api = instance.get_trading_api_object() api.execute('AddDispute', dispute_data) api.response.dict() move.write({'canceled_in_ebay': True}) self._cr.commit() except Exception as e: raise Warning(e) return True
def create(self, vals): payment_option_obj = self.env['ebay.payment.options'] site_details_obj = self.env['ebay.site.details'] instance = super(ebay_instace_ept, self).create(vals) self.create_sequences_and_dashboard_operation(instance) if not instance.fetch_token_boolean: results = {} api = instance.get_trading_api_object() para = {} api.execute('GeteBayDetails', para) results = api.response.dict() # instance.unlink() # self._cr.commit() # raise Warning(('%s')%(str(e))) if results: payment_option_obj.get_payment_options( instance, results.get('PaymentOptionDetails', [])) site_details_obj.get_site_details( instance, results.get('SiteDetails', False)) return instance
def fetch_ebay_token(self): self.ensure_one() """This method is used to catch the auth token experation date and we will able to revoke it from Odoo once it is expired""" try: if self.environment == 'is_sandbox': api = self.with_context({ 'do_not_use_site_id': True }).get_trading_api_object() else: api = self.get_trading_api_object() api.execute('GetTokenStatus', {}) results = api.response.dict() if results: tokenDate = results.get('TokenStatus', {}).get('ExpirationTime') tokenDate = tokenDate[0:19] tokenDate = time.strptime(tokenDate, "%Y-%m-%dT%H:%M:%S") tokenDate = time.strftime("%Y-%m-%d %H:%M:%S", tokenDate) self.token_expirationtime = tokenDate except Exception as e: raise Warning(e) return True
def uploadPictureFromFilesystem(opts, filepath): try: api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid, certid=opts.certid, devid=opts.devid, warnings=True) # pass in an open file # the Requests module will close the file files = {'file': ('EbayImage', open(filepath, 'rb'))} pictureData = {"WarningLevel": "High", "PictureName": "WorldLeaders"} api.execute('UploadSiteHostedPictures', pictureData, files=files) dump(api) except ConnectionError as e: print(e) print(e.response.dict())
def revoke_token_from_ebay(self): ebay_instance_obj = self.env['ebay.instance.ept'] instance_ids = self._context.get('active_ids') for instance in ebay_instance_obj.browse(instance_ids): if not instance.auth_token: raise Warning("Instance %s doesn's have Token." % instance.name) revoke_token_dict = { 'RequesterCredentials': { 'eBayAuthToken': instance.auth_token } } try: if instance.environment == 'is_sandbox': api = instance.with_context({ 'do_not_use_site_id': True }).get_trading_api_object() else: api = instance.get_trading_api_object() api.execute('RevokeToken', revoke_token_dict) instance.write({'auth_token': False}) except Exception as e: raise Warning(e) return True
def create_picture_url(self): instance = self.ept_product_id.instance_id api = instance.get_trading_api_object() pictureData = { "WarningLevel": "High", "ErrorLanguage": 'en_US', "PictureName": self.name } if self.is_binary_image: image = BytesIO( base64.standard_b64decode(self.storage_image_binary)) files = {'file': ('EbayImage', image)} response = api.execute('UploadSiteHostedPictures', pictureData, files=files) else: image = BytesIO(base64.standard_b64decode(self.url_image_binary)) files = {'file': ('EbayImage', image)} response = api.execute('UploadSiteHostedPictures', pictureData, files=files) return response and response.dict() and response.dict().get( 'SiteHostedPictureDetails', {}).get('FullURL', '')
def ups_ept_retrive_shipping_services(self, to_add): """ Retrive shipping services from the UPS @param: @return: list of dictionaries with shipping service @author: Jigar Vagadiya on dated 9-May-2017 """ # Prepared the Service list services_name = {'01': 'Next Day Air', '02': '2nd Day Air', '03': 'Ground', '12': '3 Day Select', '13': 'Next Day Air Saver', '14': 'UPS Next Day Air Early', '59': '2nd Day Air A.M.', '07': 'Worldwide Express', '08': 'Worldwide Expedited', '11': 'Standard', '54': 'Worldwide Express Plus', '65': 'Saver', '96': 'UPS Worldwide Express Freight'} shipping_services_obj = self.env['shipping.services.ept'] services = shipping_services_obj.search([('shipping_instance_id', '=', self.id)]) services.sudo().unlink() for company in self.company_ids: api = self.get_ups_api_object(True, "Rate", self.ups_userid, self.ups_password, self.access_license_number) service_root = etree.Element("RatingServiceSelectionRequest") request = etree.SubElement(service_root, "Request") etree.SubElement(request, "RequestAction").text = "Rate" etree.SubElement(request, "RequestOption").text = "Shop" shipment = etree.SubElement(service_root, "Shipment") etree.SubElement(shipment, "Description").text = "Rate Description" shipper = etree.SubElement(shipment, "Shipper") shipper_address = etree.SubElement(shipper, "Address") etree.SubElement(shipper_address, "PostalCode").text = company.zip etree.SubElement(shipper_address, "CountryCode").text = "%s" % (company.country_id and company.country_id.code or "") ship_to = etree.SubElement(shipment, "ShipTo") ship_to_address = etree.SubElement(ship_to, "Address") if to_add.use_toaddress_different: etree.SubElement(ship_to_address, "PostalCode").text = "%s" % (to_add.to_zip) etree.SubElement(ship_to_address, "CountryCode").text = "%s" % (to_add.to_country_id.code) else: etree.SubElement(ship_to_address, "PostalCode").text = company.zip etree.SubElement(ship_to_address, "CountryCode").text = "%s" % (company.country_id and company.country_id.code or "") package_info = etree.SubElement(shipment, "Package") package_type = etree.SubElement(package_info, "PackagingType") etree.SubElement(package_type, "Code").text = "02" package_weight = etree.SubElement(package_info, "PackageWeight") package_uom = etree.SubElement(package_weight, "UnitOfMeasurement") etree.SubElement(package_uom, "Code").text = "LBS" etree.SubElement(package_weight, "Weight").text = "50" try: api.execute('RatingServiceSelectionRequest', etree.tostring(service_root).decode('utf-8')) results = api.response.dict() except Exception as e: raise ValidationError(e) if results is not None: product_details = results.get('RatingServiceSelectionResponse', {}).get('RatedShipment', {}) # Take change : Check rate services response data with dict also. if isinstance(product_details,dict): product_details = [product_details] for pro_detail in product_details: service_code_ept = pro_detail.get('Service', {}).get('Code') service_name_ept = services_name.get(service_code_ept) if service_code_ept: service_id = shipping_services_obj.search( [('service_code', '=', service_code_ept), ('shipping_instance_id', '=', self.id)]) if service_id: if company.id not in service_id.company_ids.ids: service_id.write({'company_ids': [(4, company.id)]}) else: shipping_services_obj.create( {'shipping_instance_id': self.id, 'service_code': service_code_ept, 'service_name': service_name_ept, 'company_ids': [(4, company.id)]}) else: raise ValidationError("There is no shipping service available!") return True
def get_ebay_result(self, instance): api = instance.get_trading_api_object() para = {} api.execute('GeteBayDetails', para) results = api.response.dict() return results
def import_store_category(self, instances, level_limit=0, only_leaf_categories=True): for instance in instances: cat = {} site_id = instance.site_id and instance.site_id.site_id or False api = instance.get_trading_api_object() para = {'DetailLevel': 'ReturnAll'} if level_limit > 0: para.update({'LevelLimit': level_limit}) if site_id: para.update({'CategorySiteID': site_id}) if only_leaf_categories: para.update({'ViewAllNodes': 'false'}) else: para.update({'ViewAllNodes': 'true'}) try: api.execute('GetStore', para) cat = api.response.dict() except Exception as e: raise Warning(('%s') % (str(e))) categories = [] custom_category = cat.get('Store', {}).get('CustomCategories', {}) if custom_category and custom_category.get('CustomCategory', []): if isinstance(custom_category.get('CustomCategory', []), list): categories = custom_category.get('CustomCategory', []) else: categories = [custom_category.get('CustomCategory', [])] for categ in categories: name = categ.get('Name') categoryid = categ.get('CategoryID') categ_record = self.search( [('ebay_category_id', '=', categoryid), ('instance_id', '=', instance.id)], limit=1) if categ_record: categ_record.write({'name': name}) else: categ_record = self.create({ 'name': name, 'ebay_category_id': categoryid, 'site_id': instance.site_id and instance.site_id.id or False, 'instance_id': instance.id, 'is_store_category': True }) child_categs = categ.get('ChildCategory', []) if not isinstance(child_categs, list): child_categs = [child_categs] for child in child_categs: name = child.get('Name') categoryid = child.get('CategoryID') child_record = self.search( [('ebay_category_id', '=', categoryid), ('site_id', '=', instance.site_id.id), ('is_store_category', '=', True), ('instance_id', '=', instance.id)], limit=1) if child_record: child_record.write({'name': name}) else: child_record = self.create({ 'name': name, 'ebay_category_id': categoryid, 'site_id': instance.site_id and instance.site_id.id or False, 'instance_id': instance.id, 'is_store_category': True, 'ebay_category_parent_id': categ_record.ebay_category_id, 'parent_id': categ_record.id }) #Added By Dimpal 25/12/2017 sub_child_categs = child.get('ChildCategory', []) if not isinstance(sub_child_categs, list): sub_child_categs = [sub_child_categs] for sub_child in sub_child_categs: name = sub_child.get('Name') categoryid = sub_child.get('CategoryID') sub_child_record = self.search( [('ebay_category_id', '=', categoryid), ('site_id', '=', instance.site_id.id), ('is_store_category', '=', True), ('instance_id', '=', instance.id)], limit=1) if sub_child_record: sub_child_record.write({'name': name}) else: self.create({ 'name': name, 'ebay_category_id': categoryid, 'site_id': instance.site_id and instance.site_id.id or False, 'instance_id': instance.id, 'is_store_category': True, 'ebay_category_parent_id': child_record.ebay_category_id, 'parent_id': child_record.id }) self._cr.commit() return True
def get_item_conditions(self, import_category_id=None): condition_obj = self.env['ebay.condition.ept'] instance_obj = self.env['ebay.instance.ept'] category = None if not self and import_category_id: category = self.search( [('ebay_category_id', '=', import_category_id)], limit=1) else: category = self category_code = category.ebay_category_id instances = instance_obj.search([('site_id', '=', category.site_id.id), ('state', '=', 'confirmed')]) if not instances: return True instance = instances[0] if category_code: api = instance.get_trading_api_object() para = { 'ViewAllNodes': True, 'DetailLevel': 'ReturnAll', 'AllFeaturesForCategory': True, 'CategoryID': category.ebay_category_id } api.execute('GetCategoryFeatures', para) results1 = api.response.dict() if results1: category_default = results1.get('SiteDefaults', {}) category_val = results1.get('Category', {}) item_sp_en = category_val.get( 'ItemSpecificsEnabled', False) or category_default.get( 'ItemSpecificsEnabled', False) condition_enabled = category_val.get( 'ConditionEnabled', False) or category_default.get( 'ConditionEnabled', False) galary_plus_enabled = category_val.get( 'FreeGalleryPlusEnabled', False) or category_default.get( 'FreeGalleryPlusEnabled', False) offer_accept_enabled = category_val.get( 'BestOfferAutoAcceptEnabled', False) or category_default.get( 'BestOfferAutoAcceptEnabled', False) set_return_policy = category_val.get( "ReturnPolicyEnabled", False) or category_default.get( 'ReturnPolicyEnabled', False) digital_good_delivery_enabled = category_val.get( 'DigitalGoodDeliveryEnabled', False) or category_default.get( 'DigitalGoodDeliveryEnabled', False) paypal_required = category_val.get( "PayPalRequired", False) or category_default.get( 'PayPalRequired', False) variation_enabled = category_val.get( "VariationsEnabled", False) or category_default.get( 'VariationsEnabled', False) handling_time_enabled = category_val.get( "HandlingTimeEnabled", False) or category_default.get( 'HandlingTimeEnabled', False) offer_accept_enabled = False if offer_accept_enabled == 'false' else True galary_plus_enabled = False if galary_plus_enabled == 'false' else True set_return_policy = False if set_return_policy == 'false' else True item_sp_en = True if item_sp_en == 'Enabled' else False digital_good_delivery_enabled = False if digital_good_delivery_enabled == 'false' else True condition_enabled = True if condition_enabled == 'Required' else False paypal_required = False if paypal_required == 'false' else True variation_enabled = True if variation_enabled == 'true' else False handling_time_enabled = True if handling_time_enabled == 'true' else False category.write({ 'item_specifics': item_sp_en, 'condition_enabled': condition_enabled, 'offer_accept_enabled': offer_accept_enabled, 'galary_plus_enabled': galary_plus_enabled, 'set_return_policy': set_return_policy, 'variation_enabled': variation_enabled, 'handling_time_enabled': handling_time_enabled, 'digital_good_delivery_enabled': digital_good_delivery_enabled, 'paypal_required': paypal_required }) condition_values = category_val.get('ConditionValues', False) if condition_values: if isinstance(condition_values.get('Condition', []), dict): condition_values = [ condition_values.get('Condition', []) ] else: condition_values = condition_values.get( 'Condition', []) for each_val in condition_values: condition_name = each_val.get('DisplayName', False) condition_id = each_val.get('ID', False) if condition_name and condition_id: search_conditions = condition_obj.search([ ('condition_id', '=', condition_id), ('category_id', '=', category.id), ('name', '=', condition_name) ]) if not search_conditions: condition_vals = { 'name': condition_name, 'condition_id': condition_id, 'category_id': category.id } condition_obj.create(condition_vals) if not category.leaf_category and category.ebay_condition_ids: child_categ = self.env[ 'ebay.category.master.ept'].search([ ('parent_id', '=', category.id) ]) while True: for child in child_categ: for condition in category.ebay_condition_ids: search_conditions = condition_obj.search([ ('condition_id', '=', condition.condition_id), ('category_id', '=', child.id), ('name', '=', condition.name) ]) if not search_conditions: condition_vals = { 'name': condition.name, 'condition_id': condition.condition_id, 'category_id': child.id } child_categ = self.env[ 'ebay.category.master.ept'].search([ ('parent_id', 'in', child_categ.ids) ]) if not child_categ: break return True
def get_attributes(self, max_name_levels, max_value_per_name): attribute_master_obj = self.env['ebay.attribute.master'] attribute_value_obj = self.env['ebay.attribute.value'] instance_obj = self.env['ebay.instance.ept'] results = False category = self category_code = category.ebay_category_id instances = instance_obj.search([('site_id', '=', category.site_id.id), ('state', '=', 'confirmed')]) if not instances: return True instance = instances[0] if category_code: api = instance.get_trading_api_object() para = {'CategoryID': category.ebay_category_id} if max_name_levels: para.update({'MaxNames': max_name_levels}) if max_value_per_name: para.update({'MaxValuesPerName': max_value_per_name}) results = api.execute('GetCategorySpecifics', para) list_of_result = [] if isinstance( results.dict().get('Recommendations', {}).get('NameRecommendation', []), list): list_of_result = results.dict().get('Recommendations', {}).get( 'NameRecommendation', []) else: list_of_result.append(results.dict().get( 'Recommendations', {}).get('NameRecommendation', [])) for line in list_of_result: attribute_name = line.get('Name') attribute_record = attribute_master_obj.search([ ('name', '=', attribute_name), ('categ_id', '=', category.id) ]) if not attribute_record: attribute_record = attribute_master_obj.create({ 'name': attribute_name, 'categ_id': category.id }) list_of_value = [] if isinstance(line.get('ValueRecommendation', []), list): list_of_value = line.get('ValueRecommendation', []) else: list_of_value.append(line.get('ValueRecommendation', {})) for value in list_of_value: attribute_value = attribute_value_obj.search([ ('name', '=', value.get('Value')), ('attribute_id', '=', attribute_record.id) ]) if not attribute_value: attribute_value_obj.create({ 'name': value.get('Value'), 'attribute_id': attribute_record.id }) """for line in list_of_result: child_categs=self.search([('parent_id','=',category.id)]) while child_categs: for child in child_categs: child_record=attribute_master_obj.search([('name','=',attribute_name),('categ_id','=',child.id)]) if not child_record: child_record=attribute_master_obj.create({'name':attribute_name,'categ_id':child.id}) for value in line.get('ValueRecommendation',[]): child_value=attribute_value_obj.search([('name','=',value.get('Value')),('att_master_id','=',child_record.id)]) if not child_value: attribute_value_obj.create({'name':value.get('Value'),'att_master_id':child_record.id}) child_categs=self.search([('parent_id','in',child_categs.ids)])""" return True
def import_category(self, instances, level_limit=0, only_leaf_categories=True, is_import_get_item_condition=False): for instance in instances: cat = {} site_id = instance.site_id and instance.site_id.site_id or False api = instance.get_trading_api_object() para = {'DetailLevel': 'ReturnAll'} if level_limit > 0: para.update({'LevelLimit': level_limit}) if site_id: para.update({'CategorySiteID': site_id}) if only_leaf_categories: para.update({'ViewAllNodes': 'false'}) else: para.update({'ViewAllNodes': 'true'}) try: api.execute('GetCategories', para) cat = api.response.dict() except Exception as e: raise Warning(('%s') % (str(e))) categories = [] if cat.get('CategoryArray', {}) and cat['CategoryArray'].get( 'Category', []): categories = cat['CategoryArray'][ 'Category'] #returns list of dictionary if isinstance(categories, dict): categories = [categories] for categ in categories: name = categ.get('CategoryName') CategoryID = categ.get('CategoryID') AutoPayEnabled = categ.get('AutoPayEnabled') CategoryLevel = categ.get('CategoryLevel') CategoryParentID = categ.get('CategoryParentID') LSD = categ.get('LSD') LeafCategory = categ.get('LeafCategory', "false") BestOfferEnabled = categ.get('BestOfferEnabled', "false") if LeafCategory == 'true': LeafCategory = True else: LeafCategory = False if LSD == 'true': LSD = True else: LSD = False if BestOfferEnabled == 'true': BestOfferEnabled = True else: BestOfferEnabled = False if CategoryID == CategoryParentID: CategoryParentID = False categs = self.search([('ebay_category_id', '=', CategoryID), ('site_id', '=', instance.site_id.id)], limit=1) parent = self.search( [('ebay_category_id', '=', CategoryParentID), ('site_id', '=', instance.site_id.id)], limit=1) if not categs: self.create({ 'name': name, 'ebay_category_id': CategoryID, 'site_id': instance.site_id and instance.site_id.id or False, 'leaf_category': LeafCategory, 'ebay_category_parent_id': CategoryParentID, 'category_level': CategoryLevel, 'auto_pay_enabled': AutoPayEnabled, 'best_offer_enabled': BestOfferEnabled, 'parent_id': parent and parent.ids[0] or False }) else: categs.write({ 'name': name, 'ebay_category_id': CategoryID, 'site_id': instance.site_id and instance.site_id.id or False, 'leaf_category': LeafCategory, 'ebay_category_parent_id': CategoryParentID, 'category_level': CategoryLevel, 'auto_pay_enabled': AutoPayEnabled, 'best_offer_enabled': BestOfferEnabled, 'parent_id': parent and parent.ids[0] or False }) if is_import_get_item_condition: """ :Function get_item_conditions: This function call to category wise import get item condition. """ self.get_item_conditions(import_category_id=CategoryID) return True
def sync_product_listings(self, instance, from_date, to_date, is_create_auto_odoo_product=False): product_product_obj = self.env['product.product'] product_listing_obj = self.env['ebay.product.listing.ept'] ebay_product_template_obj = self.env['ebay.product.template.ept'] ebay_log_book_obj = self.env['ebay.log.book'] ebay_product_product_obj = self.env['ebay.product.product.ept'] ebay_log_line_obj = self.env['ebay.transaction.line'] ebay_site_details_obj = self.env['ebay.site.details'] job = False from_date = "%sT00:00:00.000Z" % (from_date) to_date = "%sT00:00:00.000Z" % (to_date) page_number = 1 resultfinal = [] while True: products = {} try: results = {} api = instance.get_trading_api_object() para = { 'DetailLevel': 'ItemReturnDescription', 'StartTimeFrom': from_date, 'StartTimeTo': to_date, 'IncludeVariations': True, 'Pagination': { 'EntriesPerPage': 200, 'PageNumber': page_number }, 'IncludeWatchCount': True } api.execute('GetSellerList', para) results = api.response.dict() if results and results.get('Ack', False) == 'Success': products = results.get('ItemArray', {}) and results['ItemArray'].get( 'Item', []) or [] except Exception as e: raise Warning(('%s') % (str(e))) has_more_trans = results.get('HasMoreItems', 'false') if isinstance(products, dict): products = [products] for result in products: resultfinal = resultfinal + [result] if has_more_trans == 'false': break page_number = page_number + 1 for item in resultfinal: product_list = product_listing_obj.search( [('name', '=', item.get('ItemID'))], limit=1) # If Listing Found Process if product_list: if item.get('Variations', {}): product_list.ebay_product_tmpl_id.write( {'product_type': 'variation'}) elif item.get('SKU', False): try: ebay_product = product_list.ebay_product_tmpl_id.ebay_variant_ids[ 0] self.create_individual_ebay_product_images( item, ebay_product) except Exception: pass ebay_site_ids = ebay_site_details_obj.search( [('name', '=', item.get('Site'))], limit=1) values = { 'start_time': item.get('ListingDetails')['StartTime'], 'end_time': item.get('ListingDetails')['EndTime'], 'ebay_total_sold_qty': item.get('SellingStatus')['QuantitySold'], 'state': item.get('SellingStatus')['ListingStatus'], 'ebay_stock': item.get('Quantity'), 'ebay_url': item.get('ListingDetails')['ViewItemURL'], 'listing_duration': item.get('ListingDuration'), 'listing_type': item.get('ListingType'), 'ebay_site_id': ebay_site_ids and ebay_site_ids.id or False } product_list.write(values) self.update_active_listing(instance, item, product_list) continue # Variation Listing Process variations = item.get('Variations', {}).get('Variation') if variations: if not isinstance(variations, list): variations = [variations] self.sync_variation_product_listings( instance, item, job, variations, is_create_auto_odoo_product) continue # Individual Listing Process if item.get('SKU', False): ebay_product = ebay_product_product_obj.search([ ('ebay_sku', '=', item.get('SKU')), ('instance_id', '=', instance.id) ]) if ebay_product: try: self.create_individual_ebay_product_images( item, ebay_product) except Exception: pass value = self.get_vals_for_product_listing( instance, item, ebay_product) product_listing_id = product_listing_obj.create(value) self.update_active_listing(instance, item, product_listing_id) else: if not product_product_obj.search([ ('default_code', '=', item.get('SKU')) ]) and is_create_auto_odoo_product: vals = { 'name': item.get('Title'), 'default_code': item.get('SKU'), 'type': 'product', 'purchase_ok': True, 'sale_ok': True, } product_product_obj.create(vals) odoo_product = product_product_obj.search([ ('default_code', '=', item.get('SKU')) ]) if odoo_product: ebay_tmp_record = ebay_product_template_obj.search([ ('product_tmpl_id', '=', odoo_product.product_tmpl_id.id), ('instance_id', '=', instance.id) ]) if not ebay_tmp_record: value = { 'name': item.get('Title'), 'instance_id': instance.id, 'exported_in_ebay': True, 'description': item.get('Description'), 'product_tmpl_id': odoo_product.product_tmpl_id.id, 'product_type': 'individual' if len(odoo_product.product_tmpl_id. product_variant_ids.ids) == 1 else 'variation' } ebay_tmp_record = ebay_product_template_obj.create( value) for variant in odoo_product.product_tmpl_id.product_variant_ids: if ebay_product_product_obj.search([ ('product_id', '=', variant.id), ('instance_id', '=', instance.id) ]): continue if variant.default_code == item.get('SKU'): value = { 'product_id': variant.id, 'ebay_sku': variant.default_code, 'ebay_product_tmpl_id': ebay_tmp_record.id, 'instance_id': instance.id, 'name': variant.product_tmpl_id.name, 'exported_in_ebay': True } ebay_product_record = ebay_product_product_obj.create( value) value = self.get_vals_for_product_listing( instance, item, ebay_product_record) product_listing_obj.create(value) else: if not job: value = { 'instance_id': instance.id, 'message': 'eBay Sync Products', 'application': 'sync_products', 'operation_type': 'import', 'skip_process': True } job = ebay_log_book_obj.create(value) job_line_val = { 'ebay_order_ref': item.get('ItemID'), 'job_id': job.id, 'log_type': 'not_found', 'action_type': 'skip_line', 'operation_type': 'import', 'message': 'Product Not found for SKU %s' % (item.get('SKU')), } ebay_log_line_obj.create(job_line_val) else: if not job: value = { 'instance_id': instance.id, 'message': 'eBay Sync Products', 'application': 'sync_products', 'operation_type': 'import', 'skip_process': True } job = ebay_log_book_obj.create(value) job_line_val = { 'ebay_order_ref': item.get('ItemID'), 'job_id': job.id, 'log_type': 'not_found', 'action_type': 'skip_line', 'operation_type': 'import', 'message': 'Product Have no SKU', } ebay_log_line_obj.create(job_line_val) return True