← Back to team overview

savoirfairelinux-openerp team mailing list archive

[Merge] lp:~savoirfairelinux-openerp/openerp-isp/invoice_refactoring into lp:openerp-isp

 

Joao Alfredo Gama Batista has proposed merging lp:~savoirfairelinux-openerp/openerp-isp/invoice_refactoring into lp:openerp-isp.

Requested reviews:
  OpenERP ISP Core Editors (openerp-isp-core-editor)

For more details, see:
https://code.launchpad.net/~savoirfairelinux-openerp/openerp-isp/invoice_refactoring/+merge/226031

 * Split the big invoice routine into 3 separate methods.
 * Minor adjustments and code clean-up.
-- 
https://code.launchpad.net/~savoirfairelinux-openerp/openerp-isp/invoice_refactoring/+merge/226031
Your team Savoir-faire Linux' OpenERP is subscribed to branch lp:openerp-isp.
=== modified file 'contract_isp_invoice/contract.py'
--- contract_isp_invoice/contract.py	2014-01-20 04:25:39 +0000
+++ contract_isp_invoice/contract.py	2014-07-08 19:55:06 +0000
@@ -71,7 +71,7 @@
         'original_amount': fields.float(
             'Original Amount', digits_compute=dp.get_precision('Account'),
             required=True, readonly=True,
-            states={'draft':[('readonly',False)]}),
+            states={'draft':[('readonly', False)]}),
     }
 
     _defaults = {
@@ -216,30 +216,107 @@
         'close_date': fields.datetime.now
     }
 
+    def send_email_contract_invoice(self, cr, uid, ids, context=None):
+        context = context or {}
+
+        if not isinstance(ids, list):
+            ids = [ids]
+
+        mail_template_obj = self.pool.get('email.template')
+        ir_model_data_obj = self.pool.get('ir.model.data')
+        mail_template_id = ir_model_data_obj.get_object_reference(
+            cr, uid, 'account',
+            'email_template_edi_invoice')[1]
+        mail_mail_obj = self.pool.get('mail.mail')
+
+        for inv in ids:
+            _logger.info(
+                "Mailing invoice %s" % account_invoice_obj.browse(
+                    cr, uid, inv, context=context).name)
+
+            try:
+                mail_id = mail_template_obj.send_mail(
+                    cr, uid, mail_template_id, inv, context=ctx)
+                mail_message = mail_mail_obj.browse(
+                    cr, uid, mail_id,
+                    context=context).mail_message_id
+                mail_message.write({'type': 'email'})
+            except:
+                _logger.error(
+                    'Error generating mail for invoice %s:'
+                    '\n\n%s' % (
+                        account_invoice_obj.browse(
+                            cr, uid, inv, context=context).name,
+                        sys.exc_info()[0]))
+
+        return True
+
+    def _create_invoice(self, cr, uid, ids, context=None):
+        context = context or {}
+
+        data = {
+            'name': True,
+        }
+
+        if context.get('create_invoice_mode', 'contract') == 'reseller':
+            data.update({'partner': True})
+
+        res = []
+
+        account_analytic_line_obj = self.pool.get('account.analytic.line')
+        account_invoice_obj = self.pool.get('account.invoice')
+        account_invoice_line_obj = self.pool.get('account.invoice.line')
+        wf_service = netsvc.LocalService("workflow")
+
+        inv = account_analytic_line_obj.invoice_cost_create(
+            cr, uid, ids, data=data, context=context)
+        if isinstance(inv, list):
+            if len(inv) > 1:
+                # Merge invoices
+                query = [('invoice_id', 'in', inv)]
+                line_ids = account_invoice_line_obj.search(
+                    cr, uid, query, context=context)
+                account_invoice_line_obj.write(
+                    cr, uid, line_ids, {'invoice_id': inv[0]},
+                    context=context)
+                account_invoice_obj.button_compute(
+                    cr, uid, [inv[0]], context=context)
+                account_invoice_obj.unlink(cr, uid, inv[1:], context=context)
+
+            inv = inv[0]
+
+        res.append(inv)
+
+        # jgama - If its a prorata invoice, change the invoice date
+        #         according to the invoice_day variable
+        if context.get('prorata', False):
+            account_invoice_obj.write(
+                cr, uid, inv, {'date_invoice': context.get('date_invoice')},
+                context=context)
+
+        if context.get('not_subscription_voucher', True):
+            _logger.debug(
+                "Opening invoice %s" % account_invoice_obj.browse(
+                    cr, uid, inv, context=context).name)
+
+            wf_service.trg_validate(
+                uid, 'account.invoice', inv, 'invoice_open', cr)
+
+        return res
+
     def create_invoice(self, cr, uid, ids, prorata=False, context=None):
-        return_int = False
-        if isinstance(ids, int):
-            return_int = True
+        context = context or {}
+
+        if not isinstance(ids, list):
             ids = [ids]
 
         account_analytic_account_obj = self.pool.get('account.analytic.account')
-        account_analytic_line = self.pool.get('account.analytic.line')
-        contract_service_obj = self.pool.get('contract.service')
+        account_analytic_line_obj = self.pool.get('account.analytic.line')
         res_company_obj = self.pool.get('res.company')
-        account_invoice_obj = self.pool.get('account.invoice')
         res_company_data = res_company_obj.read(
             cr, uid,
             res_company_obj._company_default_get(cr, uid, context),
             context=context)
-        wf_service = netsvc.LocalService("workflow")
-
-        if res_company_data['send_email_contract_invoice']:
-            mail_template_obj = self.pool.get('email.template')
-            ir_model_data_obj = self.pool.get('ir.model.data')
-            mail_template_id = ir_model_data_obj.get_object_reference(
-                cr, uid, 'account',
-                'email_template_edi_invoice')[1]
-            mail_mail_obj = self.pool.get('mail.mail')
 
         cuttoff_day = res_company_data['cutoff_day']
 
@@ -257,87 +334,77 @@
             int(invoice_day)
         )
 
+        ctx = dict(context.copy(), prorata=prorata)
         if prorata:
             if datetime.date.today() <= cutoff_date:
-                date_invoice = invoice_date.strftime('%Y-%m-%d')
+                ctx.update(date_invoice=invoice_date.strftime('%Y-%m-%d'))
             else:
-                date_invoice = add_months(invoice_date, 1).strftime(
-                    '%Y-%m-%d')
-
-        ret = []
-        for contract_id in ids:
-            query = [('account_id', '=', contract_id),
+                ctx.update(
+                    date_invoice=add_months(invoice_date, 1).strftime(
+                        '%Y-%m-%d')
+                )
+
+        res = []
+
+        if context.get('create_invoice_mode', 'contract') != 'reseller':
+            for contract_id in ids:
+                query = [('account_id', '=', contract_id),
+                         ('to_invoice', '!=', False),
+                         ('invoice_id', '=', False),
+                         ('product_id', '!=', False),
+                         ('is_prorata', '=', prorata)]
+
+                ids_to_invoice = account_analytic_line_obj.search(
+                    cr, uid, query, context=context)
+
+                if ids_to_invoice:
+                    _logger.info(
+                        "Invoicing contract %s" %
+                        account_analytic_account_obj.browse(
+                            cr, uid, contract_id, context=context).name)
+
+                    inv = self._create_invoice(
+                        cr, uid, ids_to_invoice, context=ctx)
+
+                    if isinstance(inv, list):
+                        for i in inv:
+                            res.append(i)
+                    else:
+                        res.append(inv)
+
+                    if res_company_data['send_email_contract_invoice']:
+                        self.send_email_contract_invoice(
+                            cr, uid, inv, context=context)
+
+        else:
+            query = [('account_id', 'in', ids),
                      ('to_invoice', '!=', False),
                      ('invoice_id', '=', False),
                      ('product_id', '!=', False),
                      ('is_prorata', '=', prorata)]
 
-            ids_to_invoice = account_analytic_line.search(cr, uid, query,
-                                                          context=context)
+            ids_to_invoice = account_analytic_line_obj.search(
+                cr, uid, query, context=context)
             if ids_to_invoice:
                 _logger.info(
-                    "Invoicing contract %s" %
+                    "Invoicing partner %s" %
                     account_analytic_account_obj.browse(
-                        cr, uid, contract_id, context=context).name)
-
-                data = {
-                    'name': True,
-                }
-                inv = account_analytic_line.invoice_cost_create(
-                    cr, uid, ids_to_invoice, data=data, context=context)
+                        cr, uid, ids[0], context=context).partner_id.parent_id.name)
+
+                inv = self._create_invoice(
+                    cr, uid, ids_to_invoice, context=ctx)
+
                 if isinstance(inv, list):
                     for i in inv:
-                        ret.append(i)
-
+                        res.append(i)
                 else:
-                    ret.append(inv)
-
-                # jgama - If its a prorata invoice, change the invoice date
-                #         according to the invoice_day variable
-                if prorata:
-                    account_invoice_obj.write(
-                        cr, uid, inv, {'date_invoice': date_invoice},
-                        context=context)
-
-                if context.get('not_subscription_voucher', True):
-                    _logger.debug(
-                        "Opening invoice %s" % account_invoice_obj.browse(
-                            cr, uid, inv[0], context=context).name)
-
-                    wf_service.trg_validate(
-                        uid, 'account.invoice', inv[0], 'invoice_open', cr)
-                    #a = account_invoice_obj._workflow_signal(
-                    #    cr, uid, inv, 'invoice_open', context)
-
-                    if res_company_data['send_email_contract_invoice']:
-                        _logger.info(
-                            "Mailing invoice %s" % account_invoice_obj.browse(
-                                cr, uid, inv[0], context=context).name)
-
-                        ctx = dict(context, default_type='email')
-
-                        try:
-                            mail_id = mail_template_obj.send_mail(
-                                cr, uid, mail_template_id, inv[0], context=ctx)
-                            mail_message = mail_mail_obj.browse(
-                                cr, uid, mail_id,
-                                context=context).mail_message_id
-                            mail_message.write({'type': 'email'})
-                        except:
-                            _logger.error(
-                                'Error generating mail for invoice %s:'
-                                '\n\n%s' % (
-                                    account_invoice_obj.browse(
-                                        cr, uid, inv[0], context=context).name,
-                                    sys.exc_info()[0]))
-
-        if return_int:
-            if len(ret) == 0:
-                return None
-            else:
-                return ret[0]
-        else:
-            return ret
+                    res.append(inv)
+
+                if res_company_data['send_email_contract_invoice']:
+                    self.send_email_contract_invoice(
+                        cr, uid, inv, context=context)
+
+        return res
 
     def set_close(self, cr, uid, ids, context=None):
 
@@ -444,7 +511,8 @@
                 if (not partner) or not (account.pricelist_id):
                     raise orm.except_orm(
                         _('Analytic Account Incomplete!'),
-                        _('Contract incomplete. Please fill in the Customer and Pricelist fields.'))
+                        _('Contract incomplete. Please fill in the Customer '
+                          'and Pricelist fields.'))
 
                 date_due = False
                 if partner.property_payment_term:
@@ -569,6 +637,8 @@
                                 details.append("%s" % (line['unit_amount'], ))
                         if data.get('name', False):
                             details.append(line['name'])
+                        if data.get('partner', False):
+                            details.append(account.partner_id.name)
                         note.append(u' - '.join(
                             map(lambda x: unicode(x) or '', details)))
                     if note:
@@ -585,4 +655,3 @@
                 invoice_obj.button_reset_taxes(
                     cr, uid, [last_invoice], context)
         return invoices
-