Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

0

How to create invoice for My custom module

By
Odoo
on 10/23/14, 7:26 AM 1,582 views

from osv import osv,fields
import datetime
import time
from datetime import datetime
from datetime import timedelta


class daily_details(osv.osv):
    
    _name='daily.details'
    
    _columns={
              'daily_id':fields.many2one('lending.info','Name:'),
              'date':fields.date('Date',required=True),
              'amount_paid':fields.float('Paid',required=True),
              'amount_deducted':fields.float('Amount Deducted',required=True),
              'daily_interst_amount':fields.float('Daily Interest ',required=True),
              'fine_amount':fields.float('Fine',required=True),
#              'acc_id':fields.many2one('account.account','Account')
             
              }
daily_details()

class lending_info(osv.osv):
    
    _name='lending.info'
    _inherits = {'res.partner':'partner_id'}
   
    
    
    def _get_costt(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for fee in self.browse(cr, uid, ids, context=context):
                totalsum = 0.0
                for line in fee.daily_amount_details:
                    totalsum += line.amount_paid-(line.daily_interst_amount+line.fine_amount)
                res[fee.id] = totalsum
        return res
   
    
    _columns={
               'state':fields.selection([('draft','New'),
                                        ('pay','Paid'),
                                        ('closed','closed')],
              'State'),
              'loan_id':fields.char('ID',readonly=True),
              'partner_id':fields.many2one('res.partner','Customer'),
              'issue_date':fields.date('Issue Date',required=True),
              'due_date':fields.date('Due date',required=True),
              'total_amount':fields.float('Amount',size=64),
              'interest_rate':fields.float('Interst rate (%)'),
              'total_inter_amount':fields.float('Total Amount Pay ',readonly=True),
              'daily_amount_details':fields.one2many('daily.details','daily_id','Loan Line'),
#                'anali_account':fields.many2one('account.analytic.account','Analytic Account'),
               'proof_name':fields.char('Proof Id'),
               'proof_image':fields.binary('proof'),
               'other_inform':fields.text('Other Information'),
               'amount_subtotal':fields.function(_get_costt, type='float', string='Total',method=True,store=True),
               'balance':fields.float('Balance',readonly=True),
               
              
               
                         
              }
    _defaults={
                'loan_id': lambda obj, cr, uid, context: '/',
                'state':'draft',
                'issue_date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
              }
    def button_total(self, cr, uid, ids, context=None):

         data=self.read(cr, uid, ids, ['amount_subtotal','total_inter_amount'],context=context)
         
         total_amount_interst=data[0]['total_inter_amount']
         paid_amount=data[0]['amount_subtotal']
         
         balance_amount=total_amount_interst-paid_amount

                }
         self.write(cr, uid, ids,vals)
         return True
#     
    
    
    
    def create(self, cr, uid, vals, context=None):
        vals['loan_id'] = self.pool.get('ir.sequence').get(cr, uid,'lending.info')
        return super(lending_info, self).create(cr, uid, vals, context=context)
    
    def button_pay(self,cr,uid,ids,context=None):
        self.write(cr,uid,ids,{'state':'pay'})
        return True
    
    def button_closed(self,cr,uid,ids,context=None):
        self.write(cr,uid,ids,{'state':'closed'})
        return True
    
    
    
    def create_invoice(self, cr, uid, ids, context=None):
        ir_model_data = self.pool.get('ir.model.data')
        form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
        form_id = form_res and form_res[1] or False
        property_obj = self.pool.get('ir.property')
        #get account_id for invoice
        rec_pro_id = property_obj.search(cr,uid,[('name','=','property_account_receivable')])
        rec_line_data = property_obj.read(cr,uid,rec_pro_id,['name','value_reference'])
        account_id =  rec_line_data [0]['value_reference'].split(',')[1]
        # get sale account_id for invoice_line
        sale_pro_id = property_obj.search(cr,uid,[('name','=','property_account_income_categ')])
        sale_line_data = property_obj.read(cr,uid,sale_pro_id,['name','value_reference'])
        sale_account_id =  sale_line_data [0]['value_reference'].split(',')[1]
        #get data for invoice
        context['type'] = 'out_invoice'
        context['active_id'] = name_id
        invoice_pool = self.pool.get('account.invoice')
        default_fields = invoice_pool.fields_get(cr, uid, context=context)
        invoice_default = invoice_pool.default_get(cr, uid, default_fields, context=context)
        onchange_partner = invoice_pool.onchange_partner_id(cr, uid, [], type='out_invoice',\
                                partner_id=name_id)
        invoice_default.update(onchange_partner['value'])
        lines = []
        line_data = {'uos_id': False, 'product_id': False,
                 'price_unit': 0, 'account_id': sale_account_id,
                 'name': 'name',
                'account_analytic_id': your_account_id,
                 'invoice_line_tax_id': [[6, False, []]], 'quantity': 1}
        invoice_line= [0,False,line_data]
        lines.append(invoice_line)

        
        invoice_data = {
                        'partner_id': "name_id",
                        'date_invoice': time.strftime('%Y-%m-%d'),
                        'account_id': account_id,#determine the account for invoice 'account receivable'
                        'invoice_line': lines,
                        }
      
        invoice_default.update(invoice_data)
        invoice_id = invoice_pool.create(cr, uid, invoice_default, context=context)
        return {
            'name': _('Invoice'),
            'view_type': 'form',
            'res_id': invoice_id,
            'view_mode': 'form,tree',
            'res_model': 'account.invoice',
            'view_id': False,
            'views': [(form_id, 'form')],
            'context': context,
            'type': 'ir.actions.act_window',
        }
    
    def calc_total_amount(self,cr,uid,ids,context=None):

         num=self.read(cr,uid,ids,['total_amount','issue_date','due_date','interest_rate'],context=context)
         
         
         
         
         dateformat="%Y-%m-%d"
         interst_rate=num[0]['interest_rate']
         #d1=datetime.strptime(num[0]['maturity_date'],dateformat)
         #d2=datetime.strptime(num[0]['deposit_date'],dateformat)
         d1=datetime.strptime(num[0]['due_date'],dateformat)
         d2=datetime.strptime(num[0]['issue_date'],dateformat)
         v1=d1-d2
         total_days=v1.days
         var1=num[0]['total_amount']*interst_rate/100
         
#          interstrat_per_day=var1/365
         
         
# #         0
         vals={
               'total_inter_amount':num[0]['total_amount']+var1*total_days,
               #'processing_fee':['total_inter_amount']-num[0]['total_amount']
               #'interest_amount':interstrat_per_day*30,
               }
         self.write(cr,uid,ids,vals)
         return True
     
      
lending_info()

 

 


class res_partner_customer(osv.osv):
    
    _inherit='res.partner'
   
res_partner_customer()

 

.xml---------

<button name="create_invoice" string="Create Invoice"
                                type="object" icon="gtk-apply" states="confirm,waiting,in_consultation,done" class="oe_highlight" />   

 

0
sameer alhwety
On 11/19/14, 9:27 AM

create function seems like this (it works for me):

def create_invoice(self, cr, uid, ids, context=None):
        course = self.browse(cr,uid,ids[0])
        ir_model_data = self.pool.get('ir.model.data')
        form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
        form_id = form_res and form_res[1] or False
        property_obj = self.pool.get('ir.property')
        #get account_id for invoice
        rec_pro_id = property_obj.search(cr,uid,[('name','=','property_account_receivable')])
        rec_line_data = property_obj.read(cr,uid,rec_pro_id,['name','value_reference'])
        account_id =  rec_line_data [0]['value_reference'].split(',')[1]
        # get sale account_id for invoice_line
        sale_pro_id = property_obj.search(cr,uid,[('name','=','property_account_income_categ')])
        sale_line_data = property_obj.read(cr,uid,sale_pro_id,['name','value_reference'])
        sale_account_id =  sale_line_data [0]['value_reference'].split(',')[1]
        #get partner_id for invoice
        if course.student_id.parent_id:
            name_id = course.student_id.parent_id.id
        else:
            name_id = course.student_id.user_id.id
        
        #get data for invoice
        context['type'] = 'out_invoice'
        context['active_id'] = name_id
        invoice_pool = self.pool.get('account.invoice')
        default_fields = invoice_pool.fields_get(cr, uid, context=context)
        invoice_default = invoice_pool.default_get(cr, uid, default_fields, context=context)
        onchange_partner = invoice_pool.onchange_partner_id(cr, uid, [], type='out_invoice',\
                                partner_id=name_id)
        invoice_default.update(onchange_partner['value'])
        lines = []
        # get the invoice lines
        for cour in course.course_ids:
            line_data = {'uos_id': False, 'product_id': False,
                     'price_unit': cour.course_ids.price, 'account_id': sale_account_id, 
                     'name': cour.course_ids.name,
                     'discount': 0, 'account_analytic_id': cour.account_analytic_id.id, 
                     'invoice_line_tax_id': [[6, False, []]], 'quantity': 1}
            invoice_line= [0,False,line_data]
            lines.append(invoice_line)

        
        invoice_data = {
                        'partner_id': name_id,
                        'date_invoice': time.strftime('%Y-%m-%d'),
                        'account_id': account_id,#determine the account for invoice 'account receivable'
                        'invoice_line': lines,
                        'student_name': course.student_id.name,
                        'student_course_id': ids[0],
                        }
      
        invoice_default.update(invoice_data)
        invoice_id = invoice_pool.create(cr, uid, invoice_default, context=context)
        #connect invoice with Apply For Course 
        self.write(cr ,uid ,course.id ,{'invoice_id': invoice_id}, context=context)
        return {
            'name': _('Invoice'),
            'view_type': 'form',
            'res_id': invoice_id,
            'view_mode': 'form,tree',
            'res_model': 'account.invoice',
            'view_id': False,
            'views': [(form_id, 'form')],
            'context': context,
            'type': 'ir.actions.act_window',
        }

I GOT THIS ERROR--------NameError: global name 'name_id' is not defined

Odoo
on 11/19/14, 10:58 AM

what is this name_id

Odoo
on 11/19/14, 10:59 AM

Can you share full code ...

Odoo
on 11/19/14, 11:05 AM

I change the code as per ur suggestion but its not working how can I chnage my code

Odoo
on 11/19/14, 11:11 AM

Answer Updated , this the full code , hope that works for you

sameer alhwety
on 11/20/14, 2:27 AM

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

3 follower(s)

Stats

Asked: 10/23/14, 7:26 AM
Seen: 1582 times
Last updated: 3/16/15, 8:10 AM