Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make sure the invoice due date should contain due date,entered by user when there is no payment term defined in OpenERP/Odoo.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 623
    Comment on it

    If you want make sure the invoice due date should contain due date ,entered by user when there is no payment term defined in Odoo you have to customized .py file in account.invoice module.For example you can see below code .

    import itertools
    from lxml import etree
    from openerp import SUPERUSER_ID
    from openerp import models, fields, api, _
    from openerp.exceptions import except_orm, Warning, RedirectWarning
    import openerp.addons.decimal_precision as dp
    import time
    import math
    
    class account_invoice(models.Model): 
        _inherit = 'account.invoice'
    
        @api.one
        @api.depends('invoice_line.price_subtotal', 'tax_line.amount','discount',)
        def _compute_amount(self):
            self.amount_untaxed = (sum(line.price_subtotal for line in self.invoice_line))
            self.amount_tax = sum(line.amount for line in self.tax_line)
            self.amount_total = round(self.amount_untaxed + self.amount_tax) 
            if self.discount:
            	self.amount_total -= round((self.amount_untaxed + self.amount_tax)*self.discount/100)
            #self.discount = self.amount_untaxed * self.discount / 100 
    
        @api.model
        def line_get_convert(self, line, part, date):
            return {
                'date_maturity': line.get('date_maturity', False),
                'partner_id': part,
                'name': line['name'][:64],
                'date': date,
                'debit': line['price']>0 and line['price'],
                'credit': line['price']<0 and -line['price'],
                'account_id': line['account_id'],
                'analytic_lines': line.get('analytic_lines', []),
                'amount_currency': round(line['price']>0 and abs(round(line.get('amount_currency', False)))) or -abs(round(line.get('amount_currency', False))),
                'currency_id': line.get('currency_id', False),
                'tax_code_id': line.get('tax_code_id', False),
                'tax_amount': line.get('tax_amount', False),
                'ref': line.get('ref', False),
                'quantity': line.get('quantity',1.00),
                'product_id': line.get('product_id', False),
                'product_uom_id': line.get('uos_id', False),
                'analytic_account_id': line.get('account_analytic_id', False),
            }
            
            
        @api.one
        @api.depends(
            'state', 'currency_id', 'invoice_line.price_subtotal',
            'move_id.line_id.account_id.type',
            'move_id.line_id.amount_residual',
            # Fixes the fact that move_id.line_id.amount_residual, being not stored and old API, doesn't trigger recomputation
            'move_id.line_id.reconcile_id',
            'move_id.line_id.amount_residual_currency',
            'move_id.line_id.currency_id',
            'move_id.line_id.reconcile_partial_id.line_partial_ids.invoice.type',
        )
        # An invoice's residual amount is the sum of its unreconciled move lines and,
        # for partially reconciled move lines, their residual amount divided by the
        # number of times this reconciliation is used in an invoice (so we split
        # the residual amount between all invoice)
        def _compute_residual(self):
            self.residual = 0.0
            # Each partial reconciliation is considered only once for each invoice it appears into,
            # and its residual amount is divided by this number of invoices
            partial_reconciliations_done = []
            for line in self.sudo().move_id.line_id:
                if line.account_id.type not in ('receivable', 'payable'):
                    continue
                if line.reconcile_partial_id and line.reconcile_partial_id.id in partial_reconciliations_done:
                    continue
                # Get the correct line residual amount
                if line.currency_id == self.currency_id:
                    line_amount = line.amount_residual_currency if line.currency_id else line.amount_residual
                else:
                    from_currency = line.company_id.currency_id.with_context(date=line.date)
                    line_amount = from_currency.compute(line.amount_residual, self.currency_id)
                # For partially reconciled lines, split the residual amount
                if line.reconcile_partial_id:
                    partial_reconciliation_invoices = set()
                    for pline in line.reconcile_partial_id.line_partial_ids:
                        if pline.invoice and self.type == pline.invoice.type:
                            partial_reconciliation_invoices.update([pline.invoice.id])
                    line_amount = self.currency_id.round(line_amount / len(partial_reconciliation_invoices))
                    partial_reconciliations_done.append(line.reconcile_partial_id.id)
                self.residual += round(line_amount)
            self.residual = max(self.residual, 0.0)
    #          @@@@@@ Fields @@@@@@
        
        discount = fields.Float('Discount(%)', readonly=True, states={'draft': [('readonly', False)]})
        customer_code = fields.Char('Customer Code', readonly=True, states={'draft': [('readonly', False)]})
        total_cash = fields.Float('Total Paid (Cash)', readonly=True, states={'draft': [('readonly', False)]})
        total_cheque = fields.Float('Total Paid (Cheque)', readonly=True, states={'draft': [('readonly', False)]})
        check_amount = fields.Float('Cheque Amount', readonly=True, states={'draft': [('readonly', False)]})
        cheque_number = fields.Char('Cheque Number', readonly=True, states={'draft': [('readonly', False)]})
        bank = fields.Char('Bank', readonly=True, states={'draft': [('readonly', False)]})
        branch = fields.Char('Branch', readonly=True, states={'draft': [('readonly', False)]})
        balance_amount = fields.Float('Balance Amount', readonly=True, states={'draft': [('readonly', False)]})
        date_hijri  = fields.Date('Date Hijri', readonly=True, states={'draft': [('readonly', False)]})
        cheque = fields.Boolean('Pay By Cheque', readonly=True, states={'draft': [('readonly', False)]})
        chq_date = fields.Date('Cheque Date', readonly=True, states={'draft': [('readonly', False)]})
        new_name = fields.Char('Name', readonly=True, states={'draft': [('readonly', False)]})
        salesperson_code = fields.Char('Salesperson Code', readonly=True, states={'draft': [('readonly', False)]})
        card = fields.Boolean('Pay By Card')
        total_paid_by_card = fields.Float('Total Paid (Card)')
        card_number = fields.Char('Card Number')
        bank = fields.Char('Bank')
        expiry_date = fields.Date('Expiry Date')
        date_invoice = fields.Date(string='Invoice Date', readonly=False, states={'draft': [('readonly', False)]}, index=True,
            help="Keep empty to use the current date", copy=False)
           
    
        
        @api.multi
        def onchange_payment_term_date_invoice(self, payment_term_id, date_invoice):
            if not date_invoice:
                date_invoice = fields.Date.context_today(self)
            if not payment_term_id:
                # To make sure the invoice due date should contain due date which is
                # entered by user when there is no payment term defined
                return {'value': {'date_due': self.date_due or date_invoice}}
            pterm = self.env['account.payment.term'].browse(payment_term_id)
            pterm_list = pterm.compute(value=1, date_ref=date_invoice)[0]
            if pterm_list:
                return {'value': {'date_due': max(line[0] for line in pterm_list)}}
            else:
                raise except_orm(_('Insufficient Data!'),
                    _('The payment term of supplier does not have a payment term line.'))
        
        @api.multi
        def invoice_print(self):
            """ Print the invoice and mark it as sent, so that we can see more
                easily the next step of the workflow
            """
            assert len(self) == 1, 'This option should only be used for a single id at a time.'
            self.sent = True
            return self.env['report'].get_action(self, 'al_bander.report_invoices')
    
        @api.multi
        def payment_print(self):
            """ Print the invoice and mark it as sent, so that we can see more
                easily the next step of the workflow
            """
            assert len(self) == 1, 'This option should only be used for a single id at a time.'
            self.sent = True
            return self.env['report'].get_action(self, 'al_bander.payment_slip')
    
    
        @api.multi
        def invoice_pay(self):
            print "self",self
            ctx = dict(self._context)
            for rec in self:
                ctx['cheque_number'] = rec.cheque_number
                ctx['bank'] = rec.bank
                ctx['branch'] = rec.branch
                ctx['chq_date'] = rec.chq_date
                if rec.total_cash:
                    ctx['journal_type'] = 'cash'
                    ctx['amount'] = rec.total_cash
                    self.with_context(ctx).make_payment_of_invoice()
                if rec.total_cheque:
                    ctx['journal_type'] = 'bank'
                    ctx['amount'] = rec.total_cheque 
                    self.with_context(ctx).make_payment_of_invoice()
            return True
    
        def make_payment_of_invoice(self, cr, uid, ids, context):
    #         logger = netsvc.Logger()
             if not context:
                 context = {}
             ctx = context.copy()
             inv_obj = self.browse(cr,uid,ids[0])
             voucher_id = False
             invoice_number = inv_obj.number
             voucher_pool = self.pool.get('account.voucher')
             journal_pool = self.pool.get('account.journal')
             period_obj = self.pool.get('account.period')
             if ctx.get('journal_type',''):
                bank_journal_ids=  journal_pool.search(cr, uid, [('type', '=', context.get('journal_type'))])
             else:
                bank_journal_ids = journal_pool.search(cr, uid, [('type', '=', 'bank')])
             if not len(bank_journal_ids):
                 return True
             ctx.update({
                     'default_partner_id': inv_obj.partner_id.id,
                     'default_amount': inv_obj.amount_total,
                     'default_name':inv_obj.name,
                     'close_after_process': True,
                     'invoice_type':inv_obj.type,
                     'invoice_id':inv_obj.id,
                     'journal_id':bank_journal_ids[0],
                     'default_type': inv_obj.type in ('out_invoice','out_refund') and 'receipt' or 'payment'
             })
             if inv_obj.type in ('out_refund','in_refund'):
                 ctx.update({'default_amount':-inv_obj.amount_total})
             tax_id = self._get_tax(cr, uid, context)
    
             account_data = self.get_accounts(cr,uid,inv_obj.partner_id.id,bank_journal_ids[0])
             date = time.strftime('%Y-%m-%d')
             voucher_data = {
                     'period_id': inv_obj.period_id.id,
                     'account_id': account_data['value']['account_id'],
                     'partner_id': inv_obj.partner_id.id,
                     'journal_id':bank_journal_ids[0],
                     'currency_id': inv_obj.currency_id.id,
                     'reference': inv_obj.name,
                     'amount': ctx.get('amount',0.0),
                     'type':account_data['value']['type'],
                     'state': 'draft',
                     'pay_now': 'pay_later',
                     'name': '',
                     'cheque_number' : ctx.get('cheque_number',0.0),
                     'bank' : ctx.get('bank', ''),
                     'branch' : ctx.get('branch', ''),
                     'chq_date' : ctx.get('chq_date', time.strftime('%Y-%m-%d')),
                     'date': time.strftime('%Y-%m-%d'),
                     'company_id': self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=None),
                     'tax_id': tax_id,
                     'payment_option': 'without_writeoff',
                     'comment': _('Write-Off'),
                 }
             if inv_obj.type in ('out_refund','in_refund'):
                 voucher_data.update({'amount':-inv_obj.amount_total})
             if not voucher_data['period_id']:
                 period_ids = period_obj.find(cr, uid, inv_obj.date_invoice, context=context)
                 period_id = period_ids and period_ids[0] or False
                 voucher_data.update({'period_id':period_id})
    #         logger.notifyChannel("warning", netsvc.LOG_WARNING,"voucher_data '%s'." % voucher_data)
             voucher_id = voucher_pool.create(cr,uid,voucher_data)
    #         logger.notifyChannel("warning", netsvc.LOG_WARNING,"voucher_id '%s'." % voucher_id)
    
             if voucher_id:
                 #Get all the Documents for a Partner
                 if inv_obj.type in ('out_refund','in_refund'):
                     amount=-inv_obj.amount_total
                     res = voucher_pool.onchange_partner_id(cr, uid, [voucher_id], inv_obj.partner_id.id, bank_journal_ids[0], amount, inv_obj.currency_id.id, account_data['value']['type'], date, context=context)
                 else:
                     res = voucher_pool.onchange_partner_id(cr, uid, [voucher_id], inv_obj.partner_id.id, bank_journal_ids[0], inv_obj.amount_total, inv_obj.currency_id.id, account_data['value']['type'], date, context=context)
                 #Loop through each document and Pay only selected documents and create a single receipt
                 for line_data in res['value']['line_cr_ids']:
                     if line_data['name'] in [invoice_number]:
                         voucher_lines = {
                             'move_line_id': line_data['move_line_id'],
                             'amount': ctx.get('amount',0.0),
                             'name': line_data['name'],
                             'amount_unreconciled': line_data['amount_unreconciled'],
                             'type': line_data['type'],
                             'amount_original': line_data['amount_original'],
                             'account_id': line_data['account_id'],
                             'voucher_id': voucher_id,
                         }
    #                     logger.notifyChannel("warning", netsvc.LOG_WARNING,"voucher_lines '%s'." % voucher_lines)
                         voucher_line_id = self.pool.get('account.voucher.line').create(cr,uid,voucher_lines)
    #                     logger.notifyChannel("warning", netsvc.LOG_WARNING,"voucher_line_id '%s'." % voucher_line_id)
                 for line_data in res['value']['line_dr_ids']:
                     if line_data['name'] in [invoice_number]:
                         voucher_lines = {
                             'move_line_id': line_data['move_line_id'],
                             'amount': ctx.get('amount',0.0),
                             'name': line_data['name'],
                             'amount_unreconciled': line_data['amount_unreconciled'],
                             'type': line_data['type'],
                             'amount_original': line_data['amount_original'],
                             'account_id': line_data['account_id'],
                             'voucher_id': voucher_id,
                         }
    #                     logger.notifyChannel("warning", netsvc.LOG_WARNING,"voucher_lines '%s'." % voucher_lines)
                         voucher_line_id = self.pool.get('account.voucher.line').create(cr,uid,voucher_lines)
    #                     logger.notifyChannel("warning", netsvc.LOG_WARNING,"voucher_line_id '%s'." % voucher_line_id)
    
                 #Add Journal Entries
                 voucher_pool.action_move_line_create(cr,uid,[voucher_id])
    
             return voucher_id
    
    
        def get_accounts(self, cr, uid, partner_id=False, journal_id=False, context=None):
    
            """price
            Returns a dict that contains new values and context
    
            @param partner_id: latest value from user input for field partner_id
            @param args: other arguments
            @param context: context arguments, like lang, time zone
    
            @return: Returns a dict which contains new values, and context
            """
            default = {
                'value':{},
            }
            if not partner_id or not journal_id:
                return default
    
            partner_pool = self.pool.get('res.partner')
            journal_pool = self.pool.get('account.journal')
    
            journal = journal_pool.browse(cr, uid, journal_id, context=context)
            partner = partner_pool.browse(cr, uid, partner_id, context=context)
            account_id = False
            tr_type = False
            if journal.type in ('sale','sale_refund'):
                account_id = partner.property_account_receivable.id
                tr_type = 'sale'
            elif journal.type in ('purchase', 'purchase_refund','expense'):
                account_id = partner.property_account_payable.id
                tr_type = 'purchase'
            else:
                account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
                tr_type = 'receipt'
    
            default['value']['account_id'] = account_id
            default['value']['type'] = tr_type
    
            return default
    
        def _get_tax(self, cr, uid, context=None):
            if context is None: context = {}
            journal_pool = self.pool.get('account.journal')
            journal_id = context.get('journal_id', False)
            if not journal_id:
                ttype = context.get('type', 'bank')
                res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
                if not res:
                    return False
                journal_id = res[0]
    
            if not journal_id:
                return False
            journal = journal_pool.browse(cr, uid, journal_id, context=context)
            account_id = journal.default_credit_account_id or journal.default_debit_account_id
            if account_id and account_id.tax_ids:
                tax_id = account_id.tax_ids[0].id
                return tax_id
            return False
    
    
        def onchange_partner_id(self, cr, uid, ids, type, partner_id, date_invoice=False,
                payment_term=False, partner_bank_id=False, company_id=False, context=None):
            print "pssssssssss", partner_id
    
            partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
    
            res =  super(account_invoice, self).onchange_partner_id(cr, uid, ids, type, partner_id, date_invoice, payment_term, partner_bank_id, company_id, context=context) ['value']
            ref = partner.ref
            user_id = partner.user_id
            if ref and user_id:
                res.update({'customer_code': ref or False,
                        'user_id': user_id or False })
            return {'value': res}
    
    
    
    class account_invoice_line(models.Model):
        _inherit = 'account.invoice.line'
        
    
        qty_char = fields.Float('Qty in M. Sqr')
    
        @api.one
        @api.depends('price_unit', 'qty_char', 'discount', 'invoice_line_tax_id', 'quantity',
            'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id')
        def _compute_price(self):
            price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
            taxes = self.invoice_line_tax_id.compute_all(price, self.qty_char, product=self.product_id, partner=self.invoice_id.partner_id)
            self.price_subtotal = taxes['total']
            if self.invoice_id:
                self.price_subtotal = self.invoice_id.currency_id.round(self.price_subtotal)
    
    
        def on_change_qty_squ(self, cr, uid, ids, qty_char, product  , price_unit=0, discount=0, quantity=0, context=None):
            qty_char = qty_char
            product_obj = self.pool.get('product.product')
            product_obj = product_obj.browse(cr, uid, product, context=context)
            prod_type = product_obj.supp_ref
            squ_meter = product_obj.squ_meter
    
            price = price_unit
            value = {}
            if prod_type == 'T':
                if qty_char:
                    typ = float(qty_char)
                    qty = typ / squ_meter
                    round = math.ceil(qty)
                    new_qty = round * squ_meter
                    value['quantity'] = round
                subtotal = (quantity) * (discount)
                value['price_subtotal'] = subtotal
            elif prod_type == 'B':
                if qty_char:
                    typ = float(qty_char)
                    qty = typ / squ_meter
                    round = math.ceil(qty)
                    new_qty = round * squ_meter
                    value['quantity'] = round
                subtotal = (quantity) * (discount)
                value['price_subtotal'] = subtotal
            else:
                if qty_char:
                    typ= float(qty_char)
                    value['quantity'] = typ
                subtotal = (quantity) * (discount)
                value['price_subtotal'] = subtotal
                
            return {'value': value}
            
            
        def on_change_qty_squmeter(self, cr, uid, ids, product, qty_char=0,  price_unit=0, discount=0,quantity=0, context=None):
            
            quantity = quantity
            product_obj = self.pool.get('product.product')
            product_obj = product_obj.browse(cr, uid, product, context=context)
            prod_type = product_obj.supp_ref
    #	prod_price = product_obj.lst_price
            squ_meter = product_obj.squ_meter
    
            price = price_unit
            print "pleasssssssss", price
            value = {}
            if prod_type == 'T':
                if quantity:
                    print "plssssssssss", quantity
                    typ = float(quantity)
                    qty = typ * squ_meter
                    round = (qty)
                    new_qty = round / (squ_meter or 1.00 )
                    value['qty_char'] = round
                subtotal = (qty_char) * (discount)
                value['price_subtotal'] = subtotal
                
            else:
                if quantity:
                    typ = float(quantity)
                    qty = typ * squ_meter
                    round = (qty)
                    new_qty = round / (squ_meter or 1.00)
                    value['qty_char'] = round
                subtotal = (qty_char) * (discount)
                value['price_subtotal'] = subtotal
                
            return {'value': value}
    
           
       
        def product_id_change(self,cr,uid,ids, product ,uom_id,  qty=0, name='', type='out_invoice',
                partner_id=False, fposition_id=False, price_unit=False, currency_id=False,
                company_id=None,context=None):
            res = super(account_invoice_line, self).product_id_change(cr,uid,ids,product, uom_id, qty, name,type, partner_id, fposition_id,price_unit, currency_id,company_id,context)
            if res['value'].get('name', False):
                name = res['value'].get('name', False)
                name = name.split(" ")
                prod_name=name[0]
                prod_name=prod_name.replace("["," ")
                prod_name=prod_name.replace("]"," ")
                prod_name=prod_name.strip()
                result=res['value'] 
                product_obj=self.pool.get('product.product')
                var=product_obj.search(cr, uid, [('default_code', '=',prod_name)])
                product_obj1 = product_obj.browse(cr, uid, var, context=context)
                prod_type = product_obj1.supp_ref
                prod_price = product_obj1.lst_price
                squ_meter = product_obj1.squ_meter
                subtotal = (qty) * (prod_price)
                result['price_subtotal'] = subtotal
                result['qty_char'] = qty * squ_meter
                return {'value' : result}
    
            return res
    
            
        default={
        'discount':0.0,
        }
    
    account_invoice_line() 
    
    
    class account_move_line(models.Model):
        _inherit='account.move.line'
        
        def _amount_residual(self, cr, uid, ids, field_names, args, context=None):
            """
               This function returns the residual amount on a receivable or payable account.move.line.
               By default, it returns an amount in the currency of this journal entry (maybe different
               of the company currency), but if you pass 'residual_in_company_currency' = True in the
               context then the returned amount will be in company currency.
            """
            res = {}
            if context is None:
                context = {}
            cur_obj = self.pool.get('res.currency')
            for move_line in self.browse(cr, uid, ids, context=context):
                res[move_line.id] = {
                    'amount_residual': 0.0,
                    'amount_residual_currency': 0.0,
                }
    
                if move_line.reconcile_id:
                    continue
                if not move_line.account_id.reconcile:
                    #this function does not suport to be used on move lines not related to a reconcilable account
                    continue
    
                if move_line.currency_id:
                    move_line_total = move_line.amount_currency
                    sign = move_line.amount_currency < 0 and -1 or 1
                else:
                    move_line_total = move_line.debit - move_line.credit
                    sign = (move_line.debit - move_line.credit) < 0 and -1 or 1
                line_total_in_company_currency =  move_line.debit - move_line.credit
                context_unreconciled = context.copy()
                if move_line.reconcile_partial_id:
                    for payment_line in move_line.reconcile_partial_id.line_partial_ids:
                        if payment_line.id == move_line.id:
                            continue
                        if payment_line.currency_id and move_line.currency_id and payment_line.currency_id.id == move_line.currency_id.id:
                                move_line_total += payment_line.amount_currency
                        else:
                            if move_line.currency_id:
                                context_unreconciled.update({'date': payment_line.date})
                                amount_in_foreign_currency = cur_obj.compute(cr, uid, move_line.company_id.currency_id.id, move_line.currency_id.id, (payment_line.debit - payment_line.credit), round=False, context=context_unreconciled)
                                move_line_total += amount_in_foreign_currency
                            else:
                                move_line_total += (payment_line.debit - payment_line.credit)
                        line_total_in_company_currency += (payment_line.debit - payment_line.credit)
    
                result = round(move_line_total)
                res[move_line.id]['amount_residual_currency'] =  sign * (move_line.currency_id and self.pool.get('res.currency').round(cr, uid, move_line.currency_id, result) or result)
                res[move_line.id]['amount_residual'] = sign * line_total_in_company_currency
            return res   
        
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: