← Back to team overview

avanzosc team mailing list archive

Re: [Merge] lp:~mikelarregi/avanzosc/nayar_mysql_connect into lp:~avanzosc-security-team/avanzosc/72horas

 

Review: Needs Fixing code review

Hay varios comentarios inline.

Mikel, has mezclado varios cambios de módulos. Tienes que ser con eso más sistemático, porque si no, a la hora de hacer los MPs, se va a mezclar todo y no va a funcionar el merge. Un MP - una rama - un módulo. Las correciones, sobre esa misma rama, y no es necesario hacer un nuevo MP, simplemente comentar sobre el MP antiguo.

Un saludo.

Diff comments:

> === modified file 'dos_account_invoice_report/__init__.py'
> --- dos_account_invoice_report/__init__.py	2014-06-11 10:23:47 +0000
> +++ dos_account_invoice_report/__init__.py	2014-06-19 15:57:57 +0000
> @@ -1,5 +1,5 @@
>  ##############################################################################
> -#    
> +#
>  #    OpenERP, Open Source Management Solution
>  #    Copyright (C) 2004-2012 DOS (<http://www.dos-sl.es>).
>  #
> @@ -14,11 +14,10 @@
>  #    GNU Affero General Public License for more details.
>  #
>  #    You should have received a copy of the GNU Affero General Public License
> -#    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
> +#    along with this program.  If not, see <http://www.gnu.org/licenses/>
>  #
>  ##############################################################################
>  
> -import report
> +from . import report
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> -
> 
> === modified file 'dos_account_invoice_report/__openerp__.py'
> --- dos_account_invoice_report/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ dos_account_invoice_report/__openerp__.py	2014-06-19 15:57:57 +0000
> @@ -19,20 +19,18 @@
>  ##############################################################################
>  
>  {
> -	"name" : "DOS Account Invoice Report",
> -	"version" : "1.1",
> -	"author" : "DOS",
> -	"category" : "Enterprise Specific Modules",
> -	"description":"""Module to print account invoice with custom format.
> -	""",
> -	"depends" : ["account"],
> -	"init_xml" : [],
> -	"demo_xml" : [],
> -	"update_xml" : [
> -		'account_invoice_report.xml',
> -	],
> -	"website": 'http://www.dos-sl.es',
> -	"active": False,
> -	"installable": True,
> +    "name": "DOS Account Invoice Report",
> +    "version": "1.1",
> +    "author": "DOS",
> +    "category": "Enterprise Specific Modules",
> +    "description": """Module to print account invoice with custom format.
> +    """,
> +    "depends": ["account"],
> +    "demo": [],
> +    "data": [
> +        'views/account_invoice_report.xml',
> +    ],
> +    "website": 'http://www.dos-sl.es',
> +    "installable": True,
>  }
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === removed file 'dos_account_invoice_report/account_invoice_report.xml'
> --- dos_account_invoice_report/account_invoice_report.xml	2014-06-11 10:23:47 +0000
> +++ dos_account_invoice_report/account_invoice_report.xml	1970-01-01 00:00:00 +0000
> @@ -1,50 +0,0 @@
> -<?xml version="1.0"?>
> -<openerp>
> -  <data>
> -    <report id="account_invoice_custom_report"
> -	    string="Invoice 72horas"
> -	    model="account.invoice"
> -	    name="account.invoice.custom"
> -	    rml="dos_account_invoice_report/report/account_invoice.rml"
> -	    attachment="(object.state in ('open','paid')) and ((object.number or '').replace('/','') + '.pdf')"
> -	    attachment_use="1"
> -	    header="False"
> -	    auto="False"
> -	    />
> -
> -    <report id="account_invoice_preprinted_report"
> -	    string="Invoice Preprinted 72horas"
> -	    model="account.invoice"
> -	    name="account.invoice.preprinted"
> -	    rml="dos_account_invoice_report/report/account_invoice.rml"
> -	    attachment="(object.state in ('open','paid')) and ((object.number or '').replace('/','') + '.pdf')"
> -	    attachment_use="1"
> -	    header="False"
> -	    auto="False"
> -	    />
> -
> -    <report id="account_invoice_nayar_report"
> -	    string="Invoice Nayar Systems"
> -	    model="account.invoice"
> -	    name="account.invoice.nayar"
> -	    rml="dos_account_invoice_report/report/account_invoice.rml"
> -	    attachment="(object.state in ('open','paid')) and ((object.number or '').replace('/','') + '.pdf')"
> -	    attachment_use="1"
> -	    header="False"
> -	    auto="False"
> -	    />
> -
> -    <record id="view_invoice_report_inherit_account" model="ir.ui.view">
> -      <field name="name">stock.invoice.report.form</field>
> -      <field name="type">form</field>
> -      <field name="model">account.invoice</field>
> -      <field name="inherit_id" ref="account.invoice_form"/>
> -      <field name="arch" type="xml">
> -	<xpath expr="/form/notebook/page[@string='Invoice']/group/group/button[@string='Print Invoice']" position="replace">
> -	  <button name="%(account_invoice_custom_report)d" string="Print Invoice" type="action" icon="gtk-print" states="open,paid,proforma,sale,proforma2"/>
> -	</xpath>
> -      </field>
> -    </record>
> -
> -  </data>
> -</openerp>
> 
> === modified file 'dos_account_invoice_report/report/account_invoice.py'
> --- dos_account_invoice_report/report/account_invoice.py	2014-06-11 10:23:47 +0000
> +++ dos_account_invoice_report/report/account_invoice.py	2014-06-19 15:57:57 +0000
> @@ -22,15 +22,16 @@
>  import time
>  from datetime import datetime
>  from dateutil.relativedelta import relativedelta
> -from report import report_sxw
> -from osv import osv
> -from tools.bank import format_acc_number
> -from tools.translate import _
> -import pooler
> -
> -class account_invoice_custom(report_sxw.rml_parse):
> +from openerp.report import report_sxw
> +from openerp.osv import orm
> +from openerp.tools.bank import format_acc_number
> +from openerp.tools.translate import _
> +
> +
> +class AccountInvoiceCustom(report_sxw.rml_parse):
>      def __init__(self, cr, uid, name, context):
> -        super(account_invoice_custom, self).__init__(cr, uid, name, context=context)
> +        super(AccountInvoiceCustom,
> +              self).__init__(cr, uid, name, context=context)
>          self.localcontext.update({
>              'time': time,
>              'get_left_text': self.get_left_text,
> @@ -56,444 +57,432 @@
>              'get_lines_per_page': self.get_lines_per_page,
>          })
>          self.context = context
> -        user = self.pool.get('res.users').browse(cr, uid, uid)
> +        user = self.pool['res.users'].browse(cr, uid, uid, context=context)
>          self.company = user.company_id
> -        
> -    def get_invoice_date (self, invoice):
> +
> +    def get_invoice_date(self, invoice):
>          invoice_date = ""
> -        
>          if str(invoice.date_invoice) != '':
>              invoice_date = datetime.strptime(invoice.date_invoice, '%Y-%m-%d')
>              invoice_date = invoice_date.strftime('%d/%m/%Y')
> -            
>          return invoice_date
> -    
> +
>      def get_invoice_refund(self, invoice):
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              number = '-'
>              str_date = '-'
> -            if len(invoice.origin_invoices_ids) > 0:
> -                number =len(invoice.origin_invoices_ids) > 0 and invoice.origin_invoices_ids[0].number or '-'
> +            if invoice.origin_invoices_ids:
> +                number = (invoice.origin_invoices_ids and
> +                          invoice.origin_invoices_ids[0].number or '-')
>                  if str(invoice.origin_invoices_ids[0].date_invoice) != '':
> -                    invoice_date = datetime.strptime(invoice.origin_invoices_ids[0].date_invoice, '%Y-%m-%d')
> -                    str_date = invoice_date.strftime('%d-%m-%Y')        
> -                
> +                    date_inv = invoice.origin_invoices_ids[0].date_invoice
> +                    invoice_date = datetime.strptime(date_inv, '%Y-%m-%d')
> +                    str_date = invoice_date.strftime('%d-%m-%Y')
>              return number + ' (' + str_date + ')'
>          else:
>              return None
> -        
> +
>      def get_left_text(self, invoice):
> -        
>          text = ""
> -        
>          company = invoice.company_id or self.company or None
> -        
>          if company and company.partner_id:
> -            
>              partner = company.partner_id
> -
>              # Nombre empresa
> -            #text += partner.name or ""
> +            # text += partner.name or ""
>              # CIF
> -            #text += partner.vat and (" - " + partner.vat) or ""
> +            # text += partner.vat and (" - " + partner.vat) or ""
>              # Tomo
> -            text += partner.es_tomo and ("" + _("RM Tomo") + " " + partner.es_tomo) or ""
> +            text += partner.es_tomo and ("" + _("RM Tomo") + " " +
> +                                         partner.es_tomo) or ""
>              # Libro
> -            text += partner.es_libro and (" " + _("Libro") + " " + partner.es_libro) or ""
> +            text += partner.es_libro and (" " + _("Libro") + " " +
> +                                          partner.es_libro) or ""
>              # Folio
> -            text += partner.es_folio and (" " + _("Folio") + " " + partner.es_folio) or ""    
> +            text += partner.es_folio and (" " + _("Folio") + " " +
> +                                          partner.es_folio) or ""
>              # Hoja
> -            text += partner.es_hoja and (" " + _("Hoja") + " " + partner.es_hoja) or ""    
> +            text += partner.es_hoja and (" " + _("Hoja") +
> +                                         " " + partner.es_hoja) or ""
>              # Inscripcion
> -            text += partner.es_registro_mercantil and (" " + _("Inscripción") + " " + partner.es_registro_mercantil) or ""    
> +            reg_merc = partner.es_registro_mercantil
> +            text += partner.es_registro_mercantil and (" " + _("Inscripción") +
> +                                                       " " + reg_merc) or ""
>              # Final
> -            text += "."        
> +            text += "."
>  
>          return text
>  
>      def get_partner_name(self, invoice):
> -                
>          text = ""
>          company = invoice.company_id or self.company or None
> -        
>          if company and company.partner_id:
> -            
>              partner = company.partner_id
> -
>              # Nombre empresa
>              text += partner.name or ""
>              # CIF
>              text += partner.vat and (" - " + partner.vat) or ""
>              return text
> -         
> -    
> -    def get_footer_text(self, invoice):
> -        
> +
> +    def get_footer_text(self, invoice, context=None):
>          text = ""
> -        
>          company = invoice.company_id or self.company or None
> -        
>          if company and company.partner_id:
> -            
> +            partner_obj = self.pool['res.partner']
> +            addr_obj = self.pool['res.partner']

No se utiliza.

>              partner = company.partner_id
> -            addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> -            addr_id = addr_ids['default']
> -            addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> -            
>              # Nombre empresa
> -            #text += partner and partner.name or ""
> +            # text += partner and partner.name or ""
>              # Calle empresa
> -            text += addr and addr.street and ("" + addr.street + ".") or ""
> -            # Codigo Postal empresa
> -            text += addr and addr.zip and (" - " + addr.zip) or ""
> -            # Ciudad
> -            text += addr and addr.city and (" " + addr.city) or ""
> -            # Telefono
> -            text += addr and addr.phone and (" - " + _("Tel.") + " " + addr.phone) or ""
> -            # Fax
> -            text += addr and addr.fax and (" - " + _("Fax.") + " " + addr.fax) or ""
> -            # Email
> -            text += addr and addr.email and (" - " + _("E-Mail") + " " + addr.email) or ""
> -            
> +            if partner:

No hace falta comprobarlo. Ya lo haces arriba.

> +                text += partner.street and ("" + addr.street + ".") or ""
> +                # Codigo Postal empresa
> +                text += partner.zip and (" - " + addr.zip) or ""
> +                # Ciudad
> +                text += partner.city and (" " + addr.city) or ""
> +                # Telefono
> +                text += partner.phone and (" - " + _("Tel.") +
> +                                           " " + addr.phone) or ""
> +                # Fax
> +                text += partner.fax and (" - " + _("Fax.") + " " +
> +                                         addr.fax) or ""
> +                # Email
> +                text += addr and addr.email and (" - " + _("E-Mail") +
> +                                                 " " + addr.email) or ""
>          return text
> -         
> -    def get_company_address (self, invoice):
> -        
> +
> +    def get_company_address(self, invoice, context=None):
>          res = []
> -        
>          company = invoice.company_id or self.company or None
> -        
>          if company and company.partner_id:
> -            
>              partner = company.partner_id
> -            addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> -            addr_id = addr_ids['default']
> -            addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> -            
> -            res.append(partner and partner.name or "")
> -            res.append((addr and addr.street) or '')
> -            res.append((addr and addr.zip or '') + " - " + (addr and addr.city or ''))
> -            res.append((addr and addr.state_id and addr.state_id.name or '') + " (" + (addr and addr.country_id and addr.country_id.name or '') + ")")
> -            res.append(partner and partner.vat or '')
> -            
> +            if partner:

No hace falta comprobarlo. Ya lo estás comprobando arriba.

> +                res.append(partner.name or "")
> +                res.append((partner.street) or '')
> +                res.append((partner.zip or '') + " - " +
> +                           (partner.city or ''))
> +                res.append((partner.state_id and partner.state_id.name or '') +
> +                           " (" + (partner.country_id and
> +                                   partner.country_id.name or '') + ")")
> +                res.append(partner.vat or '')
>          else:
> -            
> -            res.append(" ")
> -            res.append(" ")
> -            res.append(" ")
> -            res.append(" ")
> -            res.append(" ")
> -
> +            for i in range(5):
> +                res.append(" ")
>          return res
> -    
> -    def get_customer_address (self, invoice):
> -        
> +
> +    def get_customer_address(self, invoice, context=None):
>          res = []
> -        
>          partner = invoice.partner_id
> -        addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> +        partner_obj = self.pool['res.partner']
> +        addr_obj = self.pool['res.partner']

No declares algo repetido.

> +        addr_ids = partner_obj.address_get(self.cr, self.uid,
> +                                           [partner.id], ['default'])
>          addr_id = addr_ids['default']
> -        addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> -        
> +        addr = addr_obj.browse(self.cr, self.uid, addr_id, context=context)

Utiliza partner_obj

>          res.append((addr and addr.street) or '')
> -        res.append((addr and addr.zip or '') + " - " + (addr and addr.city or ''))
> -        res.append((addr and addr.state_id and addr.state_id.name or '') + " (" + (addr and addr.country_id and addr.country_id.name or '') + ")")
> +        res.append((addr and addr.zip or '') + " - " +
> +                   (addr and addr.city or ''))
> +        res.append((addr and addr.state_id and addr.state_id.name or '') +
> +                   " (" + (addr and addr.country_id and
> +                           addr.country_id.name or '') + ")")
> +        return res
>  
> -        return res
> -    
> -    def get_elevator_address (self, invoice):
> -        
> +    def get_elevator_address(self, invoice, context=None):
>          res = []
> -        
>          if invoice.elevator_partner_id:
> -            
>              partner = invoice.elevator_partner_id
> -            addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> -            addr_id = addr_ids['default']
> -            addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> -            
> -            res.append(partner and partner.name or "")
> -            res.append((addr and addr.street) or '')
> -            res.append((addr and addr.zip or '') + " - " + (addr and addr.city or ''))
> -            res.append((addr and addr.state_id and addr.state_id.name or '') + " (" + (addr and addr.country_id and addr.country_id.name or '') + ")")
> -            res.append(partner and partner.vat or '')
> -        
> +            if partner:

No hace falta este if

> +                res.append(partner.name or "")
> +                res.append((partner.street) or '')
> +                res.append((partner.zip or '') + " - " +
> +                           (partner.city or ''))
> +                res.append((partner.state_id and partner.state_id.name or '') +
> +                           " (" + (partner.country_id and
> +                                   partner.country_id.name or '') + ")")
> +                res.append(partner.vat or '')
>          elif invoice.partner_id:
> -            
>              partner = invoice.partner_id
>              addr = invoice.address_invoice_id
> -            
>              res.append(partner and partner.name or "")
>              res.append((addr and addr.street) or '')
> -            res.append((addr and addr.zip or '') + " - " + (addr and addr.city or ''))
> -            res.append((addr and addr.state_id and addr.state_id.name or '') + " (" + (addr and addr.country_id and addr.country_id.name or '') + ")")
> +            res.append((addr and addr.zip or '') + " - " +
> +                       (addr and addr.city or ''))
> +            res.append((addr and addr.state_id and addr.state_id.name or '') +
> +                       " (" + (addr and addr.country_id and
> +                               addr.country_id.name or '') + ")")
>              res.append(partner and partner.vat or '')
> -                     
>          else:
> -            
> -            res.append(" ")
> -            res.append(" ")
> -            res.append(" ")
> -            res.append(" ")
> -            res.append(" ")
> -        
> +            for i in range(5):
> +                res.append(" ")
>          return res
> -        
> -        
> +
>      def get_payment_type(self, invoice):
> -
>          return invoice.payment_type and invoice.payment_type.name.upper() or ''
> -    
> -        
> +
>      def get_payment_term(self, invoice):
> -        
>          if invoice.date_due:
>              date_due = datetime.strptime(invoice.date_due, '%Y-%m-%d')
>              str_date = date_due.strftime('%d/%m/%Y')
>          else:
>              date_invoice = datetime.strptime(invoice.date_invoice, '%Y-%m-%d')
> -            str_date = date_invoice.strftime('%d/%m/%Y')            
> -
> +            str_date = date_invoice.strftime('%d/%m/%Y')
>          return str_date
>  
> -
> -    def get_account_number(self, invoice):
> -    
> +    def get_account_number(self, invoice, context=None):
>          bank_text = ""
> -        
> -        if invoice.payment_type and invoice.payment_type.code in ('TRANSF', 'T/T', 'TRANSFERENCIA_CSB', 'CNF'):
> -            
> -            if invoice.type in ("in_invoice", "out_invoice"):
> -                
> -                # Cuenta bancaria de la empresa
> -                if self.company.partner_id:
> -                    partner_id = self.company.partner_id.id
> -                    
> -                    pool = pooler.get_pool(self.cr.dbname)
> -                    bank_obj = pool.get('res.partner.bank')
> -                    bank_ids = bank_obj.search(self.cr, self.uid, [('partner_id','=', partner_id)], limit=1, order='default_bank desc')
> -                    
> -                    for bank in bank_obj.browse(self.cr, self.uid, bank_ids):
> -                        bank_text = format_acc_number(bank.iban or bank.acc_number or "")
> -
> -            else: # ("out_refund", "in_refund")    
> -                
> -                # Cuenta bancaria del cliente
> -                if invoice.partner_bank_id:
> -                    bank_text = format_acc_number(invoice.partner_bank_id.iban or invoice.partner_bank_id.acc_number or "", masked=True)
> -                                
> -        elif invoice.payment_type and invoice.payment_type.code in ('RECIBO', 'RECIBO_CSB', 'pain.008.001.02'):
> -            if invoice.type in ("in_invoice", "out_invoice"):
> -                # Cuenta bancaria del cliente
> -                if invoice.partner_bank_id:
> -                    bank_text = format_acc_number(invoice.partner_bank_id.iban or invoice.partner_bank_id.acc_number or "", masked=True)
> -            else: # ("out_refund", "in_refund")    
> -                
> -                # Cuenta bancaria de la empresa
> -                if self.company.partner_id:
> -                    partner_id = self.company.partner_id.id
> -                    
> -                    pool = pooler.get_pool(self.cr.dbname)
> -                    bank_obj = pool.get('res.partner.bank')
> -                    bank_ids = bank_obj.search(self.cr, self.uid, [('partner_id','=', partner_id)], limit=1, order='default_bank desc')
> -                    
> -                    for bank in bank_obj.browse(self.cr, self.uid, bank_ids):
> -                        bank_text = format_acc_number(bank.iban or bank.acc_number or "")
> -
> +        pay_type('TRANSF', 'T/T', 'TRANSFERENCIA_CSB', 'CNF')
> +        if invoice.payment_type and invoice.payment_type.code in pay_type:
> +            if invoice.type in ("in_invoice", "out_invoice"):
> +                # Cuenta bancaria de la empresa
> +                if self.company.partner_id:
> +                    partner_id = self.company.partner_id.id
> +                    pool = pooler.get_pool(self.cr.dbname)

No hace falta obtener el pool de esta forma. Tienes self.pool.

> +                    bank_obj = pool.get('res.partner.bank')

Utiliza self.pool[]

> +                    bank_ids = bank_obj.search(self.cr, self.uid,
> +                                               [('partner_id', '=',
> +                                                 partner_id)],
> +                                               limit=1,
> +                                               order='default_bank desc',
> +                                               context=context)
> +                    for bank in bank_obj.browse(self.cr, self.uid, bank_ids,
> +                                                context=context):
> +                        bank_text = format_acc_number(bank.iban or
> +                                                      bank.acc_number or "")
> +            else:  # ("out_refund", "in_refund")
> +                # Cuenta bancaria del cliente
> +                if invoice.partner_bank_id:
> +                    acc_number = invoice.partner_bank_id.acc_number
> +                    bank_text = format_acc_number(invoice.partner_bank_id.iban
> +                                                  or acc_number or "",
> +                                                  masked=True)
> +        elif (invoice.payment_type and
> +              invoice.payment_type.code in

Esta indentación debería ser mayor.

> +              ('RECIBO', 'RECIBO_CSB', 'pain.008.001.02')):
> +            if invoice.type in ("in_invoice", "out_invoice"):
> +                # Cuenta bancaria del cliente
> +                if invoice.partner_bank_id:
> +                    acc_number = invoice.partner_bank_id.acc_number
> +                    bank_text = format_acc_number(invoice.partner_bank_id.iban
> +                                                  or acc_number or "",
> +                                                  masked=True)
> +            else:  # ("out_refund", "in_refund")
> +                # Cuenta bancaria de la empresa
> +                if self.company.partner_id:
> +                    partner_id = self.company.partner_id.id
> +                    bank_obj = self.pool['res.partner.bank']
> +                    bank_ids = bank_obj.search(self.cr, self.uid,
> +                                               [('partner_id', '=',
> +                                                 partner_id)], limit=1,
> +                                               order='default_bank desc',
> +                                               context=context)
> +                    for bank in bank_obj.browse(self.cr, self.uid, bank_ids,
> +                                                context=context):
> +                        bank_text = format_acc_number(bank.iban or
> +                                                      bank.acc_number or "")
>          return bank_text
>  
> -                        
>      def get_invoice_lines(self, invoice):
> -        product_obj = self.pool.get('product.product')
> -        
> +        product_obj = self.pool['product.product']
>          res = []
> -        
>          contracts = {}
>          links = {}
>          shippings = {}
>          others = {}
> -
>          max_lines_first, max_lines = self.get_lines_per_page()
> -        
>          sign = 1.0
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              sign = -1.0
> -        
>          count = 0
> -
>          for l in invoice.invoice_line:
>              # Lineas de teléfono
> -            if l.contract_id and l.product_id and product_obj._is_sim(l.product_id.categ_id):
> +            if (l.contract_id and l.product_id and
> +                    product_obj._is_sim(l.product_id.categ_id)):

Indentación mayor (la segunda línea de los if debe ser así siempre)

>                  if l.contract_id.id in contracts:
> -                    contracts[l.contract_id.id]['uds'] = contracts[l.contract_id.id]['uds'] + int(l.quantity or 0)
> -                    contracts[l.contract_id.id]['price'] = contracts[l.contract_id.id]['price'] + (l.price_subtotal or 0)
> +                    contracts_uds = contracts[l.contract_id.id]['uds']
> +                    contracts_price = contracts[l.contract_id.id]['price']
> +                    contracts[l.contract_id.id]['uds'] = (contracts_uds +

En lugar de tener que guardar el valor y después sumar, vale simplemente contracts[l.contract_id.id]['uds'] += int(l.quantity or 0))

> +                                                          int(l.quantity or 0))
> +                    contracts[l.contract_id.id]['price'] = (contracts_price +

Ídem

> +                                                            (l.price_subtotal
> +                                                             or 0))
>                  else:
> -                    contracts[l.contract_id.id] = {'uds': int(l.quantity or 0), 
> -                                                   'price': l.price_subtotal or 0,
> -                                                   'ref': l.contract_id.ref or "", 
> -                                                   'type': l.contract_id and l.contract_id.contract_type_id and l.contract_id.contract_type_id.name or " - "}
> -
> +                    uds = int(l.quantity or 0)
> +                    price = l.price_subtotal or 0
> +                    ref = l.contract_id.ref or ""
> +                    type = (l.contract_id and l.contract_id.contract_type_id
> +                            and l.contract_id.contract_type_id.name or " - ")
> +                    contracts[l.contract_id.id] = {'uds': uds,
> +                                                   'price': price,
> +                                                   'ref': ref,
> +                                                   'type': type,
> +                                                   }
>              # Gastos de envío
> -            elif l.product_id and product_obj._is_shipping_cost(l.product_id.categ_id):
> -                if l.product_id.id in shippings and shippings[l.product_id.id]['price'] == (l.price_unit or 0) and shippings[l.product_id.id]['dto'] == (l.discount or 0):
> -                    shippings[l.product_id.id]['uds'] = shippings[l.product_id.id]['uds'] + int(l.quantity or 0)
> -                    shippings[l.product_id.id]['import'] = shippings[l.product_id.id]['import'] + (l.price_subtotal or 0)                
> +            elif (l.product_id and
> +                    product_obj._is_shipping_cost(l.product_id.categ_id)):

Mayor indentación.

> +                if (l.product_id.id in shippings and
> +                    shippings[l.product_id.id]['price'] == (l.price_unit or 0)

Mayor indentación.

> +                    and shippings[l.product_id.id]['dto'] == (l.discount
> +                                                              or 0)):
> +                    shippings[l.product_id.id]['uds'] += int(l.quantity or 0)
> +                    shippings[l.product_id.id]['import'] += (l.price_subtotal
> +                                                             or 0)
>                  else:
> -                    shippings[l.product_id.id] = {'concept': l.product_id and l.product_id.name or " ",
> -                                                  'uds': int(l.quantity or 0), 
> +                    shippings[l.product_id.id] = {'concept': (l.product_id and
> +                                                              l.product_id.name
> +                                                              or " "),
> +                                                  'uds': int(l.quantity or 0),
>                                                    'price': l.price_unit or 0,
> -                                                  'dto': l.discount or 0, 
> -                                                  'import': l.price_subtotal or 0}    
> -
> +                                                  'dto': l.discount or 0,
> +                                                  'import': (l.price_subtotal
> +                                                             or 0)}
>              # Enlaces, repuestos u otros tipos de producto
>              elif l.product_id:
> -                if (l.product_id.id,l.price_unit,l.discount) in links:
> -                    links[(l.product_id.id,l.price_unit,l.discount)]['uds'] = links[(l.product_id.id,l.price_unit,l.discount)]['uds'] + int(l.quantity or 0)
> -                    links[(l.product_id.id,l.price_unit,l.discount)]['import'] = links[(l.product_id.id,l.price_unit,l.discount)]['import'] + (l.price_subtotal or 0)
> +                if (l.product_id.id, l.price_unit, l.discount) in links:
> +                    links[(l.product_id.id, l.price_unit,
> +                           l.discount)]['uds'] += int(l.quantity or 0)
> +                    links[(l.product_id.id, l.price_unit,
> +                           l.discount)]['import'] += (l.price_subtotal or 0)
>                  else:
> -                    links[(l.product_id.id,l.price_unit,l.discount)] = {
> -                        'uds': int(l.quantity or 0), 
> +                    links[(l.product_id.id, l.price_unit, l.discount)] = {
> +                        'uds': int(l.quantity or 0),
>                          'price': l.price_unit or 0,
> -                        'dto': l.discount or 0, 
> +                        'dto': l.discount or 0,
>                          'import': l.price_subtotal or 0,
>                          'concept': l.product_id and l.product_id.name or " ",
>                          }
> -
>              # Resto de líneas (texto libre)
>              else:
>                  others[l.id] = {'concept': l.name or " ",
> -                                'uds': int(l.quantity or 0), 
> +                                'uds': int(l.quantity or 0),
>                                  'price': l.price_unit or 0,
> -                                'dto': l.discount or 0, 
> -                                'import': l.price_subtotal or 0}    
> -                    
> -                
> +                                'dto': l.discount or 0,
> +                                'import': l.price_subtotal or 0}
>          # Diccionario final
>          # -------------------------------------------
> -
> -        # Lineas de teléfono    
> +        # Lineas de teléfono
>          for contract_id in contracts:
>              line = {}
> -            
> -            uds = contracts[contract_id]['uds'] > 1 and str(contracts[contract_id]['uds']) + _(" Líneas Móvil") or str(contracts[contract_id]['uds']) + _(" Línea Móvil")
> -            
> -            concept = _("Contrato ") + contracts[contract_id]['ref'] + " - " + uds + " (" + contracts[contract_id]['type'] + ")"
> -            
> +            uds = (contracts[contract_id]['uds'] > 1 and
> +                   str(contracts[contract_id]['uds']) + _(" Líneas Móvil") or
> +                   str(contracts[contract_id]['uds']) + _(" Línea Móvil"))
> +            concept = (_("Contrato ") + contracts[contract_id]['ref'] + " - " +
> +                       uds + " (" + contracts[contract_id]['type'] + ")")
>              line["concept"] = concept
>              line["uds"] = 1
>              line["price"] = contracts[contract_id]['price'] * sign or 0
>              line["dto"] = 0
> -            line["import"] = contracts[contract_id]['price']  * sign or 0
> -            line["header"] = (count == 0) or (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -            line["pagebreak"] = (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -            
> +            line["import"] = contracts[contract_id]['price'] * sign or 0
> +            line["header"] = ((count == 0) or (count == max_lines_first) or
> +                              ((count % max_lines == max_lines_first)
> +                               and 1 or 0))
> +            line["pagebreak"] = ((count == max_lines_first) or
> +                                 ((count % max_lines == max_lines_first)
> +                                  and 1 or 0))
>              res.append(line)
> -            
>              count += 1
> -            
> -        # Enlaces    
> +        # Enlaces
>          for link_id in links:
>              line = {}
> -            
>              line["concept"] = links[link_id]['concept']
>              line["uds"] = links[link_id]['uds']
>              line["price"] = links[link_id]['price'] * sign or 0
>              line["dto"] = links[link_id]['dto']
>              line["import"] = links[link_id]['import'] * sign or 0
> -            line["header"] = (count == 0) or (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -            line["pagebreak"] = (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -
> +            line["header"] = ((count == 0) or (count == max_lines_first) or
> +                              ((count % max_lines == max_lines_first)
> +                               and 1 or 0))
> +            line["pagebreak"] = ((count == max_lines_first) or
> +                                 ((count % max_lines == max_lines_first)
> +                                  and 1 or 0))
>              res.append(line)
> -            
>              count += 1
> -            
>          # Gastos de envío
>          for shipping_id in shippings:
>              line = {}
> -            
>              line["concept"] = shippings[shipping_id]['concept']
>              line["uds"] = shippings[shipping_id]['uds']
>              line["price"] = shippings[shipping_id]['price'] * sign or 0
>              line["dto"] = shippings[shipping_id]['dto']
>              line["import"] = shippings[shipping_id]['import'] * sign or 0
> -            line["header"] = (count == 0) or (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -            line["pagebreak"] = (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -
> +            line["header"] = ((count == 0) or (count == max_lines_first) or
> +                              ((count % max_lines == max_lines_first)
> +                               and 1 or 0))
> +            line["pagebreak"] = ((count == max_lines_first) or
> +                                 ((count % max_lines == max_lines_first)
> +                                  and 1 or 0))
>              res.append(line)
> -            
> -            count += 1            
> -
> +            count += 1
>          # Resto
>          for other_id in others:
>              line = {}
> -            
>              line["concept"] = others[other_id]['concept']
>              line["uds"] = others[other_id]['uds']
>              line["price"] = others[other_id]['price'] * sign or 0
>              line["dto"] = others[other_id]['dto']
>              line["import"] = others[other_id]['import'] * sign or 0
> -            line["header"] = (count == 0) or (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -            line["pagebreak"] = (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0)
> -
> +            line["header"] = ((count == 0) or (count == max_lines_first) or
> +                              ((count % max_lines == max_lines_first)
> +                               and 1 or 0))
> +            line["pagebreak"] = ((count == max_lines_first) or
> +                                 ((count % max_lines == max_lines_first)
> +                                  and 1 or 0))
>              res.append(line)
> -            
> -            count += 1            
> -
> +            count += 1
>          return res
> -    
> -    def get_phone_lines (self, invoice):
> -        
> -        product_obj = self.pool.get('product.product')
> -        
> +
> +    def get_phone_lines(self, invoice):
> +        product_obj = self.pool['product.product']
>          res = []
> -        
>          sign = 1.0
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              sign = -1.0
> -        
>          count = 0
>          max_lines = 36
> -        
>          # Teléfonos
>          for l in invoice.invoice_line:
> -            if l.contract_annexe_id and l.product_id and product_obj._is_sim(l.product_id.categ_id):
> +            if (l.contract_annexe_id and l.product_id and
> +                    product_obj._is_sim(l.product_id.categ_id)):
>                  line = {}
> -                
>                  link_model = ""
>                  str_annexe_date = ""
>                  str_start_date = ""
>                  str_end_date = ""
>                  num_cabins = l.num_cabins or 0
>                  price_month = 0
> -                
> -                # El campo modelo de enlace, se rellena únicamente cuando el contrato es de tipo integral
> -                if l.contract_id and l.contract_id.contract_type_id and l.contract_id.contract_type_id.ref == 'Integral':
> -                    link = l.contract_annexe_id.production_lot_2_id and l.contract_annexe_id.production_lot_2_id.product_id.name or ''
> +                # El campo modelo de enlace, se rellena únicamente
> +                # cuando el contrato es de tipo integral
> +                if (l.contract_id and l.contract_id.contract_type_id and
> +                        l.contract_id.contract_type_id.ref == 'Integral'):
> +                    lot_2_id = l.contract_annexe_id.production_lot_2_id
> +                    link = (lot_2_id and lot_2_id.product_id.name or '')
>                      link_model = link.replace('Enlace ', '')
> -                    link_model = len(link_model) > 10 and link_model[0:10] or link_model
> -                
> +                    link_model = (len(link_model) > 10 and link_model[0:10] or
> +                                  link_model)
>                  if str(l.contract_annexe_id.annexe_date) != '':
> -                    annexe_date = datetime.strptime(l.contract_annexe_id.annexe_date, '%Y-%m-%d')
> +                    str_annexe_date = l.contract_annexe_id.annexe_date
> +                    annexe_date = datetime.strptime(str_annexe_date,
> +                                                    '%Y-%m-%d')
>                      str_annexe_date = annexe_date.strftime('%d/%m/%Y')
> -                
>                  if str(l.start_date) != '':
>                      start_date = datetime.strptime(l.start_date, '%Y-%m-%d')
>                      str_start_date = start_date.strftime('%d/%m/%Y')
> -                    
>                  if str(l.end_date) != '':
>                      end_date = datetime.strptime(l.end_date, '%Y-%m-%d')
>                      str_end_date = end_date.strftime('%d/%m/%Y')
> -                
> -                price_cabins = num_cabins > 1 and ((num_cabins - 1) * (l.contract_annexe_id.extra_cabin_price or 0)) or 0
> -                price_month = (l.contract_annexe_id.fixed_price or 0) + price_cabins
> -                price_month = price_month - (price_month * (l.contract_annexe_id.differential_price or 0) / 100.0)
> -                
> +                price_cabins = (num_cabins > 1
> +                                and ((num_cabins - 1)
> +                                     * (l.contract_annexe_id.extra_cabin_price
> +                                        or 0)) or 0)
> +                price_month = ((l.contract_annexe_id.fixed_price or 0) +
> +                               price_cabins)
> +                price_month = (price_month -
> +                               (price_month *
> +                                (l.contract_annexe_id.differential_price or 0)
> +                                / 100.0))
>                  ref = l.contract_annexe_id.customer_ref or l.customer_ref or ''
>                  ref = len(ref) > 12 and ref[:11] + '...' or ref
> -                
> -                
> -                
> -                line['phone'] = l.contract_annexe_id.production_lot_id and l.contract_annexe_id.production_lot_id.telefono or ''
> +                phone = (l.contract_annexe_id.production_lot_id and
> +                         l.contract_annexe_id.production_lot_id.telefono or '')
> +                line['phone'] = phone
>                  line["link"] = link_model
>                  line["start_contract"] = str_annexe_date
>                  line["num_cabins"] = num_cabins
> @@ -502,185 +491,154 @@
>                  line["months"] = l.months or 0
>                  line["price_month"] = price_month * sign or 0
>                  line["ref"] = ref
> -                line["total"] = l.price_subtotal * sign or 0  #(l.months or 0) * price_month
> -                
> +                line["total"] = l.price_subtotal * sign or 0
> +                # (l.months or 0) * price_month
>                  res.append(line)
> -
>          # Ordenamos array por telefono
> -        res = sorted(res, key=lambda k: k['phone']) 
> -        
> +        res = sorted(res, key=lambda k: k['phone'])
>          # Añadimos cabeceras
>          result = []
> -        
>          for line in res:
> -            line["header"] = (count%max_lines == 0) and 1 or 0
> +            line["header"] = (count % max_lines == 0) and 1 or 0
>              line["count"] = count
>              result.append(line)
> -            count += 1            
> -        
> +            count += 1
>          return result
> -    
> -    
> -    def get_phone_lines_totals (self, invoice):
> -        
> -        product_obj = self.pool.get('product.product')
> -        
> +
> +    def get_phone_lines_totals(self, invoice):
> +        product_obj = self.pool['product.product']
>          totals = {}
> -        
>          sign = 1.0
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              sign = -1.0
> -            
>          phone = link = num_cabins = months = total = 0
> -        
>          # Teléfonos
>          for l in invoice.invoice_line:
> -            if l.contract_annexe_id and l.product_id and product_obj._is_sim(l.product_id.categ_id):
> +            if (l.contract_annexe_id and l.product_id and
> +                    product_obj._is_sim(l.product_id.categ_id)):
>                  phone += 1
>                  # Solo sumamos enlaces que pertenzca a un contrato Integral
> -                link += l.contract_id and l.contract_id.contract_type_id and (l.contract_id.contract_type_id.ref == 'Integral') and l.contract_annexe_id.production_lot_2_id and 1 or 0
> +                link += (l.contract_id and l.contract_id.contract_type_id and
> +                         (l.contract_id.contract_type_id.ref == 'Integral') and
> +                         l.contract_annexe_id.production_lot_2_id and 1 or 0)
>                  num_cabins += l.num_cabins or 0
>                  months += l.months or 0
>                  total += l.price_subtotal or 0
> -                
>          totals['phone'] = phone
>          totals["link"] = link
>          totals["num_cabins"] = num_cabins
>          totals["months"] = months
>          totals["total"] = total * sign or 0
> -        
>          return [totals]
> -    
> -    
> +
>      def get_picking_info_line(self, line):
> -        
>          if line and line.stock_move_id and line.stock_move_id.picking_id:
> -
>              picking = line.stock_move_id.picking_id
> -            
>              picking_date = datetime.strptime(picking.date[0:10], '%Y-%m-%d')
>              str_picking_date = picking_date.strftime('%d/%m/%Y')
> -            picking_info = _("Albarán") + " " + picking.name + " (" + str_picking_date + ")"
> +            picking_info = "%s %s (%s)" % (_("Albarán"), picking.name,
> +                                           str_picking_date)
>              return picking_info
>          else:
>              return ""
> -        
> +
>      def get_picking_info(self, invoice):
> -        
> -        sql = "SELECT p.name, p.date "
> -        sql += "FROM picking_invoice_rel r "
> -        sql += "INNER JOIN stock_picking p ON p.id = r.picking_id "
> -        sql += "INNER JOIN account_invoice i ON i.id = r.invoice_id "
> -        sql += "WHERE r.invoice_id=" + str(invoice.id)+ " and p.date <= i.date_invoice "
> -        sql += "ORDER BY p.date desc "
> -        
> +        sql = ("SELECT p.name, p.date "
> +               "FROM picking_invoice_rel r "
> +               "INNER JOIN stock_picking p ON p.id = r.picking_id "
> +               "INNER JOIN account_invoice i ON i.id = r.invoice_id "
> +               "WHERE r.invoice_id=" + str(invoice.id) + " and "
> +               "p.date <= i.date_invoice "
> +               "ORDER BY p.date desc ")
>          self.cr.execute(sql)
>          results = self.cr.fetchall()
> -        
>          if results and len(results) > 0:
>              for p in results:
>                  picking_date = datetime.strptime(p[1][0:10], '%Y-%m-%d')
>                  str_picking_date = picking_date.strftime('%d/%m/%Y')
> -                picking_info = _("Albarán") + " " + p[0] + " (" + str_picking_date + ")"
> +                picking_info = (_("Albarán") + " " +
> +                                p[0] + " (" + str_picking_date + ")")
>                  return picking_info
>          else:
>              return ""
> -        
> -        
> -    def get_rest_lines (self, invoice):
> -        
> -        product_obj = self.pool.get('product.product')
> +
> +    def get_rest_lines(self, invoice):
> +        product_obj = self.pool['product.product']
>          space = "     "
> -        
>          res = []
> -        
>          sign = 1.0
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              sign = -1.0
> -        
>          count = 0
>          max_lines = 35
> -        
>          # Enlaces y gastos de envio
> -        sql = "SELECT l.id "
> -        sql += "FROM account_invoice_line l "
> -        sql += "INNER JOIN stock_move m ON l.stock_move_id=m.id "
> -        sql += "INNER JOIN stock_picking a ON m.picking_id=a.id "
> -        sql += "INNER JOIN product_product p ON l.product_id=p.id "
> -        sql += "INNER JOIN product_template t ON p.product_tmpl_id=t.id "
> -        sql += "WHERE l.invoice_id = " + str(invoice.id) + " AND t.categ_id != 2 "
> -        sql += "ORDER BY a.date, a.name, t.categ_id, l.product_id "
> -        
> +        sql = ("SELECT l.id "
> +               "FROM account_invoice_line l "
> +               "INNER JOIN stock_move m ON l.stock_move_id=m.id "
> +               "INNER JOIN stock_picking a ON m.picking_id=a.id "
> +               "INNER JOIN product_product p ON l.product_id=p.id "
> +               "INNER JOIN product_template t ON p.product_tmpl_id=t.id "
> +               "WHERE l.invoice_id = " + str(invoice.id) + " AND t.categ_id != 2 "
> +               "ORDER BY a.date, a.name, t.categ_id, l.product_id ")
>          self.cr.execute(sql)
>          results = self.cr.fetchall()
>          lines_ids = [x[0] for x in results]
> -        
>          ant_picking_info = ""
> -        
> -        for l in self.pool.get('account.invoice.line').browse(self.cr, self.uid, lines_ids, context=None):
> -        
> +        inv_obj = self.pool['account.invoice.line']
> +        for l in inv_obj.browse(self.cr, self.uid, lines_ids, context=context):
>              picking_info = self.get_picking_info_line(l)
> -            
>              # Linea de albarán
>              if picking_info != ant_picking_info:
>                  line = {}
> -                
>                  line["concept"] = picking_info
>                  line["uds"] = 0
>                  line["price"] = 0
>                  line["dto"] = 0
>                  line["import"] = 0
> -                line["header"] = (count%max_lines == 0) and 1 or 0
> +                line["header"] = (count % max_lines == 0) and 1 or 0
>                  line["picking"] = 1
>                  line["count"] = count
> -                
>                  res.append(line)
> -                
>                  ant_picking_info = picking_info
>                  count += 1
> -                
>              # Lineas de enlaces o gastos de envio
>              line = {}
> -            
>              concept = l.product_id and l.product_id.name or " "
> -            
> -            if l.product_id and product_obj._is_link(l.product_id.categ_id) and l.contract_annexe_id.production_lot_2_id:
> -                ref = l.contract_annexe_id.customer_ref or l.customer_ref or '-'
> -                concept += " IMEI: " + (l.contract_annexe_id.production_lot_2_id.imei or '-') + ', REF.: ' + ref
> -                concept = len(concept) > 62 and concept[0:61] + '...' or concept
> -                
> +            if (l.product_id and product_obj._is_link(l.product_id.categ_id)
> +                    and l.contract_annexe_id.production_lot_2_id):
> +                ref = (l.contract_annexe_id.customer_ref or
> +                       l.customer_ref or '-')
> +                concept += (" IMEI: " +
> +                            (l.contract_annexe_id.production_lot_2_id.imei
> +                             or '-') + ', REF.: ' + ref)
> +                concept = (len(concept) > 62 and concept[0:61] +
> +                           '...' or concept)
>              line["concept"] = space + concept
>              line["uds"] = int(l.quantity or 0)
>              line["price"] = l.price_unit * sign or 0
>              line["dto"] = l.discount or 0
>              line["import"] = l.price_subtotal * sign or 0
> -            line["header"] = (count%max_lines == 0) and 1 or 0
> +            line["header"] = (count % max_lines == 0) and 1 or 0
>              line["count"] = count
>              line["picking"] = 0
> -                
>              res.append(line)
> -            
>              count += 1
> +        return res
>  
> -        return res
> -    
> -    def get_rest_lines_total (self, invoice):
> -        
> -        product_obj = self.pool.get('product.product')
> +    def get_rest_lines_total(self, invoice):
> +        product_obj = self.pool['product.product']
>          total = 0
> -        
>          sign = 1.0
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              sign = -1.0
> -        
>          for l in invoice.invoice_line:
> -            if l.stock_move_id and l.stock_move_id.picking_id and l.product_id and not product_obj._is_sim(l.product_id.categ_id):
> +            if (l.stock_move_id and l.stock_move_id.picking_id and l.product_id
> +                    and not product_obj._is_sim(l.product_id.categ_id)):
>                  total += l.price_subtotal or 0
> -
>          return total * sign or 0
>  
>      def get_company_logo(self, company):
> -        return company.logo        
> +        return company.logo
>  
>      def company_address_visible(self):
>          return False
> @@ -692,7 +650,7 @@
>          return (26, 44)
>  
>  
> -class account_invoice_preprinted(account_invoice_custom):
> +class AccountInvoicePreprinted(AccountInvoiceCustom):
>      def get_company_logo(self, company):
>          return None
>  
> @@ -703,7 +661,8 @@
>          return (22, 40)
>  
>  
> -class account_invoice_nayar(account_invoice_custom):
> +class AccountInvoiceNayar(AccountInvoiceCustom):
> +
>      def get_company_logo(self, company):
>          return None
>  
> @@ -712,11 +671,9 @@
>  
>      def get_invoice_lines(self, invoice):
>          max_lines_first, max_lines = self.get_lines_per_page()
> -        
>          sign = 1.0
>          if invoice.type == "out_refund" or invoice.type == "in_refund":
>              sign = -1.0
> -        
>          res = []
>          count = 0
>          for l in invoice.invoice_line:
> @@ -726,21 +683,26 @@
>                  'price': (l.price_unit or 0) * sign,
>                  'dto': l.discount or 0,
>                  'import': (l.price_subtotal or 0) * sign,
> -                'header': (count == 0) or (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0),
> -                'pagebreak': (count == max_lines_first) or ((count%max_lines == max_lines_first) and 1 or 0),
> +                'header': ((count == 0) or (count == max_lines_first) or
> +                           ((count % max_lines == max_lines_first)
> +                            and 1 or 0)),
> +                'pagebreak': ((count == max_lines_first) or
> +                              ((count % max_lines == max_lines_first)
> +                               and 1 or 0)),
>                  }
> -
>              res.append(line)
> -            
>              count += 1
> -
>          return res
> -    
> -        
> -report_sxw.report_sxw('report.account.invoice.custom', 'account.invoice', 'addons/dos_account_invoice_report/report/account_invoice.rml', parser=account_invoice_custom)
> -
> -report_sxw.report_sxw('report.account.invoice.preprinted', 'account.invoice', 'addons/dos_account_invoice_report/report/account_invoice.rml', parser=account_invoice_preprinted)
> -
> -report_sxw.report_sxw('report.account.invoice.nayar', 'account.invoice', 'addons/dos_account_invoice_report/report/account_invoice.rml', parser=account_invoice_nayar)
> -
> +
> +report_sxw.report_sxw('report.account.invoice.custom', 'account.invoice',
> +                      'addons/dos_account_invoice_report'
> +                      '/report/account_invoice.rml',
> +                      parser=AccountInvoiceCustom)
> +report_sxw.report_sxw('report.account.invoice.preprinted', 'account.invoice',
> +                      'addons/dos_account_invoice_report/'
> +                      'report/account_invoice.rml',
> +                      parser=AccountInvoicePreprinted)
> +report_sxw.report_sxw('report.account.invoice.nayar', 'account.invoice',
> +                      'addons/dos_account_invoice_report/'
> +                      'report/account_invoice.rml', parser=AccountInvoiceNayar)
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === added directory 'dos_account_invoice_report/views'
> === added file 'dos_account_invoice_report/views/account_invoice_report.xml'
> --- dos_account_invoice_report/views/account_invoice_report.xml	1970-01-01 00:00:00 +0000
> +++ dos_account_invoice_report/views/account_invoice_report.xml	2014-06-19 15:57:57 +0000
> @@ -0,0 +1,49 @@
> +<?xml version="1.0"?>
> +<openerp>
> +  <data>
> +    <report id="account_invoice_custom_report"
> +	    string="Invoice 72horas"
> +	    model="account.invoice"
> +	    name="account.invoice.custom"
> +	    rml="dos_account_invoice_report/report/account_invoice.rml"
> +	    attachment="(object.state in ('open','paid')) and ((object.number or '').replace('/','') + '.pdf')"
> +	    attachment_use="1"
> +	    header="False"
> +	    auto="False"
> +	    />
> +
> +    <report id="account_invoice_preprinted_report"
> +	    string="Invoice Preprinted 72horas"
> +	    model="account.invoice"
> +	    name="account.invoice.preprinted"
> +	    rml="dos_account_invoice_report/report/account_invoice.rml"
> +	    attachment="(object.state in ('open','paid')) and ((object.number or '').replace('/','') + '.pdf')"
> +	    attachment_use="1"
> +	    header="False"
> +	    auto="False"
> +	    />
> +
> +    <report id="account_invoice_nayar_report"
> +	    string="Invoice Nayar Systems"
> +	    model="account.invoice"
> +	    name="account.invoice.nayar"
> +	    rml="dos_account_invoice_report/report/account_invoice.rml"
> +	    attachment="(object.state in ('open','paid')) and ((object.number or '').replace('/','') + '.pdf')"
> +	    attachment_use="1"
> +	    header="False"
> +	    auto="False"
> +	    />
> +
> +    <record id="view_invoice_report_inherit_account" model="ir.ui.view">
> +      <field name="name">stock.invoice.report.form</field>
> +      <field name="model">account.invoice</field>
> +      <field name="inherit_id" ref="account.invoice_form"/>
> +      <field name="arch" type="xml">
> +		<button string="Print Invoice" position="attributes">
> +			<attribute name='states'>open,paid,proforma,sale,proforma2</attribute>
> +		</button>
> +      </field>
> +    </record>
> +
> +  </data>
> +</openerp>
> 
> === modified file 'dos_mrp_production/__init__.py'
> --- dos_mrp_production/__init__.py	2014-06-11 10:23:47 +0000
> +++ dos_mrp_production/__init__.py	2014-06-19 15:57:57 +0000
> @@ -19,7 +19,6 @@
>  #
>  ##############################################################################
>  
> -import mrp_production
> -import mrp_procurement
> +from . import models
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === modified file 'dos_mrp_production/__openerp__.py'
> --- dos_mrp_production/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ dos_mrp_production/__openerp__.py	2014-06-19 15:57:57 +0000
> @@ -21,17 +21,14 @@
>  
>  
>  {
> -	"name" : "DOS Mrp Production",
> -	"version" : "1.0",
> -	"author" : "DOS",
> -	"category" : "Production",
> -	"website" : "www.dos-sl.es",
> -	"description": "This module allows automates the selection of locations for production orders.",
> -	"depends" : ["dos_product_additional_info", "mrp"],
> -	"init_xml" : [],
> -	"update_xml" : ['stock_view.xml',],
> -	"active": False,
> -	"installable": True
> +    "name": "DOS Mrp Production",
> +    "version": "1.0",
> +    "author": "DOS",
> +    "category": "Production",
> +    "website": "www.dos-sl.es",
> +    "description": "This module allows automates the selection of "
> +                   "locations for production orders.",
> +    "depends": ["dos_product_additional_info", "mrp"],
> +    "data": ['stock_view.xml'],
> +    "installable": True
>  }
> -
> -
> 
> === added directory 'dos_mrp_production/models'
> === renamed file 'dos_mrp_production/mrp_procurement.py' => 'dos_mrp_production/models/mrp_procurement.py'
> --- dos_mrp_production/mrp_procurement.py	2014-06-11 10:23:47 +0000
> +++ dos_mrp_production/models/mrp_procurement.py	2014-06-19 15:57:57 +0000
> @@ -21,35 +21,39 @@
>  
>  from datetime import datetime
>  from dateutil.relativedelta import relativedelta
> -from osv import fields
> -from osv import osv
> -from tools.translate import _
> -import ir
> -import netsvc
> -import time
> -
> -class procurement_order(osv.osv):
> +from openerp.osv import orm, fields
> +from openerp.tools.translate import _
> +from . import ir

Mal referenciado. Ver más arriba.

> +from . import netsvc
> +from . import time
> +
> +
> +class procuremenOrder(orm.Model):
>  
>      _inherit = 'procurement.order'
> - 
> +
>      def make_mo(self, cr, uid, ids, context=None):
>          """ Make Manufacturing(production) order from procurement
> -        @return: New created Production Orders procurement wise 
> +        @return: New created Production Orders procurement wise
>          """
>          res = {}
> -        company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id
> -        production_obj = self.pool.get('mrp.production')
> -        move_obj = self.pool.get('stock.move')
> +        company = self.pool['res.users'].browse(cr, uid, uid,
> +                                                context).company_id
> +        production_obj = self.pool['mrp.production']
> +        move_obj = self.pool['stock.move']
>          wf_service = netsvc.LocalService("workflow")
> -        procurement_obj = self.pool.get('procurement.order')
> -        for procurement in procurement_obj.browse(cr, uid, ids, context=context):
> +        procurement_obj = self.pool['procurement.order']
> +        for procurement in procurement_obj.browse(cr, uid, ids,
> +                                                  context=context):
>              res_id = procurement.move_id.id
>              loc_id = procurement.location_id.id
> -            newdate = datetime.strptime(procurement.date_planned, '%Y-%m-%d %H:%M:%S') - relativedelta(days=procurement.product_id.product_tmpl_id.produce_delay or 0.0)
> +            tmpl_delay = procurement.product_id.product_tmpl_id.produce_delay
> +            newdate = (datetime.strptime(procurement.date_planned,
> +                                         '%Y-%m-%d %H:%M:%S') -
> +                       relativedelta(days=tmpl_delay or 0.0))
>              newdate = newdate - relativedelta(days=company.manufacturing_lead)
> -            
> -            #Si el producto esta marcado como producción unitaria
> -            #Creamos tantas ordenes de producción como cantidad a produccir
> +            #  Si el producto esta marcado como producción unitaria
> +            #  Creamos tantas ordenes de producción como cantidad a produccir
>              if procurement.product_id.unitary_prod_order:
>                  produce_ids = []
>                  for i in range(0, int(procurement.product_qty)):
> @@ -58,55 +62,60 @@
>                          'product_id': procurement.product_id.id,
>                          'product_qty': 1,
>                          'product_uom': procurement.product_uom.id,
> -                        'product_uos_qty': procurement.product_uos and procurement.product_uos_qty or False,
> -                        'product_uos': procurement.product_uos and procurement.product_uos.id or False,
> +                        'product_uos_qty': (procurement.product_uos and
> +                                            procurement.product_uos_qty
> +                                            or False),
> +                        'product_uos': (procurement.product_uos and
> +                                        procurement.product_uos.id or False),
>                          'location_src_id': procurement.location_id.id,
>                          'location_dest_id': procurement.location_id.id,
> -                        'bom_id': procurement.bom_id and procurement.bom_id.id or False,
> +                        'bom_id': (procurement.bom_id and procurement.bom_id.id
> +                                   or False),
>                          'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'),
>                          'move_prod_id': res_id,
>                          'company_id': procurement.company_id.id,
>                      })
> -                    
>                      produce_ids.append(produce_id)
> -                    
>                  self.write(cr, uid, [procurement.id], {'state': 'running'})
> +                props = [x.id for x in procurement.property_ids]
>                  bom_result = production_obj.action_compute(cr, uid,
> -                        produce_ids, properties=[x.id for x in procurement.property_ids])
> -                
> +                                                           produce_ids,
> +                                                           properties=props)
>                  for produce_id in produce_ids:
> -                    wf_service.trg_validate(uid, 'mrp.production', produce_id, 'button_confirm', cr)
> +                    wf_service.trg_validate(uid, 'mrp.production', produce_id,
> +                                            'button_confirm', cr)
>                      res[procurement.id] = produce_id
> -                    
>                  move_obj.write(cr, uid, [res_id],
> -                        {'location_id': procurement.location_id.id})
> -                
> -            #Caso normal
> +                               {'location_id': procurement.location_id.id})
> +            #  Caso normal
>              else:
>                  produce_id = production_obj.create(cr, uid, {
>                      'origin': procurement.origin,
>                      'product_id': procurement.product_id.id,
>                      'product_qty': procurement.product_qty,
>                      'product_uom': procurement.product_uom.id,
> -                    'product_uos_qty': procurement.product_uos and procurement.product_uos_qty or False,
> -                    'product_uos': procurement.product_uos and procurement.product_uos.id or False,
> +                    'product_uos_qty': (procurement.product_uos and
> +                                        procurement.product_uos_qty or False),
> +                    'product_uos': (procurement.product_uos and
> +                                    procurement.product_uos.id or False),
>                      'location_src_id': procurement.location_id.id,
>                      'location_dest_id': procurement.location_id.id,
> -                    'bom_id': procurement.bom_id and procurement.bom_id.id or False,
> +                    'bom_id': (procurement.bom_id and procurement.bom_id.id
> +                               or False),
>                      'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'),
>                      'move_prod_id': res_id,
>                      'company_id': procurement.company_id.id,
>                  })
>                  res[procurement.id] = produce_id
>                  self.write(cr, uid, [procurement.id], {'state': 'running'})
> +                props = [x.id for x in procurement.property_ids]
>                  bom_result = production_obj.action_compute(cr, uid,
> -                        [produce_id], properties=[x.id for x in procurement.property_ids])
> -                wf_service.trg_validate(uid, 'mrp.production', produce_id, 'button_confirm', cr)
> +                                                           [produce_id],
> +                                                           properties=props)
> +                wf_service.trg_validate(uid, 'mrp.production', produce_id,
> +                                        'button_confirm', cr)
>                  move_obj.write(cr, uid, [res_id],
> -                        {'location_id': procurement.location_id.id})
> -                
> +                               {'location_id': procurement.location_id.id})
>          return res
> -    
> -procurement_order()
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === renamed file 'dos_mrp_production/mrp_production.py' => 'dos_mrp_production/models/mrp_production.py'
> --- dos_mrp_production/mrp_production.py	2014-06-11 10:23:47 +0000
> +++ dos_mrp_production/models/mrp_production.py	2014-06-19 15:57:57 +0000
> @@ -19,110 +19,104 @@
>  #
>  ##############################################################################
>  
> -from osv import osv, fields
> -from tools.translate import _
> -import netsvc
> -import time
> -import tools
> -
> -class mrp_production(osv.osv): 
> -
> +from openerp.osv import orm, fields
> +from openerp.tools.translate import _
> +from . import netsvc

Ídem

> +from . import time
> +from . import tools
> +
> +
> +class MrpProduction(orm.Model):
>      _name = 'mrp.production'
>      _inherit = 'mrp.production'
> -    
> +
>      def product_id_change(self, cr, uid, ids, product_id, context=None):
> -    	
> -    	value = {}
> +        value = {}
>          location_src_id = False
>          location_dest_id = False
> -        
> -    	#Llamamos a la funcion on_change por defecto de product_id
> -    	result = super(mrp_production, self).product_id_change(cr, uid, ids, product_id, context=None)
> -    	
> -    	if result and result.has_key('value'):
> -    		value = result['value']
> -            
> +        # Llamamos a la funcion on_change por defecto de product_id
> +        result = super(MrpProduction, self).product_id_change(cr, uid, ids,
> +                                                              product_id,
> +                                                              context=None)
> +        if result and 'value' in result:
> +            value = result['value']
>          if product_id:
> -            bom_obj = self.pool.get('mrp.bom')
> -            product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
> -            bom_id = bom_obj._bom_find(cr, uid, product.id, product.uom_id and product.uom_id.id, [])
> +            bom_obj = self.pool['mrp.bom']
> +            product = self.pool['product.product'].browse(cr, uid,
> +                                                              product_id,
> +                                                              context=context)
> +            bom_id = bom_obj._bom_find(cr, uid, product.id, product.uom_id and
> +                                       product.uom_id.id, [])
>              routing_id = False
>              if bom_id:
>                  bom_point = bom_obj.browse(cr, uid, bom_id, context=context)
>                  for bom_line in bom_point.bom_lines:
> +                    prod = bom_line.product_id
>                      if not location_src_id:
> -                        location_src_id = bom_line.product_id and bom_line.product_id.property_stock_consumer_product and bom_line.product_id.property_stock_consumer_product.id or False
> -                    
> +                        consum_prod = (prod and
> +                                       prod.property_stock_consumer_product)
> +                        location_src_id = (consum_prod and consum_prod.id
> +                                           or False)
>                      if not location_dest_id:
> -                        location_dest_id = bom_line.product_id and bom_line.product_id.property_stock_finished_product and bom_line.product_id.property_stock_finished_product.id or False
> -     
> +                        finish_prod = (prod and
> +                                       prod.property_stock_finished_product)
> +                        location_dest_id = (finish_prod and finish_prod.id
> +                                            or False)
>                      if location_src_id and location_dest_id:
>                          break
> -        
>          value['location_src_id'] = location_src_id
> -        value['location_dest_id'] = location_dest_id      
> -          
> -    	return {'value': value}
> -    	
> +        value['location_dest_id'] = location_dest_id
> +        return {'value': value}
> +
>      def bom_id_change(self, cr, uid, ids, bom_id, context=None):
> -    	
>          value = {}
>          location_src_id = False
>          location_dest_id = False
> -        
> -        #Llamamos a la funcion on_change por defecto de product_id
> -        result = super(mrp_production, self).bom_id_change(cr, uid, ids, bom_id, context=None)
> -        
> -        if result and result.has_key('value'):
> +        # Llamamos a la funcion on_change por defecto de product_id
> +        result = super(MrpProduction, self).bom_id_change(cr, uid, ids, bom_id,
> +                                                          context=None)
> +        if result and 'value' in result:
>              value = result['value']
> -            
>          if bom_id:
> -            bom_obj = self.pool.get('mrp.bom')
> +            bom_obj = self.pool['mrp.bom']
>              bom_point = bom_obj.browse(cr, uid, bom_id, context=context)
> -
>              for bom_line in bom_point.bom_lines:
> +                prod = bom_line.product_id
>                  if not location_src_id:
> -                    location_src_id = bom_line.product_id and bom_line.product_id.property_stock_consumer_product and bom_line.product_id.property_stock_consumer_product.id or False
> -                
> +                    consum_prod = prod and prod.property_stock_consumer_product
> +                    location_src_id = (consum_prod and consum_prod.id or False)
>                  if not location_dest_id:
> -                    location_dest_id = bom_line.product_id and bom_line.product_id.property_stock_finished_product and bom_line.product_id.property_stock_finished_product.id or False
> - 
> +                    finish_prod = prod and prod.property_stock_finished_product
> +                    location_dest_id = (finish_prod and finish_prod.id
> +                                        or False)
>                  if location_src_id and location_dest_id:
>                      break
> -        
>          value['location_src_id'] = location_src_id
> -        value['location_dest_id'] = location_dest_id       
> -          
> +        value['location_dest_id'] = location_dest_id
>          return {'value': value}
>  
> -
> -    def action_produce(self, cr, uid, production_id, production_qty, production_mode, context=None):
> -        
> -        product_obj = self.pool.get('product.product')
> -        stock_mov_obj = self.pool.get('stock.move')
> -        prodlot_obj = self.pool.get('stock.production.lot')
> -        
> +    def action_produce(self, cr, uid, production_id, production_qty,
> +                       production_mode, context=None):
> +        product_obj = self.pool['product.product']
> +        stock_mov_obj = self.pool['stock.move']
> +        prodlot_obj = self.pool['stock.production.lot']
>          link_prodlot = False
>          sim_prodlot = False
>          pack_prodlot_id = False
>          pack_description = ''
> -        
>          production = self.browse(cr, uid, production_id, context=context)
> -        
>          # Identificamos los productos a consumir de tipo SIM y ENLACE
>          for move_line in production.move_lines + production.move_lines2:
>              if move_line.prodlot_id:
>                  if product_obj._is_sim(move_line.product_id.categ_id):
>                      sim_prodlot = move_line.prodlot_id
> -                    
>                  elif product_obj._is_link(move_line.product_id.categ_id):
>                      link_prodlot = move_line.prodlot_id
> -
>          # Creamos lotes de producción (si no lo estan ya)
>          # para los productos finalizados de tipo pack
>          for move_created in production.move_created_ids:
> -            if product_obj._is_pack(move_created.product_id.categ_id) and sim_prodlot and link_prodlot:
> -
> +            if (product_obj._is_pack(move_created.product_id.categ_id)
> +                    and sim_prodlot and link_prodlot):
>                  pack_description = move_created.name
>                  if move_created.prodlot_id:
>                      # Si tiene lote de produccion asignada
> @@ -130,46 +124,55 @@
>                  else:
>                      # Si no tiene lote de produccion, creamos uno nuevo
>                      # y lo asignamos al movimiento
> -                    pack_prodlot_id = prodlot_obj.search(cr, uid, [('name', '=', link_prodlot.name), ('ref', '=', sim_prodlot.telefono)])
> +                    lot_name_ref = [('name', '=', link_prodlot.name),
> +                                    ('ref', '=', sim_prodlot.telefono)]
> +                    pack_prodlot_id = prodlot_obj.search(cr, uid, lot_name_ref,
> +                                                         context=context)
>                      if pack_prodlot_id:
>                          pack_prodlot_id = pack_prodlot_id[0]
>                      else:
> -                        pack_prodlot_id = prodlot_obj.create(cr, uid, { 'product_id': move_created.product_id.id, })
> -
> -                    stock_mov_obj.write(cr, uid, [move_created.id], {'prodlot_id': pack_prodlot_id}, context={})
> -
> +                        prod_info = {'product_id': move_created.product_id.id}
> +                        pack_prodlot_id = prodlot_obj.create(cr, uid, prod_info
> +                                                             )
> +                    stock_mov_obj.write(cr, uid, [move_created.id],
> +                                        {'prodlot_id': pack_prodlot_id},
> +                                        context={})

context=context

>                  break
> -
> -
>          if sim_prodlot and link_prodlot and pack_prodlot_id:
> -            
>              # Rellenamos información adicional en el lote del pack
> -            prodlot_obj.write(cr, uid, [pack_prodlot_id], {'name': link_prodlot.name,
> -                                                           'descripcion': pack_description,
> -                                                           'icc': sim_prodlot.icc,
> -                                                           'telefono': sim_prodlot.telefono,
> -                                                           'pin': sim_prodlot.pin,
> -                                                           'puk': sim_prodlot.puk,
> -                                                           'operador': sim_prodlot.operador,
> -                                                           'imei': link_prodlot.imei,
> -                                                           'n_serie': link_prodlot.n_serie,
> -                                                           'tipo_enlace': link_prodlot.tipo_enlace,
> -                                                           'propietario': link_prodlot.propietario,
> -                                                           'precio': link_prodlot.precio,
> -                                                           'precio_subvencionado': link_prodlot.precio_subvencionado,                                                          
> -                                                           'ref_cliente': sim_prodlot.ref_cliente,
> -                                                           'fecha_alta': time.strftime('%Y-%m-%d'),
> -                                                           #'observaciones': sim_prodlot.observaciones,
> -                                                           #'albaran_entrada': sim_prodlot.albaran_entrada,
> -                                                           #'fecha_compra': link_prodlot.fecha_compra,
> -                                                           #'fecha_activacion': sim_prodlot.fecha_activacion,
> -                                                        }, context={})
> -            
> +            subsidy_price = link_prodlot.precio_subvencionado
> +            prodlot_obj.write(cr, uid, [pack_prodlot_id],
> +                              {'name': link_prodlot.name,
> +                               'descripcion': pack_description,
> +                               'icc': sim_prodlot.icc,
> +                               'telefono': sim_prodlot.telefono,
> +                               'pin': sim_prodlot.pin,
> +                               'puk': sim_prodlot.puk,
> +                               'operador': sim_prodlot.operador,
> +                               'imei': link_prodlot.imei,
> +                               'n_serie': link_prodlot.n_serie,
> +                               'tipo_enlace': link_prodlot.tipo_enlace,
> +                               'propietario': link_prodlot.propietario,
> +                               'precio': link_prodlot.precio,
> +                               'precio_subvencionado': subsidy_price,
> +                               'ref_cliente': sim_prodlot.ref_cliente,
> +                               'fecha_alta': time.strftime('%Y-%m-%d'),
> +                               # 'observaciones':
> +                               # sim_prodlot.observaciones,
> +                               # 'albaran_entrada':
> +                               # sim_prodlot.albaran_entrada,
> +                               # 'fecha_compra':
> +                               # link_prodlot.fecha_compra,
> +                               # 'fecha_activacion':
> +                               # sim_prodlot.fecha_activacion,
> +                               }, context={})
>          else:
> -            raise osv.except_osv(_('No production lots !'), _('Must assign production lots to consume products !'))
> -        
> -        #Llamamos a la funcion super de action_produce
> -        return super(mrp_production, self).action_produce(cr, uid, production_id, production_qty, production_mode, context=None)
> -        
> -        
> -mrp_production()
> +            raise orm.except_orm(_('No production lots !'),
> +                                 _('Must assign production lots'
> +                                   ' to consume products !'))
> +        #  Llamamos a la funcion super de action_produce
> +        return super(MrpProduction, self).action_produce(cr, uid,
> +                                                         production_id,
> +                                                         production_qty,
> +                                                         production_mode,
> +                                                         context=None)
> 
> === added directory 'dos_mrp_production/views'
> === renamed file 'dos_mrp_production/stock_view.xml' => 'dos_mrp_production/views/stock_view.xml'
> --- dos_mrp_production/stock_view.xml	2014-06-11 10:23:47 +0000
> +++ dos_mrp_production/views/stock_view.xml	2014-06-19 15:57:57 +0000
> @@ -5,7 +5,6 @@
>              <field name="name">stock.move.form.inherit</field>
>              <field name="model">stock.move</field>
>              <field name="inherit_id" ref="stock.view_move_form"/>
> -            <field name="type">form</field>
>              <field name="priority">1</field>
>              <field name="arch" type="xml">
>                  <field name="prodlot_id" position="replace">
> 
> === modified file 'dos_mysql_connect/__init__.py'
> --- dos_mysql_connect/__init__.py	2014-06-11 10:23:47 +0000
> +++ dos_mysql_connect/__init__.py	2014-06-19 15:57:57 +0000
> @@ -19,6 +19,6 @@
>  #
>  ##############################################################################
>  
> -import mysql_connect
> +from . import models
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === modified file 'dos_mysql_connect/__openerp__.py'
> --- dos_mysql_connect/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ dos_mysql_connect/__openerp__.py	2014-06-19 15:57:57 +0000
> @@ -20,21 +20,17 @@
>  ##############################################################################
>  
>  {
> -    "name" : "DOS MySql Connect",
> -    "version" : "1.0",
> -    "author" : "DOS",
> -    "category" : "Base",
> -    "website" : "www.dos-sl.es",
> +    "name": "DOS MySql Connect",
> +    "version": "1.0",
> +    "author": "DOS",
> +    "category": "Base",
> +    "website": "www.dos-sl.es",
>      "description": "This module allows you connect to a MySql database.",
> -    "depends" : ['base_tools'],
> -    "init_xml" : [],
> -    "update_xml" : [
> -					'security/mysql_connect_security.xml',
> -					'security/ir.model.access.csv',
> -					'mysql_connect_view.xml',
> -					],
> -    "active": False,
> +    "depends": ['base_tools'],
> +    "data": [
> +        'security/mysql_connect_security.xml',
> +        'security/ir.model.access.csv',
> +        'models/mysql_connect_view.xml',
> +    ],
>      "installable": True
>  }
> -
> -
> 
> === added directory 'dos_mysql_connect/models'
> === added file 'dos_mysql_connect/models/__init__.py'
> --- dos_mysql_connect/models/__init__.py	1970-01-01 00:00:00 +0000
> +++ dos_mysql_connect/models/__init__.py	2014-06-19 15:57:57 +0000
> @@ -0,0 +1,22 @@
> +# -*- coding: utf-8 -*-
> +##############################################################################
> +#
> +#    OpenERP, Open Source Management Solution
> +#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
> +#
> +#    This program is free software: you can redistribute it and/or modify
> +#    it under the terms of the GNU Affero General Public License as
> +#    published by the Free Software Foundation, either version 3 of the
> +#    License, or (at your option) any later version.
> +#
> +#    This program is distributed in the hope that it will be useful,
> +#    but WITHOUT ANY WARRANTY; without even the implied warranty of
> +#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +#    GNU Affero General Public License for more details.
> +#
> +#    You should have received a copy of the GNU Affero General Public License
> +#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
> +#
> +##############################################################################
> +
> +from . import mysql_connect
> \ No newline at end of file
> 
> === renamed file 'dos_mysql_connect/mysql_connect.py' => 'dos_mysql_connect/models/mysql_connect.py'
> --- dos_mysql_connect/mysql_connect.py	2014-06-11 10:23:47 +0000
> +++ dos_mysql_connect/models/mysql_connect.py	2014-06-19 15:57:57 +0000
> @@ -19,99 +19,91 @@
>  #
>  ##############################################################################
>  
> -from osv import osv
> -from osv import fields
> -from tools.translate import _
> +from openerp.osv import orm, fields
> +from openerp.tools.translate import _
>  import time
>  import MySQLdb
>  
> -class mysql_connect(osv.osv): 
> -
> -	_name = 'mysql.connect'
> -	_description = 'MySql Connect'
> -
> -	_columns = {
> -		'host': fields.char('Host', size=256, required=True, help='MySql host server address .'),
> -		'database': fields.char('Database', size=128, required=True, help='Name of the MySql database.'),
> -		'user': fields.char('User', size=128, required=True, help='User access to the MySql database.'),
> -		'password': fields.char('Password', size=128, required=True, help='Password to access the MySql database.'),
> -	}
> -	
> -	def test_connection(self, cr, uid, ids, context=None):
> -		if context is None:
> -			context = {}
> -
> -		data = ""
> -		
> -		for obj_conn in self.browse(cr, uid, ids, context=context):
> -			try:
> -				db = MySQLdb.connect(host = obj_conn.host, user = obj_conn.user, passwd = obj_conn.password, db = obj_conn.database)
> -				
> -				cursor = db.cursor()
> -				
> -				cursor.execute("SELECT VERSION()")
> -				
> -				row = cursor.fetchone()
> -				
> -				data = row[0]
> -	
> -				db.close()
> -				
> -			except Exception,e:
> -				raise osv.except_osv(_('Error connecting !'), e) 
> -			
> -		raise osv.except_osv(_('Successful connection'), _('The connection configuration is correct!') + '\n\r' + _('MySql Version: ') + data)
> -	
> -		return True
> -	
> -	def open_connection(self, cr, uid):
> -	
> -		# Cargamos datos configuracion
> -		config_ids = self.search(cr, uid, [], limit=1)
> -		if config_ids:
> -			config = self.browse(cr, uid, config_ids[0])
> -		else:
> -			raise osv.except_osv(_('Error !'), _('First define the configuration parameters of the mySql connection.'))
> -		
> -		# Abrimos conexion
> -		try:
> -			db = MySQLdb.connect(host = config.host, user = config.user, passwd = config.password, db = config.database)
> -			return db
> -		except Exception,e:
> -			return None
> -			
> -	def close_connection(self, db):
> -	
> -		# Cerramos conexion
> -		if db:
> -			db.close
> -			
> -		return True
> -		 
> -	def get_customer_ref(self, cr, uid, db, phone_number):
> -		
> -		# Comprobamos que existe una conexion abierta
> -		if not db:
> -			raise osv.except_osv(_('Error !'), _('First open mySql connection.'))
> -			
> -		customer_refs = None
> -		
> -		try:
> -			cursor = db.cursor()
> -			
> -			cursor.execute ("SELECT ref_cliente FROM telefonos WHERE n_telefono = '" + str(phone_number) + "'")
> -			
> -			rows = cursor.fetchall()
> -			
> -			for row in rows:
> -				customer_ref = row[0]
> -				# Controlamos que la referencia obtenida no sea nula o ?
> -				if customer_ref and customer_ref != '?':
> -					customer_refs = customer_refs and (customer_refs + ', ' + customer_ref) or customer_ref
> -				
> -		except Exception,e:
> -			return None
> -		 
> -		return customer_refs
> -	
> -mysql_connect()
> +
> +class MysqlConnect(orm.Model):
> +
> +    _name = 'mysql.connect'
> +    _description = 'MySql Connect'
> +    _columns = {
> +        'host': fields.char('Host', size=256, required=True,
> +                            help='MySql host server address .'),
> +        'database': fields.char('Database', size=128, required=True,
> +                                help='Name of the MySql database.'),
> +        'user': fields.char('User', size=128, required=True,
> +                            help='User access to the MySql database.'),
> +        'password': fields.char('Password', size=128, required=True,
> +                                help='Password to access the MySql database.'),
> +    }
> +
> +    def test_connection(self, cr, uid, ids, context=None):
> +        if context is None:
> +            context = {}
> +        data = ""
> +        for obj_conn in self.browse(cr, uid, ids, context=context):
> +            try:
> +                db = MySQLdb.connect(host=obj_conn.host,
> +                                     user=obj_conn.user,
> +                                     passwd=obj_conn.password,
> +                                     db=obj_conn.database)
> +                cursor = db.cursor()
> +                cursor.execute("SELECT VERSION()")
> +                row = cursor.fetchone()
> +                data = row[0]
> +                db.close()
> +            except Exception, e:
> +                raise orm.except_orm(_('Error connecting !'), e)
> +        raise orm.except_orm(_('Successful connection'),
> +                             _('The connection configuration is correct!') +
> +                             '\n\r' + _('MySql Version: ') + data)
> +        return True
> +
> +    def open_connection(self, cr, uid, context=None):
> +        # Cargamos datos configuracion
> +        config_ids = self.search(cr, uid, [], limit=1)
> +        if config_ids:
> +            config = self.browse(cr, uid, config_ids[0], context=context)
> +        else:
> +            raise orm.except_orm(_('Error !'), _('First define the '
> +                                                 'configuration parameters of'
> +                                                 ' the mySql connection.'))
> +        # Abrimos conexion
> +        try:
> +            db = MySQLdb.connect(host=config.host, user=config.user,
> +                                 passwd=config.password,
> +                                 db=config.database)
> +            return db
> +        except Exception, e:
> +            return None
> +
> +    def close_connection(self, db):
> +        # Cerramos conexion
> +        if db:
> +            db.close
> +        return True
> +
> +    def get_customer_ref(self, cr, uid, db, phone_number):
> +        # Comprobamos que existe una conexion abierta
> +        if not db:
> +            raise orm.except_orm(_('Error !'),
> +                                 _('First open mySql connection.'))
> +        customer_refs = None
> +        try:
> +            cursor = db.cursor()
> +            cursor.execute("SELECT ref_cliente FROM telefonos "
> +                           "WHERE n_telefono = '" + str(phone_number) + "'")
> +            rows = cursor.fetchall()
> +            for row in rows:
> +                customer_ref = row[0]
> +                # Controlamos que la referencia obtenida no sea nula o ?
> +                if customer_ref and customer_ref != '?':
> +                    customer_refs = (customer_refs
> +                                     and (customer_refs + ', ' + customer_ref)
> +                                     or customer_ref)
> +        except Exception, e:
> +            return None
> +        return customer_refs
> 
> === added directory 'dos_mysql_connect/views'
> === renamed file 'dos_mysql_connect/mysql_connect_view.xml' => 'dos_mysql_connect/views/mysql_connect_view.xml'
> --- dos_mysql_connect/mysql_connect_view.xml	2014-06-11 10:23:47 +0000
> +++ dos_mysql_connect/views/mysql_connect_view.xml	2014-06-19 15:57:57 +0000
> @@ -6,7 +6,6 @@
>          <record id="view_mysql_config_search" model="ir.ui.view">
>              <field name="name">view.mysql.config.search</field>
>              <field name="model">mysql.connect</field>
> -            <field name="type">search</field>
>              <field name="arch" type="xml">
>                  <search string="Search">
>                      <field name="host" select="1"/>
> @@ -19,7 +18,6 @@
>          <record id="view_mysql_config_tree" model="ir.ui.view">
>              <field name="name">view.mysql.config.tree</field>
>              <field name="model">mysql.connect</field>
> -            <field name="type">tree</field>
>              <field name="arch" type="xml">
>                  <tree string="MySql Connect Config">
>                      <field name="host" />
> @@ -33,7 +31,6 @@
>  		<record id="view_mysql_config_form" model="ir.ui.view" >
>  			<field name="name">view.mysql.config.form</field>
>  			<field name="model">mysql.connect</field>
> -			<field name="type">form</field>
>  			<field name="arch" type="xml">
>  				<form string="MySql Connect Config">
>  					<group colspan="4" col="4">
> 
> === modified file 'dos_picking_in_import/__init__.py'
> --- dos_picking_in_import/__init__.py	2014-06-11 10:23:47 +0000
> +++ dos_picking_in_import/__init__.py	2014-06-19 15:57:57 +0000
> @@ -19,7 +19,7 @@
>  #
>  ##############################################################################
>  
> -import wizard
> -import stock
> +from . import wizard
> +from . import models
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === modified file 'dos_picking_in_import/__openerp__.py'
> --- dos_picking_in_import/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ dos_picking_in_import/__openerp__.py	2014-06-19 15:57:57 +0000
> @@ -19,19 +19,17 @@
>  #
>  ##############################################################################
>  
> -
>  {
> -    "name" : "DOS Services To Invoice",
> -    "version" : "1.0",
> -    "author" : "DOS",
> -    "category" : "Stock",
> -    "website" : "www.dos-sl.es",
> -    "description": "This module allows to speed up the process of importing invoices input from a data file for the automatic creation of the delivery note lines with the SIM and lot numbers specified in the file.",
> -    "depends" : ['stock'],
> -    "init_xml" : [],
> -    "update_xml" : ['wizard/picking_in_import_view.xml', 'stock_view.xml'],
> -    "active": False,
> +    "name": "DOS Services To Invoice",
> +    "version": "1.0",
> +    "author": "DOS",
> +    "category": "Stock",
> +    "website": "www.dos-sl.es",
> +    "description": "This module allows to speed up the process of "
> +                   "importing invoices input from a data file for the "
> +                   " automatic creation of the delivery note lines with "
> +                   "the SIM and lot numbers specified in the file.",
> +    "depends": ['stock'],
> +    "data": ['wizard/picking_in_import_view.xml', 'stock_view.xml'],

La referencia de stock_view.xml ha cambiado.

>      "installable": True
>  }
> -
> -
> 
> === added directory 'dos_picking_in_import/models'
> === renamed file 'dos_picking_in_import/stock.py' => 'dos_picking_in_import/models/stock.py'
> --- dos_picking_in_import/stock.py	2014-06-11 10:23:47 +0000
> +++ dos_picking_in_import/models/stock.py	2014-06-19 15:57:57 +0000
> @@ -19,88 +19,80 @@
>  #
>  ##############################################################################
>  
> -from osv import fields, osv
> -import decimal_precision as dp
> +from openerp.osv import fields, orm
> +from . import decimal_precision as dp
>  import time
>  
> -class stock_picking(osv.osv):
> -
> -    _inherit ="stock.picking"
> +
> +class StockPicking(orm.Models):
> +
> +    _inherit = "stock.picking"
>  
>      def do_partial(self, cr, uid, ids, partial_datas, context=None):
> -
> -        res = super(stock_picking, self).do_partial(cr, uid, ids, partial_datas, context=context)
> -
> -	if context is None: context = {}
> -
> -	stock_move_obj = self.pool.get('stock.move')
> -	stock_warehouse_obj = self.pool.get('stock.warehouse')
> -
> -	#Comprobamos que hay al menos un almacen definido
> -	stock_warehouse = None
> -	stock_warehouse_ids = stock_warehouse_obj.search(cr, uid, [])
> -	for warehouse in stock_warehouse_obj.browse(cr, uid, stock_warehouse_ids, context):
> +        res = super(StockPicking, self).do_partial(cr, uid, ids, partial_datas,
> +                                                   context=context)
> +        if context is None:
> +            context = {}
> +        stock_move_obj = self.pool['stock.move']
> +        stock_warehouse_obj = self.pool['stock.warehouse']
> +        # Comprobamos que hay al menos un almacen definido
> +        stock_warehouse = None
> +        stock_warehouse_ids = stock_warehouse_obj.search(cr, uid, [])
> +        for warehouse in stock_warehouse_obj.browse(cr, uid,
> +                                                    stock_warehouse_ids,
> +                                                    context):
>              stock_warehouse = warehouse
> -	    break
> -
> -	if stock_warehouse:
> -
> -            for id in ids:
> -                if id in res and 'delivered_picking' in res[id]:
> -                    picking_id = res[id]['delivered_picking']
> -		    picking = self.browse(cr, uid, picking_id, context=context)
> -		    picking_internal_id = None
> -
> -                    # Solo al validar albaranes de entrada
> -		    if picking.type in ('in',):
> -
> -                        for line in picking.move_lines:
> -
> -                            #Comprobamos si el lote se debe trasladar de ubicacion
> -                            #    SIM - Si tiene fecha activacion
> -                            #    ENLACE - Si tiene fecha activacion
> -                            if line.prodlot_id and line.prodlot_id.fecha_activacion:
> -
> -                                if not picking_internal_id:
> -                                    #Creamos albaran interno que englobara todos los traspasos
> -                                    vals = {
> -				        'origin': picking.name,
> -					'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> -					'move_type': 'direct',
> -					'invoice_state': 'none',
> -					'state': 'draft',
> -					'auto_picking': False,
> -					'type': 'internal',
> -					}
> -
> -				    picking_internal_id = self.create(cr, uid, vals)
> -
> -				#Traspaso de ubicacion
> -				product = line.prodlot_id.product_id
> -
> -				vals = {
> -				    'picking_id': picking_internal_id,
> -				    'product_id': product.id,
> -				    'name': '[' + product.default_code + '] ' + product.name,
> -				    'prodlot_id': line.prodlot_id.id,
> -				    'product_qty': 1,
> -				    'product_uos_qty': 1,
> -				    'product_uom': 1,
> -				    'location_id': stock_warehouse.lot_input_id.id,
> -				    'location_dest_id': stock_warehouse.lot_stock_id.id,
> -				    'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
> -				    'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> -				    'auto_validate': False,
> -				    'priority': '1',
> -				    'state': 'done',
> -				    }
> -
> -				stock_move_int_id = stock_move_obj.create(cr, uid, vals)
> -
> -			#Validamos albaran interno si se han traspasado lotes
> -			if picking_internal_id:
> -                            self.write(cr, uid, [picking_internal_id], {'state': 'done'})
> -
> +            break
> +        if stock_warehouse:
> +                for id in ids:
> +                    if id in res and 'delivered_picking' in res[id]:
> +                        picking_id = res[id]['delivered_picking']
> +                picking = self.browse(cr, uid, picking_id, context=context)
> +                internal_pick_id = None
> +                # Solo al validar albaranes de entrada
> +                if picking.type in ('in',):
> +                    for line in picking.move_lines:
> +                        # Comprobamos si el lote se debe trasladar de ubicacion
> +                        #    SIM - Si tiene fecha activacion
> +                        #    ENLACE - Si tiene fecha activacion
> +                        if (line.prodlot_id
> +                                and line.prodlot_id.fecha_activacion):
> +                            if not internal_pick_id:
> +                                # Creamos albaran interno
> +                                # que englobara todos los traspasos
> +                                curr_data = time.strftime('%Y-%m-%d %H:%M:%S')
> +                                vals = {'origin': picking.name,
> +                                        'date': curr_data,
> +                                        'move_type': 'direct',
> +                                        'invoice_state': 'none',
> +                                        'state': 'draft',
> +                                        'auto_picking': False,
> +                                        'type': 'internal',
> +                                        }
> +                                internal_pick_id = self.create(cr, uid,
> +                                                               vals,
> +                                                               context=context)
> +                    # Traspaso de ubicacion
> +                    product = line.prodlot_id.product_id
> +                    vals = {
> +                        'picking_id': internal_pick_id,
> +                        'product_id': product.id,
> +                        'name': '[%s] %s' % (product.default_code,
> +                                             product.name),
> +                        'prodlot_id': line.prodlot_id.id,
> +                        'product_qty': 1,
> +                        'product_uos_qty': 1,
> +                        'product_uom': 1,
> +                        'location_id': stock_warehouse.lot_input_id.id,
> +                        'location_dest_id': stock_warehouse.lot_stock_id.id,
> +                        'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
> +                        'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> +                        'auto_validate': False,
> +                        'priority': '1',
> +                        'state': 'done',
> +                        }
> +                    stock_move_int_id = stock_move_obj.create(cr, uid, vals)
> +                # Validamos albaran interno si se han traspasado lotes
> +                if internal_pick_id:
> +                    self.write(cr, uid, [internal_pick_id], {'state': 'done'})
>          return res
> -
> -stock_picking()
> 
> === added directory 'dos_picking_in_import/views'
> === renamed file 'dos_picking_in_import/stock_view.xml' => 'dos_picking_in_import/views/stock_view.xml'
> === modified file 'dos_product_additional_info/__openerp__.py'
> --- dos_product_additional_info/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ dos_product_additional_info/__openerp__.py	2014-06-19 15:57:57 +0000
> @@ -1,4 +1,4 @@
> -# -*- coding: utf-8 -*-
> +# -*- coding: utf-8 -*-
>  ##############################################################################
>  #
>  #    OpenERP, Open Source Management Solution
> 
> === modified file 'nayar_mysql_connect/__init__.py'
> --- nayar_mysql_connect/__init__.py	2014-06-11 10:23:47 +0000
> +++ nayar_mysql_connect/__init__.py	2014-06-19 15:57:57 +0000
> @@ -19,6 +19,6 @@
>  #
>  ##############################################################################
>  
> -import mysql_connect
> +from . import models
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === modified file 'nayar_mysql_connect/__openerp__.py'
> --- nayar_mysql_connect/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ nayar_mysql_connect/__openerp__.py	2014-06-19 15:57:57 +0000
> @@ -20,16 +20,12 @@
>  ##############################################################################
>  
>  {
> -    "name" : "Nayar MySql Connect",
> -    "version" : "1.0",
> -    "author" : "Nayar Systems",
> -    "category" : "Base",
> -    "website" : "",
> +    "name": "Nayar MySql Connect",
> +    "version": "1.0",
> +    "author": "Nayar Systems",
> +    "category": "Base",
> +    "website": "",
>      "description": "This module allows you connect to a MySql database.",
> -    "depends" : ['dos_mysql_connect'],
> -    "init_xml" : [],
> -    "update_xml" : [],
> -    "active": False,
> +    "depends": ['dos_mysql_connect'],
>      "installable": True
>  }
> -
> 
> === added directory 'nayar_mysql_connect/models'
> === renamed file 'nayar_mysql_connect/mysql_connect.py' => 'nayar_mysql_connect/models/mysql_connect.py'
> --- nayar_mysql_connect/mysql_connect.py	2014-06-11 10:23:47 +0000
> +++ nayar_mysql_connect/models/mysql_connect.py	2014-06-19 15:57:57 +0000
> @@ -19,14 +19,15 @@
>  #
>  ##############################################################################
>  
> -from osv import osv
> -
> -class mysql_connect(osv.osv):
> +from openerp.osv import orm
> +
> +
> +class MysqlConnect(orm.Models):
>      _inherit = 'mysql.connect'
>      db = None
>  
>      def open_connection(self, cr, uid):
> -        self.db = super(mysql_connect, self).open_connection(cr, uid)
> +        self.db = super(MysqlConnect, self).open_connection(cr, uid)
>          return self.db
>  
>      def query(self, query_str, param=None):
> @@ -51,8 +52,6 @@
>              return None
>  
>      def close_connection(self, db=None):
> -        res = super(mysql_connect, self).close_connection(self.db)
> +        res = super(MysqlConnect, self).close_connection(self.db)
>          self.db = None
>          return res
> -
> -mysql_connect()
> 


-- 
https://code.launchpad.net/~mikelarregi/avanzosc/nayar_mysql_connect/+merge/223770
Your team Avanzosc_security is subscribed to branch lp:~avanzosc-security-team/avanzosc/72horas.


References