def import_categories(self, cr, uid):

        # magneto object through which connecting openerp with defined magneto configuration start
        start_timestamp = str(DateTime.utc())
        magento_configuration_object = self.pool.get("magento.configuration").get_magento_configuration_object(cr, uid)
        if magento_configuration_object == None:
            raise osv.except_osv(_("Import/Export is in progress!"), _("Import/Export Products is All ready Running "))

        [status, server, session] = self.pool.get("magento.configuration").magento_openerp_syn(cr, uid)
        if not status:
            raise osv.except_osv(
                _("There is no connection!"),
                _(
                    "There is no connection established with magento server\n\
                    please check the url,username and password"
                ),
            )
            return -1
        # end
        try:
            # fetching all category information from magneto using the following API.
            info_category = server.call(session, "category.tree", [])
            # Creating all records in openerp using _create_category function.
            total_no_of_records = self.pool.get("magento.configuration")._create_category(
                cr, uid, info_category, magento_configuration_object
            )
            if magento_configuration_object[0].id:
                self.pool.get("magento.configuration").write(
                    cr, uid, [magento_configuration_object[0].id], {"last_imported_category_timestamp": start_timestamp}
                )
        except Exception, e:
            #                server.endSession(session)
            return -1
示例#2
0
 def faqUse( self, faq, user ):
     """Increments the use count for this faq by 1"""
     cur = self.__conn.cursor()
     cur.execute( """INSERT INTO 
                         PrivilegeUse (Privilege, User, TimeOfUse, Data)
                         VALUES (%s, %s, %s, %s)""", 
                 UseCountStore.FaqUse, user, DateTime.utc(), faq )
     self.__conn.commit()
示例#3
0
 def newQuote( self, contents, author, addingUser ):
     """Add a new quote"""
     cur = self.__conn.cursor()
     cur.execute( """INSERT INTO Quotes 
                  (Contents, Author, Created, AddingUser)
                  VALUES (%s, %s, %s, %s)""", 
                 contents, author, DateTime.utc(), addingUser ) 
     self.__conn.commit()
     return cur.lastrowid
示例#4
0
 def newFaq( self, name, author, contents ):
     """Create a new faq"""
     
     # first check if we have a deleted faq by that name
     cur = self.__conn.cursor()
     cur.execute( """SELECT *
                     FROM LatestVersion, FaqVersions 
                     WHERE LatestVersion.Id = FaqVersions.Id 
                         AND FaqVersions.State = %d
                         AND FaqVersions.Name=%s""", STATE_DELETED, name )
     row = cur.fetchone()
     if row:
         # yes, just modify the existing one
         self.modifyFaq( name, { "author" : author, 
                                 "contents" : contents, 
                                 "state" : STATE_NORMAL } )
         # and add the alias
         cur.execute( "INSERT INTO FaqAliases (Alias, CanonicalName) VALUES(%s, %s)", 
                     name, name )
         self.__conn.commit()
         return
     
     # is there a non-deleted faq by that name?
     cur.execute ( """   SELECT * 
                         FROM LatestVersion, FaqVersions
                         WHERE LatestVersion.Id = FaqVersions.Id
                             AND FaqVersions.State <> %d
                             AND FaqVersions.Name=%s""", STATE_DELETED, name )
     if row:
         raise FaqStoreError( "Faq %s already exists" % name )
     
     # verify that there is no alias by that name either
     cur.execute( "SELECT CanonicalName from FaqAliases WHERE Alias=%s", name )
     row = cur.fetchone()
     if row:
         aliasName = row[0]
         raise FaqStoreError( "%s is already an alias for %s" % ( name, aliasName ) )
     
     # create the faq entry itself
     try:
         cur.execute ( "INSERT INTO FaqVersions (Name, Version, State, Contents, Author, Created) VALUES " +
                     "(%s, %d, %d, %s, %s, %s )", 
                     name, 1, STATE_NORMAL, contents, author, DateTime.utc() )
         id = cur.lastrowid
         
         # and the primary alias
         cur.execute( "INSERT INTO FaqAliases (Alias, CanonicalName) VALUES(%s, %s)", 
                     name, name )
         
         # and the latest version
         cur.execute( "INSERT INTO LatestVersion (Name, Id) VALUES(%s, %d)", name, id )
         self.__conn.commit()
     except:
         self.__conn.rollback()
         raise
示例#5
0
    def modifyFaq( self, name, modifyDict ):
        """modifies an existing faq"""
        cur = self.__conn.cursor()
        
        canonicalName = self.getCanonicalName( name, checkCanonical = True, checkDeleted = True )
        
        # generate the insertion string and varargs dynamically
        fields = [ "%s", "%s" ] 
        args = [ canonicalName, DateTime.utc(), canonicalName ]        
        
        for field in ( "contents", "author", "state" ):
            if field in modifyDict.keys():
                args.append( modifyDict[field] )
                fields.append( "%s" )
            else:
                fields.append( field )
            
        args.append( canonicalName )
        
        #print "Args: %s" % (", ".join( [str(s) for s in args ]))
        #print "Fields: %s" % ", ".join( fields )    """    
        
        stmt = """INSERT INTO FaqVersions 
                     (Version, Created, Name, Contents, Author, State )                                          
                     SELECT
                        (SELECT MAX(Version) FROM FaqVersions WHERE FaqVersions.Name=%%s) + 1, 
                        %s 
                     FROM FaqVersions, LatestVersion 
                        WHERE LatestVersion.Name=%%s AND LatestVersion.Id = FaqVersions.Id""" % \
                        ( ", ".join( fields ) )

        args = tuple(args)
        #print stmt 
        #print args        
        
        #print
        #print
        
        try:        
            cur.execute( stmt, *args );
            id = cur.lastrowid
            cur.execute( """UPDATE LatestVersion
                            SET Id = %d
                            WHERE LatestVersion.Name=%s""",
                        (id, canonicalName) )  
        
            self.__conn.commit()
        except:
            self.__conn.rollback()
            raise
示例#6
0
    def import_categories(self, cr, uid):
            
                # magneto object through which connecting openerp with defined magneto configuration start
            start_timestamp = str(DateTime.utc())
            magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
            if magento_configuration_object==None:
                raise osv.except_osv(_('Import/Export is in progress!'),_("Import/Export Products is All ready Running ") )
                
            [status, server, session] = self.pool.get('magento.configuration').magento_openerp_syn(cr, uid)
            if not status:
                    raise osv.except_osv(_('There is no connection!'),_("There is no connection established with magento server\n\
                    please check the url,username and password") )
                    return -1 
                #end
            try:     
                #fetching all category information from magneto using the following API.
                info_category = server.call(session, 'category.tree',[])
                #Creating all records in openerp using _create_category function.
                total_no_of_records=self.pool.get('magento.configuration')._create_category(cr, uid, info_category, magento_configuration_object)
                if magento_configuration_object[0].id:
                  self.pool.get('magento.configuration').write(cr, uid, [magento_configuration_object[0].id], {'last_imported_category_timestamp':start_timestamp})

            except Exception,e:
                return -1 
示例#7
0
 def import_credit_memos(self,cr,uid): #Customized Import creditmemo Function
     total_no_of_records=0# Number of credit memos imported  
     start_timestamp = str(DateTime.utc())
     if True:
         # magneto object through which connecting openerp with defined magento configuration start
         start_timestamp = str(DateTime.utc())
         magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
         last_import = magento_configuration_object[0].last_imported_credit_timestamp
         [status, server, session] = self.pool.get('magento.configuration').magento_openerp_syn(cr, uid)
         #checking server status
         if not status:
             raise osv.except_osv(_('There is no connection!'),_("There is no connection established with magento server\n\
               please check the url,username and password") )
             server.endSession(session)
             return -1
         #end
         # API to fetch all sale order information ##
         listcreditmemo = server.call(session, 'order_creditmemo.list')#,[{'updated_at': {'from':last_import}}])
         all_increment_id=[]
         all_customer_id=[]
         for credit in listcreditmemo:
             all_increment_id.append(credit['increment_id'])
         listorder = server.call(session, 'order_creditmemo.list',[all_increment_id]) 
         for creditmemo in  listorder:
                 product = {}
                 return_to_stock = {}
                 product['magento_creditmemo_id']=int(creditmemo['creditmemo_id'])
                 if self.pool.get('stock.picking').search(cr,uid,[('magento_creditmemo_id','=',product['magento_creditmemo_id'])]):
                     continue
                 if self.pool.get('account.invoice').search(cr,uid,[('magento_creditmemo_id','=',product['magento_creditmemo_id'])]):
                     continue
                 magento_increment = creditmemo['order_id']
                 sale_order = self.pool.get('sale.order').search(cr,uid,[('magento_id','=',magento_increment)])
                 sale_obj = self.pool.get('sale.order').browse(cr,uid,sale_order)[0]
                 customer_id = sale_obj.partner_id.id
                 if creditmemo['items']:
                             for item in creditmemo['items']:
                                  product[item['product_id']]=float(item['qty'])
                                  return_to_stock[item['product_id']]=item['back_to_stock']
                             picking_ids = self.pool.get('stock.picking').search(cr,uid,[('type','=','out'),('sale_id','=',sale_order[0])])
                             for pick_id in picking_ids:
                                     context1={'active_id':pick_id,'active_ids':[pick_id]}
                                     mod_obj = self.pool.get('ir.model.data')
                                     act_obj = self.pool.get('ir.actions.act_window')
                                     result = mod_obj.get_object_reference(cr, uid, 'stock', 'act_stock_return_picking')
                                     id = result and result[1] or False
                                     result = act_obj.read(cr, uid, [id], context={})[0]
                                     context1['magento']=creditmemo['increment_id']+' for order '+ sale_obj.name
                                     context1['increment_id']=creditmemo['increment_id']
                                     try:
                                          return_picking_id = self.pool.get('stock.return.picking').create(cr,uid,result,context1)
                                     except Exception,e:
                                          continue
                                     result = self.pool.get('stock.return.picking').create_returns_from_magento(cr,uid,[return_picking_id],product,return_to_stock,creditmemo,context1)
                                     start = result['domain'][1:-1].index('[')
                                     stop = result['domain'][1:-1].index(']')
                                     inv_id = result['domain'][1:-1][start+1:stop]
                                     if float(creditmemo['base_adjustment_positive']):
                                                 product_id = self.pool.get('product.product').search(cr,uid,[('name','=','Refund Amount')])
                                                 if not product_id:
                                                       raise osv.except_osv(_('There is no refund product!'),_("There is no product with name 'Refund Amount', please create.") )
                                                 product_obj = self.pool.get('product.product').browse(cr,uid,product_id)[0]
                                                 a_m_l = {}
                                                 a_m_l['origin']=sale_obj.name
                                                 a_m_l['product_id']=product_id[0]
                                                 a_m_l['name']=product_obj.name
                                                 a_m_l['invoice_id']=inv_id
                                                 a_m_l['price_unit']=creditmemo['base_adjustment_positive']
                                                 a_m_l['partner_id']=customer_id
                                                 self.pool.get('account.invoice.line').create(cr,uid,a_m_l)
                                     
                                     if float(creditmemo['base_shipping_amount']):
                                                 product_id = magento_configuration_object[0].shipping_product.id
                                                 product_obj = magento_configuration_object[0].shipping_product.name
                                                 a_m_l = {}
                                                 a_m_l['origin']=sale_obj.name
                                                 a_m_l['product_id']=product_id
                                                 a_m_l['name']=product_obj
                                                 a_m_l['invoice_id']=inv_id
                                                 a_m_l['price_unit']=creditmemo['base_shipping_incl_tax']
                                                 a_m_l['partner_id']=customer_id
                                                 
                                                 if creditmemo['base_shipping_tax_amount'] and creditmemo['base_shipping_amount']:
                                                       try:
                                                          tax_percent = float(creditmemo['base_shipping_tax_amount'])/float(creditmemo['base_shipping_amount'])*100
                                                          tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, tax_percent)
                                                          a_m_l['invoice_line_tax_id']=[[6,0,[tax_id]]]
                                                       except:
                                                              pass
                                                 self.pool.get('account.invoice.line').create(cr,uid,a_m_l)     
                                            
                                     if result:
                                         total_no_of_records+=1
                 else:
                     refund={}
                     refund['date']=datetime.datetime.now()
                     journal_ids = self.pool.get('account.journal').search(cr,uid,[('type','=','sale_refund')])
                     refund['journal_id'] = journal_ids and journal_ids[0]
                     refund['filter_refund']='refund'
                     refund['description']="Magento Refund"
                     refund_id = self.pool.get('account.invoice.refund').create(cr,uid,refund)
                     context={}
                     if not sale_obj.invoice_ids:
                         continue
                     context['active_ids']=[sale_obj.invoice_ids[-1].id]
                     context['notax']=True
                     result = self.pool.get('account.invoice.refund').invoice_refund(cr,uid,[refund_id],context)
                     refund_inv_id=result['refunded_invoice_id'][0]
                     account_move_line_ids = self.pool.get('account.invoice.line').search(cr,uid,[('invoice_id','=',refund_inv_id)])
                     if account_move_line_ids:
                           self.pool.get('account.invoice.line').unlink(cr,uid,account_move_line_ids)
                           inv_tax_lines = self.pool.get('account.invoice.tax').search(cr,uid,[('invoice_id','=',refund_inv_id)])
                           self.pool.get('account.invoice.tax').unlink(cr,uid,inv_tax_lines)
                     product_id = self.pool.get('product.product').search(cr,uid,[('name','=','Refund Amount')])
                     if not product_id:
                           raise osv.except_osv(_('There is no refund product!'),_("There is no product with name 'Refund Amount', please create.") )
                     product_obj = self.pool.get('product.product').browse(cr,uid,product_id)[0]
                     a_m_l = {}
                     a_m_l['origin']=sale_obj.name
                     a_m_l['product_id']=product_id[0]
                     a_m_l['name']=product_obj.name
                     a_m_l['invoice_id']=refund_inv_id
                     a_m_l['price_unit']=creditmemo['base_adjustment_positive']
                     a_m_l['partner_id']=customer_id
                     self.pool.get('account.invoice.line').create(cr,uid,a_m_l)
                     if float(creditmemo['base_shipping_amount']):
                             product_id = magento_configuration_object[0].shipping_product.id
                             product_obj = magento_configuration_object[0].shipping_product.name
                             a_m_l = {}
                             a_m_l['origin']=sale_obj.name
                             a_m_l['product_id']=product_id
                             a_m_l['name']=product_obj
                             a_m_l['invoice_id']=refund_inv_id
                             a_m_l['price_unit']=creditmemo['base_shipping_incl_tax']
                             a_m_l['partner_id']=customer_id
                             
                             if creditmemo['base_shipping_tax_amount'] and creditmemo['base_shipping_amount']:
                                   try:
                                      tax_percent = float(creditmemo['base_shipping_tax_amount'])/float(creditmemo['base_shipping_amount'])*100
                                      tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, tax_percent)
                                      a_m_l['invoice_line_tax_id']=[[6,0,[tax_id]]]
                                   except:
                                          pass
                             self.pool.get('account.invoice.line').create(cr,uid,a_m_l)
                     self.pool.get('account.invoice').write(cr,uid,[refund_inv_id],{'name':creditmemo['increment_id'],'origin':creditmemo['increment_id']+' of order '+creditmemo['order_increment_id'],'magento_creditmemo_id':product['magento_creditmemo_id'],'amount_tax':0.0})        
                     cr.execute("insert into sale_order_invoice_rel (invoice_id,order_id)values(%s,%s)",(refund_inv_id,sale_obj.id))
                 total_no_of_records+=1
                 continue
                
         if magento_configuration_object[0].id:
             self.pool.get('magento.configuration').write(cr, uid, [magento_configuration_object[0].id], {'last_imported_credit_timestamp':start_timestamp})    
             server.endSession(session)
             return total_no_of_records    
         server.endSession(session)
         return -1           
    def import_orders (self,cr,uid): #Customized Import Order Function
        total_no_of_records=0# Number of sale order imported  
        start_timestamp = str(DateTime.utc())
        if True:
            # magneto object through which connecting openerp with defined magento configuration start
            start_timestamp = str(DateTime.utc())
            magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
            last_import = magento_configuration_object[0].last_imported_invoice_timestamp
            [status, server, session] = self.pool.get('magento.configuration').magento_openerp_syn(cr, uid)
            #checking server status
            if not status:
                raise osv.except_osv(_('There is no connection!'),_("There is no connection established with magento server\n\
                  please check the url,username and password") )
                server.endSession(session)
                return -1
            #end
            #API to fetch all sale order information
            listorder = server.call(session, 'sales_order.list',[{'updated_at': {'from':last_import}}])
            
            all_increment_id=[]
            all_customer_id=[]
            for info_order in listorder:
                if info_order['customer_id']:
                    all_customer_id.append(info_order['customer_id'])
                all_increment_id.append(info_order['increment_id'])
            min=0
            max_number_order_import=20
            if magento_configuration_object[0].max_number_order_import:
                max_number_order_import=int(magento_configuration_object[0].max_number_order_import)
            max=max_number_order_import
            length_ord=len(listorder)
            while length_ord>0:
                all_customer_id_max=all_customer_id[min:max]
                all_increment_id_max=all_increment_id[min:max]  
#                try:
#                   #API to get customer information for all customer_id at a time 
                info_customers = [server.call(session, 'customapi_customer.itemslist' , [all_customer_id_max])][0];
#                except:
#                   info_customers=[] 
                
#                try:     
                   #API to get sale order information for all increment_ids at a time
                info_orders = [server.call(session, 'customapi_order.itemslist',[all_increment_id_max])][0]; 
#                except:
#                   info_orders=[]   
                
                min=max
                length_ord=length_ord-max_number_order_import
                if length_ord<max_number_order_import:
                    max=min+length_ord 
                else:
                    max=max+max_number_order_import 
                for info_order in info_orders: 
                        header=info_order['0']
                        #API to get sale order information based on increment_id
                        name_sales_order = str(header['increment_id'])
                        #searching sale order availability in openerp based on magneto_id or Order Reference
                        id_orders = self.pool.get('sale.order').search(cr, uid, ['|',('magento_id', '=', header['order_id']),('name', '=', name_sales_order)])
                        if True:
                            #To get customer information for each sale order from list of info_customers
                            info_customer = [customer for customer in info_customers if header['customer_id']==customer['customer_id']]
                            if info_customer:
                                info_customer=info_customer[0]
                            else:
                                info_customer = {
                                        'customer_id' : '0'
                                    }
                            pricelist_ids = self.pool.get('product.pricelist').search(cr, uid,[])
                            if (header['customer_is_guest'] == '1'):
                                info_customer['store_id'] = header['store_id']
                                info_customer['website_id'] = '1'
                                info_customer['email'] = header['customer_email']
                                info_customer['firstname'] = info_order['billing_address']['firstname']
                                info_customer['lastname'] = info_order['billing_address']['lastname']
                                info_customer['customer_is_guest'] = '1'
                            info_customer['shipping_address'] = info_order['shipping_address']
                            info_customer['billing_address'] = info_order['billing_address']
                            #getting billing and shipping address id from openerp
                            erp_customer_info = self.pool.get('magento.configuration').update_customer(cr, uid, info_customer)
                        if id_orders == []:     
                            if  header['status'] == 'canceled':
                                state = 'cancel'
                            else:
                                state = 'draft'    
                            erp_sales_order = {
                                            'name' : name_sales_order,
                                            'order_policy' : 'manual',  
                                            'state' : state,  
                                            'partner_id' : erp_customer_info['id'],
                                            'partner_invoice_id'  : erp_customer_info['billing_id'],
                                            'partner_order_id'    : erp_customer_info['billing_id'],
                                            'partner_shipping_id' : erp_customer_info['shipping_id'],
                                            'pricelist_id'        : pricelist_ids[0],
                                            'magento_id'      : header['order_id'],
                                            'magento_increment_id' : header['increment_id'],
                                            'order_policy':'prepaid',
                                           }
                            #creating sale order record in openerp
                            #===================================================
                            # To Store the payment method information i openerp from magento
                            #===================================================
                            if 'method' in  info_order['payment'].keys() and (info_order['payment']['method']):
                                          erp_sales_order[ 'payment_method_string']=info_order['payment']['method']
                                          payment=erp_sales_order[ 'payment_method_string']
                                          if payment and payment.lower() in ['ops_paysafecard','ops_cc']:
                                                journal = self.pool.get('account.journal').search(cr,uid,[('name','ilike','Kartenzahlungen Webshop')])
                                          elif payment and payment.lower() =='bankpayment':      
                                                journal = self.pool.get('account.journal').search(cr,uid,[('name','ilike','vorkasse')])
                                          elif payment and 'paypal' in payment.lower():
                                                journal = self.pool.get('account.journal').search(cr,uid,[('name','ilike','Paypal')])    
                                          elif payment and 'sofort' in payment.lower():
                                                journal = self.pool.get('account.journal').search(cr,uid,[('name','ilike','Sofort')])           
                                          else:
                                                journal = False 
                                          if journal:
                                              erp_sales_order[ 'payment_me']=journal[0]
                            #=====================================
                            # End
                            #=====================================
                            id_orders = [self.pool.get('sale.order').create(cr, uid, erp_sales_order)]
                            if id_orders:
                               total_no_of_records+=1 
                            missing_products_in_openerp=False
                            parents = {}
                            product_ids_shop = []
                            base_price=0.0
                            #fetching sale order line information from magneto 
                            
                            for item in info_order['items']:	
                                if item.has_key('product_type') and (item['product_type'] == 'configurable'):
                                    parents[item['item_id']] = {
                                        'base_price':   item['base_price_incl_tax'],
                                        'tax_percent':  item['tax_percent'],
                                        'discount_amount':float(item['discount_amount']),
                                        'discount_percent':float(item['discount_percent']),
                                    }
                                    continue
                                #searching product availability in openerp for each sale order line
                                product_ids = self.pool.get('product.product').search(cr, uid, [('magento_id', '=', item['product_id'])])
                                if (product_ids == []):
                                    try:
                                       info_products = server.call(session, 'customapi_product.itemslist',[item['product_id']])
                                    except:
                                       info_products=[] 
                                    missing_products_in_openerp = True
                                    continue
                                product_id = product_ids[0]
                                if base_price:
                                    price =  base_price                                    
                                else:
                                    price = item['base_price_incl_tax']
                                if not price and item['parent_item_id']:
                                    price = parents[item['parent_item_id']]['base_price']    
                                if  item.has_key('product_type') and (item['product_type'] != 'simple'):
                                       price=0.0    
                                #making product object for each sale order line's product
                                my_product = self.pool.get('product.product').browse(cr, uid, product_id)  
                                #===============================================
                                # For shop selection
                                #===============================================
                                pos_categ  = my_product.pos_categ_id
                                if  pos_categ and pos_categ.shop_ids:
                                        for shop in pos_categ.shop_ids:
                                             product_ids_shop.append(shop.id)
                               #=======================================
                               # End
                               #=======================================
                               
                               #================================================
                               # To Sync Discount and Discount amount
                               #============================i====================
                                discount_amount=float(item['discount_amount'])
                                if float(item['discount_amount']):
                                    	discount_amount=float(item['discount_amount'])
                                else:
                                    if parents.has_key(item['parent_item_id']):
                                         discount_amount=parents[item['parent_item_id']]['discount_amount']
                                dis_percentage=float(item['discount_percent'])
                                if float(item['discount_percent']):
                                        dis_percentage=float(item['discount_percent'])
                                else:
                                    if parents.has_key(item['parent_item_id']):
                                        dis_percentage=parents[item['parent_item_id']]['discount_percent']
                               #================================================
                               # End
                               #================================================
                                
                                if item['tax_percent']=='0.0000' and item['parent_item_id']:
                                    try:
                                         item['tax_percent']=parents[item['parent_item_id']]['tax_percent']
                                    except:
                                              item['tax_percent']='0.0000'
                                try:
                                    if (item['tax_percent'] != '0.0000'):
                                        tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, item['tax_percent'])
                                        if (tax_id == 0):
                                            raise 
                                        else:
                                            tax_ids = [[6,0,[tax_id]]]   
                                    else:
                                        tax_ids = []
                                except:
                                    tax_ids = []      
                                erp_sales_order_line = { 'order_id'      : id_orders[0],
                                                         'product_id'      : product_id,
                                                         'name'            : item['name'],
                                                         'tax_id'          : tax_ids,
                                                         'price_unit'      : price,
                                                         'product_uom'     : my_product['uom_id']['id'],
                                                         'product_uom_qty' : item['qty_ordered'],
                                                         'discount'        : dis_percentage,
                                                         'discount_amount' : discount_amount,
                                }
                                #creating sale order line record in openerp
                                id_order_line = self.pool.get('sale.order.line').create(cr, uid, erp_sales_order_line)
###                                for shop checking in pos and storing in sale order
                            if product_ids_shop:
                                 list1 = list(set(product_ids_shop))
                                 if len(list1)==1:
                                     self.pool.get('sale.order').write(cr,uid,[id_orders[0]],{'shop_id':list1[0]})
                            #Shipping costs
                            try:
                                my_shipping = magento_configuration_object[0].shipping_product.id
                                try:
                                    if (header['shipping_tax_amount'] != '0.0000'):
                                        tax_percent = 100 * float(header['shipping_tax_amount']) / float(header['shipping_amount'])
                                        tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, tax_percent)
                                        if (tax_id == 0):
                                            raise  
                                        else:
                                            tax_ids = [[6,0,[tax_id]]]      
                                    else:
                                        tax_ids = []     
                                except:
                                    tax_ids = []
                                if (header['shipping_incl_tax'] !='0.0000'):
                                          erp_ship_line = {
                                                          'order_id'        : id_orders[0],
                                                          'name'            : header['shipping_description'].replace('Select Shipping Method','Shipping Charges'),
                                                          'price_unit'      : float(header['base_shipping_incl_tax']),
                                                          'product_id' :my_shipping,
                                                          'tax_id':tax_ids,
                                                          'product_uom_qty' : 1,
                                                        }
                                          order_line = self.pool.get('sale.order.line').create(cr, uid, erp_ship_line)        
                            except:
                                pass
                            if missing_products_in_openerp:
                                continue 
                        else:
                           pass
            #updating last imported time in openerp magneto object
            if magento_configuration_object[0].id:
                self.pool.get('magento.configuration').write(cr, uid, [magento_configuration_object[0].id], {'last_imported_invoice_timestamp':start_timestamp})    
                server.endSession(session)
                return total_no_of_records    
        server.endSession(session)
        return -1  
    def import_products(self, cr, uid, context=None):
        if context == None:
            context = {}
        total_no_of_records = 0
        start_timestamp = str(DateTime.utc())
        magento_configuration_object = self.pool.get("magento.configuration").get_magento_configuration_object(cr, uid)
        if magento_configuration_object == None:
            raise osv.except_osv(_("Import is in progress!"), _("Import Products is All ready Running "))
        try:
            # magneto object through which connecting openerp with defined magneto configuration start
            magento_configuration_object = self.pool.get("magento.configuration").get_magento_configuration_object(
                cr, uid
            )
            last_import = magento_configuration_object[0].last_imported_product_timestamp  # last imported time
            if magento_configuration_object[0].sync_status == "Running":
                raise osv.except_osv(_("Import is in process!"), _("Import Products is All ready Running "))
            [status, server, session] = self.pool.get("magento.configuration").magento_openerp_syn(cr, uid)
            if not status:
                server.endSession(session)
                return -1
            # end
        except:
            #            server.endSession(session)
            return -1
        self.pool.get("magento.configuration").write(
            cr, uid, [magento_configuration_object[0].id], {"sync_status": "Running"}
        )
        increment = 30000
        index = 1
        max_number_product_import = 30000  # max number import product per connection
        attribute_sets = server.call(session, "product_attribute_set.list")
        while True:
            stop = index + increment - 1
            # fetching all information from magneto based on last imported time
            if last_import:
                all_products = server.call(
                    session,
                    "product.list",
                    [{"updated_at": {"from": last_import}, "product_id": {"from": str(index), "to": str(stop)}}],
                )
                products = all_products
            else:
                all_products = server.call(
                    session, "product.list", [{"product_id": {"from": str(index), "to": str(stop)}}]
                )
                products = all_products
            index = stop + 1
            all_product_id = []
            for prod in products:
                all_product_id.append(prod["product_id"])
            # Fetching Product,Based on min and max number from magneto (Due to Response error)
            min = 0
            if magento_configuration_object[0].max_number_product_import:
                max_number_product_import = int(
                    magento_configuration_object[0].max_number_product_import
                )  # In Openerp,Configured max number per connection for product
            max = max_number_product_import
            length_prod = len(all_product_id)  # length of all product in magneto

            while length_prod > 0:
                all_product_id_max = all_product_id[min:max]

                # API to get all products information from magneto
                try:
                    info_products = server.call(session, "customapi_product.itemslist", [all_product_id_max])
                except:
                    info_products = []
                # To modify min,max and total length of product start
                min = max
                length_prod = length_prod - max_number_product_import
                if length_prod < max_number_product_import:
                    max = min + length_prod
                else:
                    max = max + max_number_product_import
                # End
                for info_product in info_products:
                    try:
                        info_category = info_product
                        info_product = info_product["0"]
                        tax_parcent = False
                        try:
                            tax_parcent = info_category["tax_percent"]
                            tax_class_id = info_product["tax_class_id"]
                            if tax_parcent:
                                tax_id = self.pool.get("magento.configuration").get_tax_id(cr, uid, tax_parcent)
                                if tax_class_id:
                                    self.pool.get("account.tax").write(
                                        cr, uid, tax_id, {"magento_id": int(tax_class_id)}
                                    )
                                if tax_id == 0:
                                    raise
                                else:
                                    tax_ids = [[6, 0, [tax_id]]]
                        except Exception, e:
                            tax_ids = []
                        product = {
                            "magento_id": info_product["entity_id"],
                            "magento_name": info_product["name"],
                            "name": info_product["name"],
                            "default_code": info_product["sku"],
                            "modified": False,
                            "type": "product",
                            "export_to_magento": True,
                            "taxes_id": tax_ids,
                            "magento_attr_id": info_product["attribute_set_id"]
                            #                          'description':info_product['description'],
                        }
                        if "openerp_name" in info_product.keys() and info_product["openerp_name"]:
                            product["name"] = info_product["openerp_name"]
                        product["list_price"] = info_product["price"]
                        try:
                            product["weight"] = info_product["weight"]
                        except:
                            product["weight"] = "0.00"
                        if info_product.has_key("type_id") and info_product["type_id"] == "bundle":
                            product["magento_pro_type"] = info_product["type_id"]
                        if info_category.has_key("category_ids") and info_category["category_ids"]:
                            magento_cat_ids = info_category["category_ids"]
                        elif info_category.has_key("categories") and info_category["categories"]:
                            magento_cat_ids = info_category["categories"]
                        else:
                            magento_cat_ids = []
                        # searching category availability in openerp
                        if magento_cat_ids:
                            cat_ids = self.pool.get("product.category").search(
                                cr, uid, [("magento_id", "=", magento_cat_ids[-1])]
                            )
                            if cat_ids[0]:
                                product["categ_id"] = cat_ids[0]
                            else:
                                product["categ_id"] = magento_configuration_object[0].default_category.id
                        else:
                            product["categ_id"] = magento_configuration_object[0].default_category.id
                        # searching product availability in openerp
                        prod_ids = self.pool.get("product.product").search(
                            cr, uid, [("magento_id", "=", product["magento_id"])]
                        )
                        #####image fetching for specific product###############################
                        # try:
                        img_list = server.call(session, "catalog_product_attribute_media.list", [product["magento_id"]])

                        #                        except:
                        #                           img_list=[]
                        ########End###########################################################
                        if prod_ids == []:
                            # inserting new product in openerp
                            product["magento_name"] = product["name"]
                            prod_ids = [self.pool.get("product.product").create(cr, uid, product)]
                            if prod_ids:
                                total_no_of_records += 1  # count number of imported records in openerp
                            #####Import image in openerp start#####################################
                            id1 = []
                            for image in img_list:
                                images_dict = {
                                    "name": image["label"],
                                    "filename": image["url"],
                                    "position": image["position"],
                                    "exclude": image["exclude"],
                                    "product_id": prod_ids[0],
                                    # 'file' : image['file']
                                }

                                for type in image["types"]:

                                    images_dict[type] = True
                                    if type == "thumbnail":
                                        (filename, header) = urllib.urlretrieve(image["url"])
                                        f = open(filename, "rb")
                                        img = base64.encodestring(f.read())
                                        f.close()
                                #                                            self.pool.get('product.product').write(cr,uid,prod_ids[0],{'image_medium' :img})
                                self.pool.get("product.images").create(cr, uid, images_dict)

                            # self.pool.get('product.product').write(cr,uid,prod_ids[0],{'image_ids' :id1})
                            # End#######################################################################
                        else:
                            total_no_of_records += 1
                            # updating product information in openerp
                            # Dantunes Requirement to dont update category#
                            if "categ_id" in product.keys():
                                del (product["categ_id"])
                            ##########End##########
                            if "update" not in context.keys():
                                self.pool.get("product.product").write(cr, uid, [prod_ids[0]], product)

                            #####Import image in openerp start#######################################
                            for image in img_list:
                                images_dict = {
                                    "name": image["label"] or "test",
                                    "filename": image["url"],
                                    "position": image["position"],
                                    "exclude": image["exclude"],
                                    "product_id": prod_ids[0],
                                }
                                for type in image["types"]:
                                    images_dict[type] = True
                                    if type == "thumbnail":
                                        (filename, header) = urllib.urlretrieve(image["url"])
                                        f = open(filename, "rb")
                                        img = base64.encodestring(f.read())
                                        f.close()
                                #                                            self.pool.get('product.product').write(cr,uid,prod_ids[0],{'image_medium' :img})
                                # searching product image in openerp
                                prod_img_id = self.pool.get("product.images").search(
                                    cr, uid, [("product_id", "=", prod_ids[0]), ("filename", "=", image["url"])]
                                )
                                if prod_img_id:
                                    # updating product image in openerp if image exist
                                    self.pool.get("product.images").write(cr, uid, [prod_img_id[0]], images_dict)
                                else:
                                    # creating product image in openerp
                                    self.pool.get("product.images").create(cr, uid, images_dict)
                            # End#######################################################################
                        if prod_ids == []:
                            return -1
                    except:
                        pass
示例#10
0
    def import_customers(self,cr,uid):
        total_records=0#count number of imported records
        # magneto object through which connecting openerp with defined magento configuration start
        start_timestamp = str(DateTime.utc())
        magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
        last_import = magento_configuration_object[0].last_imported_customer_timestamp
        [status, server, session] = self.pool.get('magento.configuration').magento_openerp_syn(cr, uid)
        #checking server status
        if not status:
            raise osv.except_osv(_('There is no connection!'),_("There is no connection established with magento server\n\
                  please check the url,username and password") )
#            server.endSession(session)
            return -1
        #end
        ################################################### Import Customer Groups  #########################
        #API for importing customer group from magneto 
        max_number_customer_import =30000 #max number import customer per connection
        customer_groups = server.call(session, 'customer_group.list',[])
        #creating all customer groups in openerp start
        for cus_group in customer_groups:
            cus_grp_data = {
                            'name' : cus_group['customer_group_code'],
                            'magento_id' : cus_group['customer_group_id'],
                            }
            
            cust_grp_ids = self.pool.get('res.partner.category').search(cr, uid, [('magento_id', '=', cus_grp_data['magento_id'])])
            if cust_grp_ids == []:
                cust_grp_ids = [self.pool.get('res.partner.category').create(cr, uid,cus_grp_data)]
            else:
                self.pool.get('res.partner.category').write(cr, uid,[cust_grp_ids[0]],cus_grp_data)
        #end
        #fetching all customer information from magento based on last imported time
        increment = 20000
        index = 1
        stop = index + increment - 1
        if last_import:
            customers = server.call(session, 'customer.list',[ {'updated_at': {'from': last_import},'customer_id': {'from': str(index), 'to': str(stop)}}])
        else:  
            all_customers = server.call(session, 'customer.list',[{'customer_id': {'from': str(index), 'to': str(stop)}}])
            customers = all_customers
        all_customer_id=[]
        for cus in customers:
            all_customer_id.append(cus['customer_id'])
        
        
         #Fetching Product,Based on min and max number from magneto (Due to Response error)
        min=0
        if magento_configuration_object[0].max_number_customer_import:
             max_number_customer_import=int(magento_configuration_object[0].max_number_customer_import)#In Openerp,Configured max number per connection for product 
        max=max_number_customer_import
        length_cust=len(all_customer_id)#length of all product in magneto   
        while length_cust>0:
                all_customer_id_max=all_customer_id[min:max]
                try:
                   #API to get all customer informations based on all customer    
                   info_customers = server.call(session, 'customapi_customer.itemslist',[all_customer_id_max])
                except Exception,e:
                   info_customers=[]
                    #To modify min,max and total length of product start
                min=max
                length_cust=length_cust-max_number_customer_import
                if length_cust<max_number_customer_import:
                    max=min+length_cust
                else:
                    max=max+max_number_customer_import
                #End   
              
                for info_customer in info_customers:
                    customer_address=[]
                    if info_customer.has_key('addresses') and info_customer['addresses']:
                          customer_address = info_customer['addresses']
                    #fetching customer group id from openerp
                    if info_customer.has_key('group_id') and info_customer['group_id']:
                      cust_grp_ids = self.pool.get('res.partner.category').search(cr, uid, [('magento_id', '=', info_customer['group_id'])])
                      #all categorie's object
                      category_ids =self.pool.get('res.partner.category').browse(cr,uid,cust_grp_ids)
                    #dict for customer information that we are going to insert in openerp
                    
                    erp_customer = {  
                                    'magento_id'     : info_customer['customer_id'],
                                    'export_magento' : True,
                                    'name'           : info_customer['firstname'],
                                    'email'          : info_customer['email'],
                                    'group_id'       : cust_grp_ids[0] or False,
                                    'created_at'     : info_customer['created_at'],
                                    'website_id'     : info_customer['website_id'],
                                    'customer'       : True,
                                    'modified'       : False,
                                    'supplier'       : False
                                    }
                    if info_customer['lastname']:
                         erp_customer['name'] = info_customer['firstname'] + ' ' + info_customer['lastname']
                    #searching availability of customer in openerp
                    cust_ids = self.pool.get('res.partner').search(cr, uid, [('magento_id', '=', int(erp_customer['magento_id']))])
                    if cust_ids == []:
                      if 1==1:
                        #creating customer record in openerp   
                        cust_ids = [self.pool.get('res.partner').create(cr, uid, erp_customer)]
                        if cust_ids:
                               total_records+=1 
                        for cust_grp_id in cust_grp_ids:
                               cr.execute('insert into res_partner_res_partner_category_rel (category_id,partner_id) \
                                      values (%s,%s)', (cust_grp_id, cust_ids[0]))
                        #inserting customer address in openerp
                        i =0
                        for cus_add in customer_address:
                            i +=1
                            try:
                                country_id = self.pool.get('res.country').name_search(cr, uid, cus_add['country_id'])[0][0]
                            except:
                                if 'country_id' in cus_add.keys():
                                        new_country = { 
                                                        'name': cus_add['country_id'],
                                                        'code': cus_add['country_id']
                                                       }
                                        country_id = self.pool.get('res.country').create(cr, uid, new_country)
                            phone=''
                            if info_customer.has_key('phone') and info_customer['phone']:
                                phone=info_customer['phone']
                            fax=''
                            if cus_add.has_key('fax') and cus_add['fax']:
                                fax=cus_add['fax']
                            postcode=''
                            if cus_add.has_key('postcode') and cus_add['postcode']:
                                postcode=cus_add['postcode']
                            city=''
                            if cus_add.has_key('city') and cus_add['city']:
                                city=cus_add['city']     
                            telephone=''
                            if cus_add.has_key('telephone') and cus_add['telephone']:
                                telephone=cus_add['telephone']          
                            street=''
                            if cus_add.has_key('street') and cus_add['street']:
                                street=cus_add['street']
                                
                            cus_address={
                                          'magento_address_id': cus_add['customer_address_id'],
                                          'type'  : 'delivery',
                                          'street': street,
                                          'zip'  : postcode,
                                          'fax' : fax ,
                                          'city' : city,
                                          'country_id': country_id,
                                          'email': info_customer['email'],
                                          'mobile': phone,
                                          'phone': telephone,
                                          'use_parent_address':False,
                                          #'is_default_shipping' : cus_add['is_default_shipping'],
                                         # 'is_default_billing'  : cus_add['is_default_billing'],
                                         }
                            
                            if cus_add.has_key('region_id') and   cus_add['region_id'] and int(cus_add['region_id']) > 0:
                                state_id = self.pool.get('res.country.state').search(cr, uid, [('magento_id', '=', cus_add['region_id'])])
                                if state_id:
                                      self.pool.get('res.country.state').write(cr, uid, [state_id[0]], {'name' : cus_add['region'] } )
                                      cus_address['state_id'] = state_id[0]
        #                        else:
        #                             state_id = [self.pool.get('res.country.state').create(cr, uid, {'name' : cus_add['region'] ,'magento_id':cus_add['region_id'],'country_id' : country_id} )]
        #                        cus_address['state_id'] = state_id[0]
                            elif cus_add.has_key('region') and cus_add['region']:
                                      state_id = self.pool.get('res.country.state').search(cr, uid, [('name', '=', cus_add['region']),('country_id','=',country_id)])
                                      if state_id:
                                          self.pool.get('res.country.state').write(cr, uid, [state_id[0]], {'name' : cus_add['region'] } )
                                          cus_address['state_id'] = state_id[0]
        #                              else:
        #                                 state_id = [self.pool.get('res.country.state').create(cr, uid, {'name' : cus_add['region'],'country_id' : country_id } )]
                                      
                            if 'is_default_shipping' in cus_add.keys() and cus_add['is_default_shipping']:
                               cus_address['type'] = 'delivery'
                            if cus_add['is_default_billing']: 
                               cus_address['type'] = 'invoice'
                            if cus_add['is_default_billing'] and cus_add['is_default_shipping']:
                               cus_address['type'] = 'default'    
                            if not cus_add['is_default_billing'] and not cus_add['is_default_shipping']:
                               cus_address['type'] = 'delivery'
                            
                            if i==1:
                               
                               cus_address['is_company']  = True  
                               cust_add_ids = [self.pool.get('res.partner').write(cr, uid,[cust_ids[0]], cus_address)]
                               
                            else:
                                 
                                 cus_address['parent_id'] = cust_ids[0]    
                                 cus_address['name'] = cus_add['firstname'] + ' ' + cus_add['lastname']
                                 cust_add_ids = [self.pool.get('res.partner').create(cr, uid, cus_address)]
        #              except:
        #                  pass
                    else:
                        total_records+=1
                        self.pool.get('res.partner').write(cr, uid, [cust_ids[0]], erp_customer)
                        partner_address=[]
                        #Group Updation in openerp
                        for cust_grp_id in cust_grp_ids:
                                cr.execute("""select category_id from res_partner_res_partner_category_rel where
                                    category_id = %s and  partner_id = %s """ , (cust_grp_id, cust_ids[0])  )
                                if not cr.dictfetchall():
                                    cr.execute('insert into res_partner_res_partner_category_rel (category_id,partner_id) \
                                    values (%s,%s)', (cust_grp_id, cust_ids[0]))
                        #Address updation for a specified customer in openerp
                        
                        for cus_add in customer_address:
                            
                            #searching country availability in openerp start
                            try:
                                country_id = self.pool.get('res.country').name_search(cr, uid, cus_add['country_id'])[0][0]
                            except:
                                new_country = { 
                                                'name': cus_add['country_id'],
                                                'code': cus_add['country_id']
                                               }
                                country_id = self.pool.get('res.country').create(cr, uid, new_country)
                            #end
                            phone=''
                            if info_customer.has_key('phone') and info_customer['phone']:
                                phone=info_customer['phone']
                                
                            fax=''
                            if cus_add.has_key('fax') and cus_add['fax']:
                                fax=cus_add['fax']
                            postcode=''
                            if cus_add.has_key('postcode') and cus_add['postcode']:
                                postcode=cus_add['postcode']
                            city=''
                            if cus_add.has_key('city') and cus_add['city']:
                                city=cus_add['city']     
                            telephone=''
                            if cus_add.has_key('telephone') and cus_add['telephone']:
                                telephone=cus_add['telephone']              
                            street=''
                            if cus_add.has_key('street') and cus_add['street']:
                                street=cus_add['street']    
                            company=''    
                            if cus_add.has_key('company') and cus_add['company']:
                                company=cus_add['company']        
                            cus_address = { 
                                    'magento_address_id'   : cus_add['customer_address_id'],
                                     'partner_id'  : cust_ids[0],
                                     'type'        : 'delivery',
                                     
                                      'street'     : street,
                                      'zip'        : postcode,
                                      'city'       : city,
                                      'email'      : info_customer['email'],
                                       'mobile'    : phone,
                                      'country_id' : country_id,
                                      'fax'        : fax ,
                                      'phone'      : telephone,
                                      'company':company,
                                      'is_default_shipping' : cus_add['is_default_shipping'],
                                      'is_default_billing' : cus_add['is_default_billing'],
                                         'use_parent_address':False,
                                           }
                            #searching state availability in openerp start
                            if cus_add.has_key('region_id') and   cus_add['region_id'] and int(cus_add['region_id']) > 0:
                                state_id = self.pool.get('res.country.state').search(cr, uid, [('magento_id', '=', cus_add['region_id'])])
                                if state_id:
                                      self.pool.get('res.country.state').write(cr, uid, [state_id[0]], {'name' : cus_add['region'] } )
                                      cus_address['state_id'] = state_id[0]
        #                        else:
        #                             state_id = [self.pool.get('res.country.state').create(cr, uid, {'name' : cus_add['region'] ,'magento_id':cus_add['region_id'],'country_id' : country_id} )]
        #                        cus_address['state_id'] = state_id[0]   
                            elif cus_add.has_key('region') and cus_add['region']:
                                      state_id = self.pool.get('res.country.state').search(cr, uid, [('name', '=', cus_add['region']),('country_id','=',country_id)])
                                      if state_id:
                                         self.pool.get('res.country.state').write(cr, uid, [state_id[0]], {'name' : cus_add['region'] } )
                                         cus_address['state_id'] = state_id[0]
        #                              else:
        #                                  state_id = [self.pool.get('res.country.state').create(cr, uid, {'name' : cus_add['region'],'country_id' : country_id } )]
        #                              cus_address['state_id'] = state_id[0]         
                            #end
                            if cus_add['is_default_shipping']:
                               cus_address['type'] = 'delivery'
                            if cus_add['is_default_billing']: 
                               cus_address['type'] = 'invoice'
                            if cus_add['is_default_billing'] and cus_add['is_default_shipping']:
                               cus_address['type'] = 'default'     
                            if not cus_add['is_default_billing'] and not cus_add['is_default_shipping']:
                               cus_address['type'] = 'default' 
                            #checking availability of address in openerp for a specified customer
                            cust_add_ids = self.pool.get('res.partner').search(cr, uid, [('magento_address_id', '=', cus_address['magento_address_id'])])
                            if  cust_add_ids:
                                self.pool.get('res.partner').write(cr, uid, [cust_add_ids[0]], cus_address )
                                partner_address.append(cust_add_ids[0])
                            else:
                                cus_address['parent_id'] = cust_ids[0]    
                                cus_address['name'] = cus_add['firstname'] + ' ' + cus_add['lastname']           
                                cust_add_ids = [self.pool.get('res.partner').create(cr, uid, cus_address)]
                                partner_address.append(cust_add_ids[0])
                        #unlink the old address for a specified customer in openerp start
                        address_ids = self.pool.get('res.partner').search(cr, uid, [('parent_id', '=', cust_ids[0])]) 
#                        for line in address_ids:
#                            if line not in partner_address: 
#                                self.pool.get('res.partner').write(cr, uid, [line], {'parent_id':False,'magento_id':-2} )        
                cr.commit()
    def import_orders (self,cr,uid): #Customized Import Order Function
        total_no_of_records=0# Number of sale order imported  
        start_timestamp = str(DateTime.utc())
        if True:
            # magneto object through which connecting openerp with defined magento configuration start
            start_timestamp = str(DateTime.utc())
            magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
            last_import = magento_configuration_object[0].last_imported_invoice_timestamp
            [status, server, session] = self.pool.get('magento.configuration').magento_openerp_syn(cr, uid)
            #checking server status
            if not status:
                raise osv.except_osv(_('There is no connection!'),_("There is no connection established with magento server\n\
                  please check the url,username and password") )
                server.endSession(session)
                return -1
            #end
            #API to fetch all sale order information###################################################
	    increment = 1000
            index = 1
            while(True):
              stop = index + increment - 1
	      if last_import:
		  listorder = server.call(session, 'sales_order.list',[{'updated_at': {'from':last_import}}])
	      else:
                  listorder = server.call(session, 'sales_order.list',[{'updated_at': {'from':last_import},'order_id': {'from': str(index), 'to': str(stop)}}])
              index = stop + 1
              all_increment_id=[]
              all_customer_id=[]
              for info_order in listorder:
                if info_order['customer_id']:
                    all_customer_id.append(info_order['customer_id'])
                all_increment_id.append(info_order['increment_id'])
              min=0
              max_number_order_import=20
              if magento_configuration_object[0].max_number_order_import:
                max_number_order_import=int(magento_configuration_object[0].max_number_order_import)
              max=max_number_order_import
              length_ord=len(listorder)
              while length_ord>0:
                all_customer_id_max=all_customer_id[min:max]
                all_increment_id_max=all_increment_id[min:max]  
#                try:
#                   #API to get customer information for all customer_id at a time 
                info_customers = [server.call(session, 'customapi_customer.itemslist' , [all_customer_id_max])][0];
#                except:
#                   info_customers=[] 
                
#                try:     
                   #API to get sale order information for all increment_ids at a time
                info_orders = [server.call(session, 'customapi_order.itemslist',[all_increment_id_max])][0]; 
#                except:
#                   info_orders=[]   
                
                min=max
                length_ord=length_ord-max_number_order_import
                if length_ord<max_number_order_import:
                    max=min+length_ord 
                else:
                    max=max+max_number_order_import 
                for info_order in info_orders: 
                        header=info_order['0']
                        #API to get sale order information based on increment_id
                        name_sales_order = str(header['increment_id'])
                        #searching sale order availability in openerp based on magneto_id or Order Reference
                        id_orders = self.pool.get('sale.order').search(cr, uid, ['|',('magento_id', '=', header['order_id']),('name', '=', name_sales_order)])
                        if True:
                            #To get customer information for each sale order from list of info_customers
                            info_customer = [customer for customer in info_customers if header['customer_id']==customer['customer_id']]
                            if info_customer:
                                info_customer=info_customer[0]
                            else:
                                info_customer = {
                                        'customer_id' : '0'
                                    }
                            pricelist_ids = self.pool.get('product.pricelist').search(cr, uid,[])
                            if (header['customer_is_guest'] == '1'):
                                info_customer['store_id'] = header['store_id']
                                info_customer['website_id'] = '1'
                                info_customer['email'] = header['customer_email']
                                info_customer['firstname'] = info_order['billing_address']['firstname']
                                info_customer['lastname'] = info_order['billing_address']['lastname']
                                info_customer['customer_is_guest'] = '1'
                            info_customer['shipping_address'] = info_order['shipping_address']
                            info_customer['billing_address'] = info_order['billing_address']
                            #getting billing and shipping address id from openerp
                            erp_customer_info = self.pool.get('magento.configuration').update_customer(cr, uid, info_customer)
                        if id_orders == []:     
                            if  header['status'] == 'canceled':
                                state = 'cancel'
                            else:
                                state = 'draft'    
                            
                            erp_sales_order = {
                                            'name' : name_sales_order,
                                            'date_order':header['created_at'],
                                            'state' : state,  
                                            'partner_id' : erp_customer_info['id'],
                                            'partner_invoice_id'  : erp_customer_info['billing_id'],
                                            'partner_order_id'    : erp_customer_info['billing_id'],
                                            'partner_shipping_id' : erp_customer_info['shipping_id'],
                                            'pricelist_id'        : pricelist_ids[0],
                                            'magento_id'      : header['order_id'],
                                            'magento_increment_id' : header['increment_id'],
                                           
                                           }
                           
                            if 'status_history' in info_order.keys() and (info_order['status_history']):
                                erp_sales_order['note']=''
                                for comment in info_order['status_history']:
                                            if comment['comment']:
                                                  erp_sales_order['note'] +=comment['comment']+'\n'
                            #creating sale order record in openerp
                            id_orders = [self.pool.get('sale.order').create(cr, uid, erp_sales_order)]
                            if id_orders:
                               total_no_of_records+=1 
                            missing_products_in_openerp=False
                            parents = {}
                            base_price=0.0
                            #fetching sale order line information from magneto 
                            for item in info_order['items']:
                                if item.has_key('product_type') and (item['product_type'] in ['configurable','bundle']):
                                    parents[item['item_id']] = {
                                        'base_price':   item['base_price'],
                                        'tax_percent':  item['tax_percent'],
                                    }
                                    continue
                                #searching product availability in openerp for each sale order line
                                product_ids = self.pool.get('product.product').search(cr, uid, [('magento_id', '=', item['product_id'])])
                                if (product_ids == []):
                                    try:
                                       info_products = server.call(session, 'catalog_product.itemslist',[item['product_id']])
                                    except:
                                       info_products=[] 
                                    missing_products_in_openerp = True
                                    continue
                                product_id = product_ids[0]
                                if base_price:
                                    price =  base_price                                    
                                else:
                                    price = item['base_price_incl_tax'] or item['base_price']
                                if  item.has_key('product_type') and item['product_type'] and (item['product_type'] != 'simple'):
                                       price=0.0    
                                #making product object for each sale order line's product
                                my_product = self.pool.get('product.product').browse(cr, uid, product_id)   
                                try:
                                    if (item['tax_percent'] != '0.0000'):
                                        tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, item['tax_percent'])
                                        if (tax_id == 0):
                                            raise 
                                        else:
                                            tax_ids = [[6,0,[tax_id]]]   
                                    else:
                                        tax_ids = []
                                except:
                                    tax_ids = []      
                                erp_sales_order_line = { 'order_id'      : id_orders[0],
                                                         'product_id'      : product_id,
                                                         'name'            : my_product['name'],
                                                         'tax_id'          : tax_ids,
                                                         'price_unit'      : price,
                                                         'product_uom'     : my_product['uom_id']['id'],
                                                         'product_uom_qty' : item['qty_ordered'],
                                } 
                                #creating sale order line record in openerp
                                id_order_line = self.pool.get('sale.order.line').create(cr, uid, erp_sales_order_line)
                            #Shipping costs
                            try:
                                my_shipping = magento_configuration_object[0].shipping_product.id
                                try:
                                    if (header['shipping_tax_amount'] != '0.0000'):
                                        tax_percent = 100 * float(header['shipping_tax_amount']) / float(header['shipping_amount'])
                                        tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, tax_percent)
                                        if (tax_id == 0):
                                            raise  
                                        else:
                                            tax_ids = [[6,0,[tax_id]]]      
                                    else:
                                        tax_ids = []     
                                except:
                                    tax_ids = []
                                if (header['shipping_incl_tax'] !='0.0000'):
                                          erp_ship_line = {
                                                         'order_id'      : id_orders[0],
                                                         'name'            : header['shipping_description'].replace('Select Shipping Method','Shipping Charges'),
                                                          'price_unit'      : float(header['shipping_incl_tax']),
                                                          'product_id' :my_shipping,
                                                          'tax_id':tax_ids,
                                                          'product_uom_qty' : 1,
                                                        }
                                          order_line = self.pool.get('sale.order.line').create(cr, uid, erp_ship_line)    
                            except:
                                pass
                            if missing_products_in_openerp:
                                continue 
                        else:
                           pass
	      cr.commit()
	      if last_import or not listorder:
		break
            #updating last imported time in openerp magneto object
            if magento_configuration_object[0].id:
                self.pool.get('magento.configuration').write(cr, uid, [magento_configuration_object[0].id], {'last_imported_invoice_timestamp':start_timestamp})    
                server.endSession(session)
                return total_no_of_records    
        server.endSession(session)
        return -1  
示例#12
0
    def import_orders(self, cr, uid):  #Customized Import Order Function
        total_no_of_records = 0  # Number of sale order imported
        start_timestamp = str(DateTime.utc())
        if True:
            # magneto object through which connecting openerp with defined magento configuration start
            start_timestamp = str(DateTime.utc())
            magento_configuration_object = self.pool.get(
                'magento.configuration').get_magento_configuration_object(
                    cr, uid)
            last_import = magento_configuration_object[
                0].last_imported_invoice_timestamp
            [status, server, session
             ] = self.pool.get('magento.configuration').magento_openerp_syn(
                 cr, uid)
            #checking server status
            if not status:
                raise osv.except_osv(
                    _('There is no connection!'),
                    _("There is no connection established with magento server\n\
                  please check the url,username and password"))
                server.endSession(session)
                return -1
            #end
            #API to fetch all sale order information
            listorder = server.call(session, 'sales_order.list', [{
                'updated_at': {
                    'from': last_import
                }
            }])

            all_increment_id = []
            all_customer_id = []
            for info_order in listorder:
                if info_order['customer_id']:
                    all_customer_id.append(info_order['customer_id'])
                all_increment_id.append(info_order['increment_id'])
            min = 0
            max_number_order_import = 20
            if magento_configuration_object[0].max_number_order_import:
                max_number_order_import = int(
                    magento_configuration_object[0].max_number_order_import)
            max = max_number_order_import
            length_ord = len(listorder)
            while length_ord > 0:
                all_customer_id_max = all_customer_id[min:max]
                all_increment_id_max = all_increment_id[min:max]
                #                try:
                #                   #API to get customer information for all customer_id at a time
                info_customers = [
                    server.call(session, 'customapi_customer.itemslist',
                                [all_customer_id_max])
                ][0]
                #                except:
                #                   info_customers=[]

                #                try:
                #API to get sale order information for all increment_ids at a time
                info_orders = [
                    server.call(session, 'customapi_order.itemslist',
                                [all_increment_id_max])
                ][0]
                #                except:
                #                   info_orders=[]

                min = max
                length_ord = length_ord - max_number_order_import
                if length_ord < max_number_order_import:
                    max = min + length_ord
                else:
                    max = max + max_number_order_import
                for info_order in info_orders:
                    header = info_order['0']
                    #API to get sale order information based on increment_id
                    name_sales_order = str(header['increment_id'])
                    #searching sale order availability in openerp based on magneto_id or Order Reference
                    id_orders = self.pool.get('sale.order').search(
                        cr, uid, [
                            '|', ('magento_id', '=', header['order_id']),
                            ('name', '=', name_sales_order)
                        ])
                    if True:
                        #To get customer information for each sale order from list of info_customers
                        info_customer = [
                            customer for customer in info_customers
                            if header['customer_id'] == customer['customer_id']
                        ]
                        if info_customer:
                            info_customer = info_customer[0]
                        else:
                            info_customer = {'customer_id': '0'}
                        pricelist_ids = self.pool.get(
                            'product.pricelist').search(cr, uid, [])
                        if (header['customer_is_guest'] == '1'):
                            info_customer['store_id'] = header['store_id']
                            info_customer['website_id'] = '1'
                            info_customer['email'] = header['customer_email']
                            info_customer['firstname'] = info_order[
                                'billing_address']['firstname']
                            info_customer['lastname'] = info_order[
                                'billing_address']['lastname']
                            info_customer['customer_is_guest'] = '1'
                        info_customer['shipping_address'] = info_order[
                            'shipping_address']
                        info_customer['billing_address'] = info_order[
                            'billing_address']
                        #getting billing and shipping address id from openerp
                        erp_customer_info = self.pool.get(
                            'magento.configuration').update_customer(
                                cr, uid, info_customer)
                    if id_orders == []:
                        if header['status'] == 'canceled':
                            state = 'cancel'
                        else:
                            state = 'draft'
                        erp_sales_order = {
                            'name': name_sales_order,
                            'order_policy': 'manual',
                            'state': state,
                            'partner_id': erp_customer_info['id'],
                            'partner_invoice_id':
                            erp_customer_info['billing_id'],
                            'partner_order_id':
                            erp_customer_info['billing_id'],
                            'partner_shipping_id':
                            erp_customer_info['shipping_id'],
                            'pricelist_id': pricelist_ids[0],
                            'magento_id': header['order_id'],
                            'magento_increment_id': header['increment_id'],
                            'order_policy': 'prepaid',
                        }
                        #creating sale order record in openerp
                        #===================================================
                        # To Store the payment method information i openerp from magento
                        #===================================================
                        if 'method' in info_order['payment'].keys() and (
                                info_order['payment']['method']):
                            erp_sales_order[
                                'payment_method_string'] = info_order[
                                    'payment']['method']
                            payment = erp_sales_order['payment_method_string']
                            if payment and payment.lower() in [
                                    'ops_paysafecard', 'ops_cc'
                            ]:
                                journal = self.pool.get(
                                    'account.journal').search(
                                        cr, uid, [('name', 'ilike',
                                                   'Kartenzahlungen Webshop')])
                            elif payment and payment.lower() == 'bankpayment':
                                journal = self.pool.get(
                                    'account.journal').search(
                                        cr, uid,
                                        [('name', 'ilike', 'vorkasse')])
                            elif payment and 'paypal' in payment.lower():
                                journal = self.pool.get(
                                    'account.journal').search(
                                        cr, uid, [('name', 'ilike', 'Paypal')])
                            elif payment and 'sofort' in payment.lower():
                                journal = self.pool.get(
                                    'account.journal').search(
                                        cr, uid, [('name', 'ilike', 'Sofort')])
                            else:
                                journal = False
                            if journal:
                                erp_sales_order['payment_me'] = journal[0]
                        #=====================================
                        # End
                        #=====================================
                        id_orders = [
                            self.pool.get('sale.order').create(
                                cr, uid, erp_sales_order)
                        ]
                        if id_orders:
                            total_no_of_records += 1
                        missing_products_in_openerp = False
                        parents = {}
                        product_ids_shop = []
                        base_price = 0.0
                        #fetching sale order line information from magneto

                        for item in info_order['items']:
                            if item.has_key('product_type') and (
                                    item['product_type'] == 'configurable'):
                                parents[item['item_id']] = {
                                    'base_price':
                                    item['base_price_incl_tax'],
                                    'tax_percent':
                                    item['tax_percent'],
                                    'discount_amount':
                                    float(item['discount_amount']),
                                    'discount_percent':
                                    float(item['discount_percent']),
                                }
                                continue
                            #searching product availability in openerp for each sale order line
                            product_ids = self.pool.get(
                                'product.product').search(
                                    cr, uid,
                                    [('magento_id', '=', item['product_id'])])
                            if (product_ids == []):
                                try:
                                    info_products = server.call(
                                        session, 'customapi_product.itemslist',
                                        [item['product_id']])
                                except:
                                    info_products = []
                                missing_products_in_openerp = True
                                continue
                            product_id = product_ids[0]
                            if base_price:
                                price = base_price
                            else:
                                price = item['base_price_incl_tax']
                            if not price and item['parent_item_id']:
                                price = parents[
                                    item['parent_item_id']]['base_price']
                            if item.has_key('product_type') and (
                                    item['product_type'] != 'simple'):
                                price = 0.0
                            #making product object for each sale order line's product
                            my_product = self.pool.get(
                                'product.product').browse(cr, uid, product_id)
                            #===============================================
                            # For shop selection
                            #===============================================
                            pos_categ = my_product.pos_categ_id
                            if pos_categ and pos_categ.shop_ids:
                                for shop in pos_categ.shop_ids:
                                    product_ids_shop.append(shop.id)
                        #=======================================
                        # End
                        #=======================================

                        #================================================
                        # To Sync Discount and Discount amount
                        #============================i====================
                            discount_amount = float(item['discount_amount'])
                            if float(item['discount_amount']):
                                discount_amount = float(
                                    item['discount_amount'])
                            else:
                                if parents.has_key(item['parent_item_id']):
                                    discount_amount = parents[item[
                                        'parent_item_id']]['discount_amount']
                            dis_percentage = float(item['discount_percent'])
                            if float(item['discount_percent']):
                                dis_percentage = float(
                                    item['discount_percent'])
                            else:
                                if parents.has_key(item['parent_item_id']):
                                    dis_percentage = parents[item[
                                        'parent_item_id']]['discount_percent']
                        #================================================
                        # End
                        #================================================

                            if item['tax_percent'] == '0.0000' and item[
                                    'parent_item_id']:
                                try:
                                    item['tax_percent'] = parents[
                                        item['parent_item_id']]['tax_percent']
                                except:
                                    item['tax_percent'] = '0.0000'
                            try:
                                if (item['tax_percent'] != '0.0000'):
                                    tax_id = self.pool.get(
                                        'magento.configuration').get_tax_id(
                                            cr, uid, item['tax_percent'])
                                    if (tax_id == 0):
                                        raise
                                    else:
                                        tax_ids = [[6, 0, [tax_id]]]
                                else:
                                    tax_ids = []
                            except:
                                tax_ids = []
                            erp_sales_order_line = {
                                'order_id': id_orders[0],
                                'product_id': product_id,
                                'name': item['name'],
                                'tax_id': tax_ids,
                                'price_unit': price,
                                'product_uom': my_product['uom_id']['id'],
                                'product_uom_qty': item['qty_ordered'],
                                'discount': dis_percentage,
                                'discount_amount': discount_amount,
                            }
                            #creating sale order line record in openerp
                            id_order_line = self.pool.get(
                                'sale.order.line').create(
                                    cr, uid, erp_sales_order_line)


###                                for shop checking in pos and storing in sale order
                        if product_ids_shop:
                            list1 = list(set(product_ids_shop))
                            if len(list1) == 1:
                                self.pool.get('sale.order').write(
                                    cr, uid, [id_orders[0]],
                                    {'shop_id': list1[0]})
                        #Shipping costs
                        try:
                            my_shipping = magento_configuration_object[
                                0].shipping_product.id
                            try:
                                if (header['shipping_tax_amount'] != '0.0000'):
                                    tax_percent = 100 * float(
                                        header['shipping_tax_amount']) / float(
                                            header['shipping_amount'])
                                    tax_id = self.pool.get(
                                        'magento.configuration').get_tax_id(
                                            cr, uid, tax_percent)
                                    if (tax_id == 0):
                                        raise
                                    else:
                                        tax_ids = [[6, 0, [tax_id]]]
                                else:
                                    tax_ids = []
                            except:
                                tax_ids = []
                            if (header['shipping_incl_tax'] != '0.0000'):
                                erp_ship_line = {
                                    'order_id':
                                    id_orders[0],
                                    'name':
                                    header['shipping_description'].replace(
                                        'Select Shipping Method',
                                        'Shipping Charges'),
                                    'price_unit':
                                    float(header['base_shipping_incl_tax']),
                                    'product_id':
                                    my_shipping,
                                    'tax_id':
                                    tax_ids,
                                    'product_uom_qty':
                                    1,
                                }
                                order_line = self.pool.get(
                                    'sale.order.line').create(
                                        cr, uid, erp_ship_line)
                        except:
                            pass
                        if missing_products_in_openerp:
                            continue
                    else:
                        pass
            #updating last imported time in openerp magneto object
            if magento_configuration_object[0].id:
                self.pool.get('magento.configuration').write(
                    cr, uid, [magento_configuration_object[0].id],
                    {'last_imported_invoice_timestamp': start_timestamp})
                server.endSession(session)
                return total_no_of_records
        server.endSession(session)
        return -1
    def import_orders(self, cr, uid):  #Customized Import Order Function
        total_no_of_records = 0  # Number of sale order imported
        start_timestamp = str(DateTime.utc())
        if True:
            # magneto object through which connecting openerp with defined magento configuration start
            start_timestamp = str(DateTime.utc())
            magento_configuration_object = self.pool.get(
                'magento.configuration').get_magento_configuration_object(
                    cr, uid)
            last_import = magento_configuration_object[
                0].last_imported_invoice_timestamp
            [status, server, session
             ] = self.pool.get('magento.configuration').magento_openerp_syn(
                 cr, uid)
            #checking server status
            if not status:
                raise osv.except_osv(
                    _('There is no connection!'),
                    _("There is no connection established with magento server\n\
                  please check the url,username and password"))
                server.endSession(session)
                return -1
            #end
            #API to fetch all sale order information###################################################
            increment = 1000
            index = 1
            while (True):
                stop = index + increment - 1
                if last_import:
                    listorder = server.call(session, 'sales_order.list', [{
                        'updated_at': {
                            'from': last_import
                        }
                    }])
                else:
                    listorder = server.call(session, 'sales_order.list', [{
                        'updated_at': {
                            'from': last_import
                        },
                        'order_id': {
                            'from': str(index),
                            'to': str(stop)
                        }
                    }])
                index = stop + 1
                all_increment_id = []
                all_customer_id = []
                for info_order in listorder:
                    if info_order['customer_id']:
                        all_customer_id.append(info_order['customer_id'])
                    all_increment_id.append(info_order['increment_id'])
                min = 0
                max_number_order_import = 20
                if magento_configuration_object[0].max_number_order_import:
                    max_number_order_import = int(
                        magento_configuration_object[0].max_number_order_import
                    )
                max = max_number_order_import
                length_ord = len(listorder)
                while length_ord > 0:
                    all_customer_id_max = all_customer_id[min:max]
                    all_increment_id_max = all_increment_id[min:max]
                    #                try:
                    #                   #API to get customer information for all customer_id at a time
                    info_customers = [
                        server.call(session, 'customapi_customer.itemslist',
                                    [all_customer_id_max])
                    ][0]
                    #                except:
                    #                   info_customers=[]

                    #                try:
                    #API to get sale order information for all increment_ids at a time
                    info_orders = [
                        server.call(session, 'customapi_order.itemslist',
                                    [all_increment_id_max])
                    ][0]
                    #                except:
                    #                   info_orders=[]

                    min = max
                    length_ord = length_ord - max_number_order_import
                    if length_ord < max_number_order_import:
                        max = min + length_ord
                    else:
                        max = max + max_number_order_import
                    for info_order in info_orders:
                        header = info_order['0']
                        #API to get sale order information based on increment_id
                        name_sales_order = str(header['increment_id'])
                        #searching sale order availability in openerp based on magneto_id or Order Reference
                        id_orders = self.pool.get('sale.order').search(
                            cr, uid, [
                                '|', ('magento_id', '=', header['order_id']),
                                ('name', '=', name_sales_order)
                            ])
                        if True:
                            #To get customer information for each sale order from list of info_customers
                            info_customer = [
                                customer for customer in info_customers
                                if header['customer_id'] ==
                                customer['customer_id']
                            ]
                            if info_customer:
                                info_customer = info_customer[0]
                            else:
                                info_customer = {'customer_id': '0'}
                            pricelist_ids = self.pool.get(
                                'product.pricelist').search(cr, uid, [])
                            if (header['customer_is_guest'] == '1'):
                                info_customer['store_id'] = header['store_id']
                                info_customer['website_id'] = '1'
                                info_customer['email'] = header[
                                    'customer_email']
                                info_customer['firstname'] = info_order[
                                    'billing_address']['firstname']
                                info_customer['lastname'] = info_order[
                                    'billing_address']['lastname']
                                info_customer['customer_is_guest'] = '1'
                            info_customer['shipping_address'] = info_order[
                                'shipping_address']
                            info_customer['billing_address'] = info_order[
                                'billing_address']
                            #getting billing and shipping address id from openerp
                            erp_customer_info = self.pool.get(
                                'magento.configuration').update_customer(
                                    cr, uid, info_customer)
                        if id_orders == []:
                            if header['status'] == 'canceled':
                                state = 'cancel'
                            else:
                                state = 'draft'

                            erp_sales_order = {
                                'name':
                                name_sales_order,
                                'date_order':
                                header['created_at'],
                                'state':
                                state,
                                'partner_id':
                                erp_customer_info['id'],
                                'partner_invoice_id':
                                erp_customer_info['billing_id'],
                                'partner_order_id':
                                erp_customer_info['billing_id'],
                                'partner_shipping_id':
                                erp_customer_info['shipping_id'],
                                'pricelist_id':
                                pricelist_ids[0],
                                'magento_id':
                                header['order_id'],
                                'magento_increment_id':
                                header['increment_id'],
                            }

                            if 'status_history' in info_order.keys() and (
                                    info_order['status_history']):
                                erp_sales_order['note'] = ''
                                for comment in info_order['status_history']:
                                    if comment['comment']:
                                        erp_sales_order['note'] += comment[
                                            'comment'] + '\n'
                            #creating sale order record in openerp
                            id_orders = [
                                self.pool.get('sale.order').create(
                                    cr, uid, erp_sales_order)
                            ]
                            if id_orders:
                                total_no_of_records += 1
                            missing_products_in_openerp = False
                            parents = {}
                            base_price = 0.0
                            #fetching sale order line information from magneto
                            for item in info_order['items']:
                                if item.has_key('product_type') and (
                                        item['product_type']
                                        in ['configurable', 'bundle']):
                                    parents[item['item_id']] = {
                                        'base_price': item['base_price'],
                                        'tax_percent': item['tax_percent'],
                                    }
                                    continue
                                #searching product availability in openerp for each sale order line
                                product_ids = self.pool.get(
                                    'product.product').search(
                                        cr, uid, [('magento_id', '=',
                                                   item['product_id'])])
                                if (product_ids == []):
                                    try:
                                        info_products = server.call(
                                            session,
                                            'catalog_product.itemslist',
                                            [item['product_id']])
                                    except:
                                        info_products = []
                                    missing_products_in_openerp = True
                                    continue
                                product_id = product_ids[0]
                                if base_price:
                                    price = base_price
                                else:
                                    price = item['base_price_incl_tax'] or item[
                                        'base_price']
                                if item.has_key('product_type') and item[
                                        'product_type'] and (
                                            item['product_type'] != 'simple'):
                                    price = 0.0
                                #making product object for each sale order line's product
                                my_product = self.pool.get(
                                    'product.product').browse(
                                        cr, uid, product_id)
                                try:
                                    if (item['tax_percent'] != '0.0000'):
                                        tax_id = self.pool.get(
                                            'magento.configuration'
                                        ).get_tax_id(cr, uid,
                                                     item['tax_percent'])
                                        if (tax_id == 0):
                                            raise
                                        else:
                                            tax_ids = [[6, 0, [tax_id]]]
                                    else:
                                        tax_ids = []
                                except:
                                    tax_ids = []
                                erp_sales_order_line = {
                                    'order_id': id_orders[0],
                                    'product_id': product_id,
                                    'name': my_product['name'],
                                    'tax_id': tax_ids,
                                    'price_unit': price,
                                    'product_uom': my_product['uom_id']['id'],
                                    'product_uom_qty': item['qty_ordered'],
                                }
                                #creating sale order line record in openerp
                                id_order_line = self.pool.get(
                                    'sale.order.line').create(
                                        cr, uid, erp_sales_order_line)
                            #Shipping costs
                            try:
                                my_shipping = magento_configuration_object[
                                    0].shipping_product.id
                                try:
                                    if (header['shipping_tax_amount'] !=
                                            '0.0000'):
                                        tax_percent = 100 * float(
                                            header['shipping_tax_amount']
                                        ) / float(header['shipping_amount'])
                                        tax_id = self.pool.get(
                                            'magento.configuration'
                                        ).get_tax_id(cr, uid, tax_percent)
                                        if (tax_id == 0):
                                            raise
                                        else:
                                            tax_ids = [[6, 0, [tax_id]]]
                                    else:
                                        tax_ids = []
                                except:
                                    tax_ids = []
                                if (header['shipping_incl_tax'] != '0.0000'):
                                    erp_ship_line = {
                                        'order_id':
                                        id_orders[0],
                                        'name':
                                        header['shipping_description'].replace(
                                            'Select Shipping Method',
                                            'Shipping Charges'),
                                        'price_unit':
                                        float(header['shipping_incl_tax']),
                                        'product_id':
                                        my_shipping,
                                        'tax_id':
                                        tax_ids,
                                        'product_uom_qty':
                                        1,
                                    }
                                    order_line = self.pool.get(
                                        'sale.order.line').create(
                                            cr, uid, erp_ship_line)
                            except:
                                pass
                            if missing_products_in_openerp:
                                continue
                        else:
                            pass
                cr.commit()
                if last_import or not listorder:
                    break
            #updating last imported time in openerp magneto object
            if magento_configuration_object[0].id:
                self.pool.get('magento.configuration').write(
                    cr, uid, [magento_configuration_object[0].id],
                    {'last_imported_invoice_timestamp': start_timestamp})
                server.endSession(session)
                return total_no_of_records
        server.endSession(session)
        return -1
示例#14
0
    def import_products(self, cr, uid,context=None):
        if context==None:
            context={}
        total_no_of_records=0
        start_timestamp = str(DateTime.utc())
        magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
        if magento_configuration_object==None:
              raise osv.except_osv(_('Import is in progress!'),_("Import Products is All ready Running ") )
        try:
            # magneto object through which connecting openerp with defined magneto configuration start
            magento_configuration_object = self.pool.get('magento.configuration').get_magento_configuration_object(cr, uid)
            last_import = magento_configuration_object[0].last_imported_product_timestamp # last imported time
            if magento_configuration_object[0].sync_status=='Running':
                 raise osv.except_osv(_('Import is in process!'),_("Import Products is All ready Running ") )
            [status, server, session] = self.pool.get('magento.configuration').magento_openerp_syn(cr, uid)
            if not status:
                server.endSession(session)
                return -1
            #end 
        except:
#            server.endSession(session)
            return -1
        self.pool.get('magento.configuration').write(cr, uid, [magento_configuration_object[0].id], {'sync_status':'Running'})
        increment = 30000
        index = 1
        max_number_product_import =30000 #max number import product per connection
        attribute_sets = server.call(session, 'product_attribute_set.list');
        while True:
              stop = index + increment - 1
              #fetching all information from magneto based on last imported time
              if last_import:
                  all_products = server.call(session, 'product.list',[{'updated_at': {'from': last_import}, 'product_id': {'from': str(index), 'to': str(stop)}}])
                  products = all_products
              else: 
                  all_products = server.call(session, 'product.list',[{'product_id': {'from': str(index), 'to': str(stop)}}]) 
                  products = all_products
              index = stop + 1
              all_product_id=[]
              for prod in products:
                    all_product_id.append(prod['product_id'])
              #Fetching Product,Based on min and max number from magneto (Due to Response error)
              print all_product_id
              min=0
              if magento_configuration_object[0].max_number_product_import:
                 max_number_product_import=int(magento_configuration_object[0].max_number_product_import)#In Openerp,Configured max number per connection for product 
              max=max_number_product_import
              length_prod=len(all_product_id)#length of all product in magneto   
              
              while length_prod>0:
                all_product_id_max=all_product_id[min:max]
            
                #API to get all products information from magneto 
                try:
                    info_products = server.call(session, 'customapi_product.itemslist',[all_product_id_max])
                except:
                    info_products=[]  
                #To modify min,max and total length of product start
                min=max
                length_prod=length_prod-max_number_product_import
                if length_prod<max_number_product_import:
                    max=min+length_prod
                else:
                    max=max+max_number_product_import
                #End
                for info_product in info_products:
                    try:
                        info_category=info_product
                        info_product=info_product['0']
                        tax_parcent=False
                        try:
                                tax_parcent = info_category['tax_percent']
                                tax_class_id = info_product['tax_class_id']
                                if tax_parcent:
                                        tax_id = self.pool.get('magento.configuration').get_tax_id(cr, uid, tax_parcent)
                                        if tax_class_id:
                                                 self.pool.get('account.tax').write(cr,uid,tax_id,{'magento_id':int(tax_class_id)})
                                        if (tax_id == 0):
                                                      raise  
                                        else:
                                                 tax_ids = [[6,0,[tax_id]]]   
                        except Exception,e:
                                    tax_ids = []   
                        product = { 'magento_id' : info_product['entity_id'],
                          'magento_name' : info_product['name'],
                          'name':info_product['name'],
                          'default_code' : info_product['sku'],
                          'modified' : False,
                          'type':'product',
                          'export_to_magento': True,
                           'taxes_id':tax_ids,
                           'magento_attr_id':info_product['attribute_set_id']
#                          'description':info_product['description'],
                        }
                        if 'openerp_name' in info_product.keys() and info_product['openerp_name']:
                            product['name']=info_product['openerp_name']
                        product['list_price'] = info_product['price']    
                        try:
                            product['weight'] = info_product['weight']
                        except:
                            product['weight'] = '0.00'
                        if info_product.has_key('type_id') and info_product['type_id'] =='bundle':
                           product['magento_pro_type'] = info_product['type_id']
                        if info_category.has_key('category_ids') and info_category['category_ids'] :
                            magento_cat_ids = info_category['category_ids']
                        elif info_category.has_key('categories') and info_category['categories']:
                            magento_cat_ids = info_category['categories']
                        else:
                            magento_cat_ids = []  
                        #searching category availability in openerp
                        if magento_cat_ids:
                            cat_ids = self.pool.get('product.category').search(cr, uid, [('magento_id', '=', magento_cat_ids[-1])])
                            if (cat_ids[0]):
                                product['categ_id'] = cat_ids[0]
                            else:
                                product['categ_id'] = magento_configuration_object[0].default_category.id    
                        else:
                            product['categ_id'] = magento_configuration_object[0].default_category.id    
                        #searching product availability in openerp
                        prod_ids = self.pool.get('product.product').search(cr, uid, [('magento_id', '=', product['magento_id'])])
                        #####image fetching for specific product###############################
                       # try:
                        img_list = server.call(session, 'catalog_product_attribute_media.list',[product['magento_id']])
                        
#                        except:
#                           img_list=[]  
                        ########End###########################################################
                        if prod_ids == []:
                            #inserting new product in openerp
                            product['magento_name']=product['name']
                            prod_ids = [self.pool.get('product.product').create(cr, uid, product)]
                            if prod_ids:
                               total_no_of_records+=1 #count number of imported records in openerp
                            #####Import image in openerp start#####################################
                            id1 = []   
                            for image in img_list:    
                                images_dict = {
                                               'name' : image['label'],
                                               'filename' : image['url'],
                                               'position' : image['position'],
                                               'exclude' : image['exclude'],
                                               'product_id' : prod_ids[0],
                                              # 'file' : image['file']
                                            }
                               
                                for type in image['types']:
                                    
                                    images_dict[type] = True
                                    if type == 'thumbnail':
                                            (filename, header) = urllib.urlretrieve(image['url'])
                                            f = open(filename , 'rb')
                                            img = base64.encodestring(f.read())
                                            f.close()
#                                            self.pool.get('product.product').write(cr,uid,prod_ids[0],{'image_medium' :img})
                                self.pool.get('product.images').create(cr, uid, images_dict)
                            
                            #self.pool.get('product.product').write(cr,uid,prod_ids[0],{'image_ids' :id1})
                            #End#######################################################################                      
                        else:
                            total_no_of_records+=1 
                            #updating product information in openerp
                            #Dantunes Requirement to dont update category#
                            if 'categ_id' in product.keys():
                                   del(product['categ_id'])
                            ##########End##########
                            if 'update' not in context.keys():
                                  self.pool.get('product.product').write(cr, uid, [prod_ids[0]], product)
                           
                            #####Import image in openerp start#######################################
                            for image in img_list:
                                images_dict = {
                                               'name' : image['label'] or 'test',
                                               'filename' : image['url'],
                                               'position' : image['position'],
                                               'exclude' : image['exclude'],
                                               'product_id' : prod_ids[0],
                                            }
                                for type in image['types']:
                                    images_dict[type] = True
                                    if type == 'thumbnail':
                                            (filename, header) = urllib.urlretrieve(image['url'])
                                            f = open(filename , 'rb')
                                            img = base64.encodestring(f.read())
                                            f.close()

                                #searching product image in openerp
                                prod_img_id = self.pool.get('product.images').search(cr, uid, [('product_id', '=', prod_ids[0]),('filename' ,'=',image['url'])])
                                if prod_img_id :
                                    #updating product image in openerp if image exist
                                    self.pool.get('product.images').write(cr, uid, [prod_img_id[0]],images_dict)
                                else: 
                                    #creating product image in openerp   
                                    self.pool.get('product.images').create(cr, uid, images_dict) 
                            #End####################################################################### 
                        if prod_ids == []:
                            return -1
                    except:
                        pass